当前位置: 移动技术网 > IT编程>开发语言>PHP > curl模拟http请求

curl模拟http请求

2018年11月22日  | 移动技术网IT编程  | 我要评论
简介 cURL的 官方定义 为: ,即 使用URL语法规则来传输数据的命令行工具 。 PHP 支持 Daniel Stenberg 创建的 libcurl 库,能够连接通讯各种服务器、使用各种协议。libcurl 目前支持的协议有 http、https、ftp、gopher、telnet、dict、 ...

简介

curl的官方定义为:curl is a command line tool for transferring data with url syntax,即使用url语法规则来传输数据的命令行工具

php 支持 daniel stenberg 创建的 libcurl 库,能够连接通讯各种服务器、使用各种协议。libcurl 目前支持的协议有 http、https、ftp、gopher、telnet、dict、file、ldap。 libcurl 同时支持 https 证书、http post、http put、 ftp 上传(也能通过 php 的 ftp 扩展完成)、http 基于表单的上传、代理、cookies、用户名+密码的认证。

概念

在php中使用curl

图示:

curl模拟get请求

/**
 * get方式发送curl请求
 * @param string $url    请求服务器地址
 * @param array $header  请求头数据
 * @param int $timeout   超时时间
 * @return mixed
 * @author itbsl
 */
function curl_get($url, $header=[], $timeout=30) {

    //初始化curl
    $curl = curl_init();

    //设置curl(请求的服务器地址)
    //参数1: curl资源
    //参数2: 配置项名称
    //参数3: 配置项的值
    curl_setopt($curl, curlopt_url, $url);

    //跳过安全证书验证
    curl_setopt($curl, curlopt_ssl_verifyhost, false);  // 从证书中检查ssl加密算法是否存在
    curl_setopt($curl, curlopt_ssl_verifypeer, false);  // 跳过证书检查

    //设置获取的信息以文件流的形式返回,而不是直接输出
    curl_setopt($curl, curlopt_returntransfer, true);

    curl_setopt($curl, curlopt_httpheader, $header);

    curl_setopt($curl, curlopt_timeout, $timeout);

    //发出请求
    $result = curl_exec($curl);

    //关闭curl资源
    curl_close($curl);

    return $result;
}

curl模拟post请求

/**
 * post方式发送curl请求
 * @param string $url   请求的服务器地址
 * @param array $data   要发送的数据
 * @param array $header 请求头数据
 * @param int $timeout  超时时间
 * @return mixed
 * @author itbsl<itbsl@foxmail.com>
 */
function curl_post($url, $data=[], $header=[], $timeout=30) {

    //初始化curl
    $curl = curl_init();

    //设置curl(请求的服务器地址)
    //参数1: curl资源
    //参数2: 配置项名称
    //参数3: 配置项的值
    curl_setopt($curl, curlopt_url, $url);

    //跳过安全证书验证
    curl_setopt($curl, curlopt_ssl_verifyhost, false);  // 从证书中检查ssl加密算法是否存在
    curl_setopt($curl, curlopt_ssl_verifypeer, false);  // 跳过证书检查

    //设置获取的信息以文件流的形式返回,而不是直接输出
    curl_setopt($curl, curlopt_returntransfer, true);

    curl_setopt($curl, curlopt_httpheader, $header);

    //设置请求方式为post请求
    curl_setopt($curl, curlopt_post, true);

    //设置post方式提交时携带的数据
    curl_setopt($curl, curlopt_postfields, $data);

    curl_setopt($curl, curlopt_timeout, $timeout);

    //发出请求
    $result = curl_exec($curl);

    //关闭curl资源
    curl_close($curl);

    return $result;
}

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网