How to automatically unzip uploaded zip files with PHP
I wanted to upload a zip file with php script and unzip it within the server running PHP and linux. How to do it? i am documenting here about a solution to unpack uploaded zip files locally within the server with PHP.
well! it can be done in 3 ways. I
1. Using PHP exec command
2. suPHP (Alternative to PHPsuexec)
3. Get Pclzip class library. (create and extract ZIP files
4. Using Zziplib with PHP
I was successful with (3) option.
I tried the first option of using php exec command calling system level but it never worked for me and it just kept getting checkdir errors in my apache log.
[sourcecode language=”php”]
[/sourcecode]
checkdir error: cannot create ithemex
unable to process xtheme/images/mini-archive.gif.
checkdir error: cannot create ithemex
unable to process itheme-x/images/mini-archive.png.
Using suPHP
suPHP is a good method just because instead of apache running as nobody/apache it runs under user account ownership. Basically what this means that it will have no problem with file permissions for zip files. Another great advantage of suphp is security (it restricts local users reading php files).
Unfortunately i couldnt use suphp because it needs PHP to be running as CGI, but mine was apache module. I couldnt use suPHP
Using Pclzip class for Zip files
This method worked best for me. I uploaded a zip and it cleanly unpacked within my server. Just download the pclzip class library. Set the folder permissions to 755 where you are unpacking the files. It need not be 777. If that 755 doesnt work set the ownership and usergroup to apache or nobody.
Now upload a sample zip file test.zip and put the following code in php file
[sourcecode language=”php”]
extract(PCLZIP_OPT_PATH, ‘uploads’)) == 0) {
die(“Error : “.$archive->errorInfo(true));
}
echo “
"; var_dump($v_result_list); echo "
“;
?>
[/sourcecode]
PCLZIP_OPT_PATH, ‘uploads’ -> is the destination unzip folder (give it 777 or 755 permissions)
Just the php script and you will see error codes if any. In my case it worked perfectly fine unpacking the zip file. Refer to Pclzip documentation.
Note: You must have Zlib support installed for this script to work.
To install Zlib with PHP just do yum install zlib zip php-zip
Dont forget to check apache logs to trace the exact error!