質問

I am trying to write some php (new to php) that downloads a zip file from a remote server using curl and unzips it to a wordpress theme directory. The unzipping through php is failing reporting a result of 19 which from what I've found indicates no zip file. However when I check the directory, the zip file is there. If I unzip it I end up with a zip.cpgz file. I'm not sure if this is a problem with my code or if it's a way the server is sending the file. Here's my code. Thanks.

$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.");
}
役に立ちましたか?

解決

This should do it:

<?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.");
}
?>
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top