Question

I guys, i'm writting code to upload file, zip them and delete tmp file. But when i use unlink function, it do not remove all file, someone can explain to me why ?

Concerned php code :

$zip = new ZipArchive();
$target_path = 'img/products/';
$zip->open($target_path.$id_insert.'.zip', ZIPARCHIVE::CREATE);
$img_count = $_POST['count_file'];
for ($i = 1; $i <= $img_count; $i++){
    $temp = 'img'.$i;
    $file = $i.'-'.$id_insert.'-'.$_FILES[$temp]['name'];
    $path = $target_path.basename($file); 
    if(move_uploaded_file($_FILES[$temp]['tmp_name'], $path)) {
        $zip->addFile($path, basename($file));
        $files_to_delete[] = $path;
    }
} 
$zip->close();
foreach($files_to_delete AS $file){
    //unlink(dirname(__FILE__).'/'.$path);
}
Was it helpful?

Solution

foreach($files_to_delete AS $file){
    //unlink(dirname(__FILE__).'/'.$path);
}

In this block you should replace $path with $file since that's what you're foreaching them as. You get the error because after you unlink $path the first time, the file at $path is unlinked, but every other iteration of it tries to delete the same file (which is the last one assigned to the $path variable).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top