Cross Vander
Cross Vander

Reputation: 2177

PHP Unzip File and Extract Files On By One

I want to create a PHP code to unzip a file, then extract it to a folder. I know to extract all the file inside the zip, but, I want to extract it one by one, because I want to check each file need to be below 1MB

Here's my code:

$zip = new ZipArchive();
for ($i=0; $i<$zip->numFiles;$i++) 
    {
        $current = $zip->statIndex($i);
        if($current["size"] > (1*1024*1024))
        {
            printf("%s (size: %d bytes) is too big, failed to upload this photo<br>", $current["name"], $current["size"]);
        }
        else
        {
            $location = 'picture/'.$current['name'];
            if(move_uploaded_file($current['name'], $location))
                printf("%s successfully uploaded<br>", $current["name"]);
            else
                printf("Failed <br />");
        }
    }

I always failed on these line code : if(move_uploaded_file($current['name'], $lokasi)) it always return Failed, and I know $current['name'] is only the file name, not the file inside the zip. Anyone know how to get file inside the zip (one by one)?

Upvotes: 2

Views: 773

Answers (2)

Cross Vander
Cross Vander

Reputation: 2177

Finally, from this link I read, so I choose to extract the file with array method. Here's my end code for my problem:

for ($i=0; $i<$zip->numFiles;$i++) 
        {
            $current = $zip->statIndex($i);
            if($current["size"] > (1*1024*1024))
            {
                printf("%s (size: %d bytes) is too big, failed to upload this image!<br>", $current["name"], $current["size"]);
            }
            else
            {
                $location = $folder.'/'.$folder2.'/';
                if($zip->extractTo($location , array($current['name'])))
                    printf("%s successfully uploaded<br>", $current["name"]);
                else
                    printf("Failed <br />");
            }
        }

Upvotes: 1

VolkerK
VolkerK

Reputation: 96199

http://docs.php.net/move_uploaded_file says:

This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism)
The zip archive file may be uploaded. But the files your script extracts from it are not.
And getting the stat entry doesn't actually extract the data to the local file system. For that you might be interested in ZipArchive::extractTo and/or ZipArchive::getStream

Upvotes: 0

Related Questions