I have a simple bit of PHP code which copies a zip file from a remote url to the server, and then extracts it into another folder.
function extract_remote_zip($new_file_loc, $tmp_file_loc, $zip_url) {
echo 'Copying Zip to local....<br>';
//copy file to local
if (!copy($zip_url, $tmp_file_loc)) {
echo "failed to copy zip from".$zip_url."...";
}
//unzip
$zip = new ZipArchive;
$res = $zip->open($tmp_file_loc);
if ($res === TRUE) {
echo 'Extracting Zip....<br>';
if(! $zip->extractTo($new_file_loc)){
echo 'Couldnt extract!<br>';
}
$zip->close();
echo 'Deleting local copy....<br>';
unlink($tmp_file_loc);
return 1;
} else {
echo 'Failed to open tmp zip!<br>';
return 0;
}
}
It works perfectly with one URL from Awin and downloads and extracts the correct 600kb zip, but with another from Webgains it just downloads a Zip file with size 0 bytes. I'm guessing the download is getting corrupted somewhere?
When I visit the URL on my browser it downloads the zip perfectly (the size is about 3mb). I just can't get it to download with PHP.
Please help!
Since you didn't provide the problem URL, I can't say for sure, but you are likely encountering an issue with the method copy uses to read the file. Doing a direct curl call should resolve this.
Try the below:
function file_get_contents_curl( $url ) {
$ch = curl_init();
curl_setopt( $ch, CURLOPT_AUTOREFERER, TRUE );
curl_setopt( $ch, CURLOPT_HEADER, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, TRUE );
$data = curl_exec( $ch );
if ( curl_errno( $ch ) <> FALSE ) {
echo "ERROR at line " . __LINE__ . " in file_get_contents_curl: error number: " . curl_errno( $ch ) . ' error : ' . curl_error( $ch ) . " url: $url";
return FALSE;
}
curl_close( $ch );
return $data;
}
function extract_remote_zip($new_file_loc, $tmp_file_loc, $zip_url) {
echo 'Copying Zip to local....<br>';
// read the zip
if ( $zip_str = file_get_contents_curl( $zip_url ) ) {
// write the zip to local
if ( !file_put_contents( $tmp_file_loc, $zip_str ) ) {
echo "failed to write the zip to: " . $zip_url;
return FALSE;
}
} else {
echo "failed to read the zip from: " . $zip_url;
return FALSE;
}
//unzip
$zip = new ZipArchive;
$res = $zip->open($tmp_file_loc);
if ($res === TRUE) {
echo 'Extracting Zip....<br>';
if(! $zip->extractTo($new_file_loc)){
echo 'Couldnt extract!<br>';
}
$zip->close();
echo 'Deleting local copy....<br>';
unlink($tmp_file_loc);
return 1;
} else {
echo 'Failed to open tmp zip!<br>';
return 0;
}
}