在 PHP 中使用 CURL 下载文件

Sheeraz Gul 2024年2月15日
在 PHP 中使用 CURL 下载文件

-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 下载文件。要下载大文件,我们可以增加超时限制。

作者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook