如何通过file_get_content或curl正确获取文件

时间:2017-10-16 15:45:52

标签: php curl

我试图通过Icecat下载文件。该文件需要下载访问权限。

我的问题是:

  • file_get_content没有下载文件。我的目录位于777,路径正确。
  • 如果我在目录中插入文档,则文件不会解压缩。

    public function getIceCatFile() {
    
          set_time_limit (0);
    
          $url = 'https://data.Icecat.biz/export/freexml/EN/daily.index.xml.gz';
    
          $context = stream_context_create(array('http' => array( 'header'  => "Authorization: Basic " . base64_encode($this->username . ":" . $this->password) )));
    
          if ($this->checkDirectoryIceCat() === true) {
    
             // does'nt download the file inside the server directory    
            file_get_contents($url, true, $context);
    
            $file = $this->IceCatDirectory . 'daily.index.xml.gz';
    
    
            if (is_file($file)) {
              $zip = new \ZipArchive;
    
              // error failed same if I include the file inside the directory    
              $icecat_file = $zip->open($this->IceCatDirectory . 'files.index.xml.gz');
    
              if ($icecat_file === true) {
                $zip->extractTo($icecat_file);
                $zip->close();
                echo 'file downloaded and unzipped';
              } else {
                echo 'failed';
              }
            } else {
              echo 'error no file found in ' . $file;
            }
          }
        }
    

1 个答案:

答案 0 :(得分:0)

尝试使用PHP Curl下载具有用户名密码身份验证的文件,

$localfile = fopen($file_store_locally, 'wb'); // open with write enable
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, $localfile);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "username:password"); // see here for auth
curl_exec($ch);
curl_close($ch);
fclose($localfile); //store file data to local file