HOWTO · PHP

在 PHP 中使用 CURL 下載檔案

本教程演示如何使用 cURL 庫在 PHP 中下載檔案。

本頁內容

-output-o 命令用於在 PHP 中下載帶有 cURL 的檔案。

我們可以通過提供檔案的 URL 來下載帶有 cURL 的檔案。cURL 庫在 PHP 中有多種用途。

使用 cURL 從 PHP 中的給定 URL 下載檔案

首先,確保在你的 PHP 中啟用了 cURL。你可以通過執行 phpinfo() 並從 php.ini 檔案啟用它來檢查它。

我們正在嘗試將檔案從本地伺服器下載到本地伺服器本身。

<?php
// File download information
set_time_limit(0); // if the file is large set the timeout.
$to_download = "http://localhost/delftstack.jpg"; // the target url from which the file will be downloaded
$downloaded = "newDelftstack.jpg"; // downloaded file url

// File Handling

$new_file = fopen($downloaded, "w") or die("cannot open" . $downloaded);

// Setting the curl operations
$cd = curl_init();
curl_setopt($cd, CURLOPT_URL, $to_download);
curl_setopt($cd, CURLOPT_FILE, $new_file);
curl_setopt($cd, CURLOPT_TIMEOUT, 30); // timeout is 30 seconds, to download the large files you may need to increase the timeout limit.

// Running curl to download file
curl_exec($cd);
if (curl_errno($cd)) {
  echo "the cURL error is : " . curl_error($cd);
} else {
  $status = curl_getinfo($cd);
  echo $status["http_code"] == 200 ? "The File is Downloaded" : "The error code is : " . $status["http_code"] ;
  // the http status 200 means everything is going well. the error codes can be 401, 403 or 404.
}

// close and finalize the operations.
curl_close($cd);
fclose($new_file);
?>

輸出:

使用 CURL 下載 PHP 檔案

輸出顯示程式碼可以從給定的 URL 下載檔案。要下載大檔案,我們可以增加超時限制。