簡體   English   中英

從url下載文件到目錄

[英]Download file from url to directory

嘗試通過下載文件進行搜索。 我找不到所需的答案。 我正在嘗試將文件從 url 下載到 php 中的特定目錄/文件夾。 我正在使用下面的代碼。

foreach($files as $file) {

     $url  = 'http://www.example.com/'.$file.'';
     $path = '/project/'.$file.'';

     $fp = fopen($path, 'w');

     if($fp) {         
     $ch = curl_init($url);
     curl_setopt($ch, CURLOPT_FILE, $fp);

     $data = curl_exec($ch);

     curl_close($ch);
     fclose($fp);       
  }
}

當我運行 php 文件時。 它顯示錯誤:

Warning: fopen(/project/GEN1.mp4): failed to open stream: No such file or directory.

Warning: curl_setopt(): supplied argument is not a valid File-Handle resource in.

Warning: fclose() expects parameter 1 to be resource, boolean given 

應該是這樣的:

foreach($files as $file) {

     $url  = 'http://www.example.com/'.$file.'';
     $path = '/project/'.$file.'';

     $ch = curl_init($url);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);

     $data = curl_exec($ch);

     curl_close($ch);

     $fp = fopen($path, 'wb');
     fwrite($fp, $data);
     fclose($fp);
}
  • 錯誤Warning: fopen(/project/GEN1.mp4): failed to open stream: No such file or directory. 告訴您該文件不存在,因此您需要手動或使用fopen調用創建它,請查看此處以了解可能的模式。

  • 錯誤Warning: fclose() expects parameter 1 to be resource, boolean given意味着您將布爾變量傳遞給需要資源的fclose函數。

  • 錯誤Warning: curl_setopt(): supplied argument is not a valid File-Handle resource in.意味着您需要將Warning: curl_setopt(): supplied argument is not a valid File-Handle resource in.傳遞給函數。

嘗試使用另一個 PHP 函數file_get_contents而不是 CURL。 更多信息在這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM