Skip to content
PHP Logo

What are some common pitfalls when working with file manipulation in PHP, and how can they be avoided when creating zip files from folders?

One common pitfall when working with file manipulation in PHP is not properly handling file paths and permissions. When creating zip files from folders, ensure that you have the necessary permissions to read the files and write the zip file. Additionally, be mindful of file paths when adding files to the zip archive to avoid errors.

php
// Ensure proper permissions and handle file paths correctly when creating zip files from folders
$zip = new ZipArchive();
$zipFileName = 'archive.zip';

if ($zip->open($zipFileName, ZipArchive::CREATE) === TRUE) {
    $folderPath = 'path/to/folder';
    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($folderPath));

    foreach ($files as $file) {
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($folderPath) + 1);

        if (is_file($filePath)) {
            $zip->addFile($filePath, $relativePath);
        }
    }

    $zip->close();
    echo 'Zip file created successfully.';
} else {
    echo 'Failed to create zip file.';
}