常用操作
初始化
$url = 'https://apee.top';
$curl = curl_init($url);
设置请求方式
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
设置 POST 数据
// 关联数组
$data = ['key' => 'value', 'key2' => 'value2'];
// URL 参数
$data = 'key=value&key2=value2';
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
设置请求头
$headers = ['Content-Type: text.plain'];
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
设置登录的账号密码
curl_setopt($curl, CURLOPT_USERPWD, 'username:password');
将创建一个 Authorization 请求头,如:
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ
其实是对 username:password
进行 Base64 编码得到。
设置响应输出到变量中
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
默认情况下,响应内容会输出到命令行,而不是变量。设置为 true
后,可以在响应成功后获得一个字符串。
设置代理
curl_setopt($curl, CURLOPT_PROXY, 'http://127.0.0.1:7890');
发送请求
$response = curl_exec($curl);
echo $response;
关闭请求
curl_close($curl);
代码实例
简单 GET 请求
<?php
$curl = curl_init('https://apee.top');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
echo $response;
POST 请求
<?php
$curl = curl_init('https://apee.top/example.php');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, 'username=apee&password=123456');
$response = curl_exec($curl);
curl_close($curl);
echo $response;
获取响应头
<?php
$curl = curl_init('http://iapp.apee.top');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
$response = curl_exec($curl);
curl_close($curl);
$size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $size);
echo $header;
获取重定向后的地址
<?php
$curl = curl_init('https://web.dxj.mobi');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
$new_url = curl_getinfo($curl, CURLINFO_REDIRECT_URL);
curl_close($curl);
echo $new_url;
获取 Set-Cookie 内容
<?php
$curl = curl_init('http://iapp.apee.top/login.php');
curl_setopt($curl, CURLOPT_POSTFIELDS, "password=12345678&action=login");
curl_setopt($curl, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_exec($curl);
curl_close($curl);
Cookie 将保存到 cookie.txt
文件中,示例:
# Netscape HTTP Cookie File
# https://curl.se/docs/http-cookies.html
# This file was generated by libcurl! Edit at your own risk.
iapp.apee.top FALSE / FALSE 1704800235 password 666666
发表评论 取消回复