用户名:  密码:   
您当前的位置:首页 > 网页设计 >  PHP > 

curl使用说明

上次修改时间: 2024-04-29 16:32:15      来源:网络总结      作者:钢铁长陈
上一页      路径:DSD\Learn\PHP相关\      下一页

curl使用说明

curl官网下载地址:https://curl.se/download.html
Windows10以下的系统自带curl
Win7及以下的系统需要手动安装,安装比较麻烦,安装后还要设置环境变量

多数新版的Linux也会自带curl,没有就需要下载安装了,
yum install curl

使用:
通过在cmd下执行
curl --help 查看有没有安装成功
curl --version //查看版本


crul的主要作用
1. 可以上传和下载文件
 curl -O http://example.com/file.zip //下载一个文件
 curl -o a.jpg http://www.baidu.com/b.jpg
2. 可以模拟Get和Post请求
 curl http://localhost:8080/GetUserInfo?id=1 //模拟get请求
 curl -H "Content-Type:application/json" -d '{"id":1,"name":"shone"}'; http://localhost:8080/queryinfo
  //-H后指定请求头,Content-Type:application/json表传送的是Json格式数据
  //-d后可以接多个值,如-d 'key1=val1&key2=val2', -d后还可接json格式数据,或指定文件作为参数,如-d "@test.txt"
3. 保存请求信息到cookies中
 curl -o page1.html -D cookie.txt http://www.baidu.com
4. 模拟指定浏览器来发起请求并保存cookies
 curl -A "Mozilla/4.0 (compatible;MSIE6.0; windows NT 5.0)" -o page1.html -D cookie.txt http://www.baidu.com
5. 携带cookes来发起请求
 curl -b cookie.txt http://www.baidu.com
 
PHP本身带有curl的扩展库,可通过PHP代码发送http请示,并处理返回数据等,示例: 
<?php
// 初始化一个 cURL 对象
$ch = curl_init();

// 设置 cURL 选项
curl_setopt($ch, CURLOPT_URL, "http://example.com/api");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// 执行 cURL 请求
$response = curl_exec($ch);

// 检查是否有错误发生
if (curl_errno($ch)) {
    echo 'Error: ' . curl_error($ch);
}

// 关闭 cURL 资源
curl_close($ch);

// 处理返回的数据
echo $response;
?>