How can the ZipArchive class in PHP be effectively used to create archives that maintain folder structures when extracted on different operating systems?

When creating ZIP archives in PHP using the ZipArchive class, it's important to set the correct flag to ensure that the folder structure is maintained when extracted on different operating systems. This can be achieved by using the ZipArchive::addFile() method with the ZIPARCHIVE::CREATE and ZIPARCHIVE::OVERWRITE flags.

$zip = new ZipArchive();
$zipFileName = 'archive.zip';

if ($zip->open($zipFileName, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('path/to/directory'));
    
    foreach ($files as $file) {
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen('path/to/directory') + 1);
        $zip->addFile($filePath, $relativePath);
    }
    
    $zip->close();
    echo 'Archive created successfully';
} else {
    echo 'Failed to create archive';
}