从curl下载zip文件会在解压缩后生成cpgz文件

时间:2014-01-23 17:02:29

标签: php curl ziparchive

我正在尝试编写一些php(新到php),它使用curl从远程服务器下载zip文件并将其解压缩到wordpress主题目录。通过php解压缩失败报告19的结果,从我发现的结果表明没有zip文件。但是,当我检查目录时,zip文件就在那里。如果我解压缩它,我最终得到一个zip.cpgz文件。我不确定这是否是我的代码的问题,或者它是服务器发送文件的方式。这是我的代码。感谢。

$dirpath = dirname(__FILE__);
$themepath = substr($dirpath, 0, strrpos($dirpath, 'wp-content') + 10)."/themes/";
//make call to api to get site information
$pagedata = file_get_contents("https://ourwebsite/downloadzip.php?industryid=$industry");
$jsondata = json_decode($pagedata);

$fileToWrite = $themepath.basename($jsondata->zip_file_url);

$zipfile = curl_init();
curl_setopt($zipfile, CURLOPT_URL, $jsondata->zip_file_url);
curl_setopt($zipfile, CURLOPT_HEADER, 1);
curl_setopt($zipfile, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($zipfile, CURLOPT_BINARYTRANSFER, 1);
$file = curl_exec($zipfile);

if ($file == FALSE){
    echo "FAILED";
}else{
    $fileData = fopen($fileToWrite,"wb");
    fputs($fileData,$file);
}
curl_close($zipfile);

if (file_exists($fileToWrite)){
    $zip = new ZipArchive;
    $res = $zip->open($fileToWrite);
    if ($res === TRUE)
    {
        $zip->extractTo($themepath);
        $zip->close();
        echo 'Theme file has been extracted.';
    }
    else
    {
        echo 'There was a problem opening the theme zip file: '.$res;
    }
}
else{
    echo("There was an error downloading, writing or accessing the theme file.");
}

1 个答案:

答案 0 :(得分:-2)

这应该这样做:

<?php
set_time_limit(0);

$industry = "industryid"; //replace this
$url = "https://ourwebsite/downloadzip.php?industryid=$industry";
$tmppath = "/tmp/tmpfile.zip";
$themdir = "/your/path/wp-content/themes/";
$fp = fopen ($tmppath, 'w+');//This is the file where we save the zip file

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_FILE, $fp); // write curl response to file
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch); // get curl response
curl_close($ch);
fclose($fp);


if (file_exists($tmppath)){
    $zip = new ZipArchive;
    $res = $zip->open($tmppath);
    if ($res === TRUE)
    {
        $zip->extractTo($themdir);
        $zip->close();
        echo 'Theme file has been extracted.';
    }
    else
    {
        echo 'There was a problem opening the theme zip file: '.$res;
    }
}
else{
    echo("There was an error downloading, writing or accessing the theme file.");
}
?>