<?php
$url = "http://localhost/1.txt"; // 示例下载链接
$localFile = "iso_8859-1.txt"; // 替换为有效路径
$ch = curl_init($url);
$fp = fopen($localFile, 'wb');
// 设置 cURL 选项
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
// 添加 User-Agent
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36');
if (curl_exec($ch) === false) {
echo 'cURL Error: ' . curl_error($ch);
} else {
echo 'File downloaded successfully.';
}
curl_close($ch);
fclose($fp);
?>
代码分解
设置下载链接和本地文件名:
php
$url = “http://localhost/1.txt”; // 示例下载链接
$localFile = “iso_8859-1.txt”; // 替换为有效路径
$url 变量指定了要下载的文件的 URL,这里是本地服务器上的 1.txt 文件。
$localFile 变量定义了下载后保存的文件名,这里是 iso_8859-1.txt。
初始化 cURL 会话:
php
c
h
=
c
u
r
l
i
n
i
t
(
ch = curl_init(
ch=curlinit(url);
curl_init() 函数用于初始化一个 cURL 会话,并为其指定目标 URL。
打开文件句柄以写入:
php
f
p
=
f
o
p
e
n
(
fp = fopen(
fp=fopen(localFile, ‘wb’);
fopen() 函数以写入二进制(‘wb’)模式打开本地文件,以便可以将下载的内容写入该文件。如果文件已存在,将会被覆盖。
设置 cURL 选项:
php
curl_setopt($ch, CURLOPT_FILE,
f
p
)
;
c
u
r
l
s
e
t
o
p
t
(
fp); curl_setopt(
fp);curlsetopt(ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt(
c
h
,
C
U
R
L
O
P
T
T
I
M
E
O
U
T
,
60
)
;
c
u
r
l
s
e
t
o
p
t
(
ch, CURLOPT_TIMEOUT, 60); curl_setopt(
ch,CURLOPTTIMEOUT,60);curlsetopt(ch, CURLOPT_FILE, $fp):将下载的内容写入之前打开的文件句柄
f
p
。
c
u
r
l
s
e
t
o
p
t
(
fp。 curl_setopt(
fp。curlsetopt(ch, CURLOPT_FOLLOWLOCATION, true):设置 cURL 跟随 HTTP 重定向。
curl_setopt($ch, CURLOPT_TIMEOUT, 60):设置请求超时时间为 60 秒。
添加 User-Agent 头:
php
curl_setopt($ch, CURLOPT_USERAGENT, ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36’);
有些网站或者服务器可能会检查请求中的 User-Agent 字段,以识别请求来源。这行代码设置了一个常见的浏览器 User-Agent,以模拟来自真实浏览器的请求。
执行 cURL 请求:
php
if (curl_exec(KaTeX parse error: Expected '}', got 'EOF' at end of input: …' . curl_error(ch);
} else {
echo ‘File downloaded successfully.’;
}
curl_exec(
c
h
)
执行
c
U
R
L
请求。返回
f
a
l
s
e
表示出现错误,此时通过
c
u
r
l
e
r
r
o
r
(
ch) 执行 cURL 请求。返回 false 表示出现错误,此时通过 curl_error(
ch)执行cURL请求。返回false表示出现错误,此时通过curlerror(ch) 获取错误信息并输出。
如果没有错误,输出成功消息。
关闭 cURL 会话和文件:
php
curl_close(
c
h
)
;
f
c
l
o
s
e
(
ch); fclose(
ch);fclose(fp);
curl_close(
c
h
)
关闭
c
U
R
L
会话,释放资源。
f
c
l
o
s
e
(
ch) 关闭 cURL 会话,释放资源。 fclose(
ch)关闭cURL会话,释放资源。fclose(fp) 关闭文件句柄,确保数据正确写入并释放系统资源。
curl -L -o my66.txt “http://localhost/1.txt”
curl:
这是一个用于发送请求和获取数据的命令行工具,通常用于下载文件或与网络服务器进行交互。
-L:
这个选项指示 curl 跟随 HTTP 重定向。如果请求的 URL 被重定向(例如,通过 301 或 302 状态码),curl 会自动跟随重定向到新的 URL。
-o my66.txt:
-o 选项用于指定输出文件的名称。在这个例子中,下载的内容将被保存为 my66.txt 文件。如果该文件已经存在,它将被覆盖。
“http://localhost/1.txt”:
这是要访问的 URL。在这个例子中,它指的是本地机器上的一个文件 1.txt。localhost 指的是你自己计算机的网络地址,通常在 Web 开发期间使用,用于测试本地运行的应用程序或服务。