php curl数据传输神器

一、curl的概念:

curl (Client Url Library Functions)  

定义: curl is a command  line tool for transfering data with url syntax

使用 URL 语法传输数据的命令行工具

CURL是访问网络资源的工具

二、curl的使用场景

1、访问网页资源 (例如:编写网页爬虫)

2、访问WebService 数据接口资源 (例如:动态获取数据接口,天气,号码归属地等)

3、下载FTP服务器里面的文件资源等 (例如:下载FTP服务器里面的文件)

所有的网络资源都可以用CRUL访问和下载到

三、在PHP中使用cUrl

windows: 在cmd中执行命令

 php -i  // 所有php的设置都会被打印出来, i 代表 infomations的意思

 然后 右键 -> 编辑 -> 查找->输入 cUrl ,可以看到类似如下信息:

说明cUrl 可用,且版本为 7.25.0

Linux:输入命令:

php -i | grep cUrl

 几乎所有的工具都需要经历:

去初始化它 -> 去使用它 -> 去关闭它

curl也是这样。

curl_exec() 把发送请求和接收数据都一起做了。

四、使用示例

1、一个最简单的 curl 示例(编写一个网页爬虫,获取百度首页的 html)

$curl = curl_init('www.baidu.com');  // 初始化
curl_exec($curl);  // 执行
curl_close($curl); // 关闭

 这样子会得到百度首页的 html 代码,并且会直接输出,用浏览器显示的话,和输入www.baidu.com显示的内容一模一样。

2、对网页代码做一些修改(例如将百度改为慕课)

$url = 'www.baidu.com';
$curl = curl_init();  // 初始化 curl
curl_setopt($curl,CURLOPT_URL,$url); // 设置访问的 url
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true); // CURLOPT_RETURNTRANSFER 设为 tuue,表示执行结果不直接打印出来,以便对结果做一些后续的处理
$output = curl_exec($curl); //执行
curl_close($curl); // 关闭 curl
str_replace('百度','慕课',$output); // 对返回结果做替换

 

 3、访问 WebService 数据接口资源(查询深圳的天气)

使用的天气接口为 http://www.webxml.com.cn/WebServices/WeatherWebService.asmx ,虽说是免费的,但是有使用次数限制

$url = 'http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getWeatherbyCityName';
$data = 'theCityName=深圳';  // 多个参数用 & 连接
$httpHeader = array(
    'Content-type: application/x-www-form-urlencoded;charset=utf-8',  // 数据被编码为名称/值对的形式,字符集为utf-8
    'content-length: '.strlen($data), // post发送都需要指定一下数据的长度
);
$curl = curl_init();  // 初始化 curl
curl_setopt($curl,CURLOPT_URL,$url); // 设置访问的 url
curl_setopt($curl,CURLOPT_HEADER,0); // 不设置 header
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true); // CURLOPT_RETURNTRANSFER 设为 tuue,表示执行结果不直接打印出来,以便对结果做一些后续的处理
// post请求,下面这 3 行是重点
curl_setopt($curl,CURLOPT_POST,true);  // 通过 post 的方式请求
curl_setopt($curl,CURLOPT_POSTFIELDS,$data); // 设置请求的参数
curl_setopt($curl,CURLOPT_HTTPHEADER,$httpHeader); // 设置 httpheader
curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); //声明浏览器用于 HTTP 请求的用户代理头的值。简单来说,就是“声明用什么浏览器来打开目标网页”,当抓取网页资源不能正确返回结果时,可以加入这一项
$output = curl_exec($curl); //执行
if(! curl_errno($curl)){  // 如果执行的过程中出错了,将错误打印出来
    echo $output; 
    //$info = curl_getinfo($curl);  // 返回的是数组格式
    //print_r($info);
}else{
    echo 'curl error:'.curl_error($curl);
}
curl_close($curl); // 关闭 curl

 CURLOPT_HEADER 和 CURLOPT_HTTPHEADER 的区别:

简单来说 CURLOPT_HEADER是设置输出的,CURLOPT_HTTPHEADER是设置输入的

4、从ftp服务器下载文件

/*
 * 从FTP服务器下载一个文件到本地
 * 假如服务器地址为:ftp:192.168.1.100/downloaddemo.txt
 * */
$url = 'ftp:192.168.1.100/downloaddemo.txt';
$curl = curl_init();  // 初始化 curl
curl_setopt($curl,CURLOPT_URL,$url); // 设置访问的 url
curl_setopt($curl,CURLOPT_HEADER,0); // 不设置 header
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true); // CURLOPT_RETURNTRANSFER 设为 tuue,表示执行结果不直接打印出来,以便对结果做一些后续的处理
curl_setopt($curl,CURLOPT_TIMEOUT,300); // 设置下载超时时间
curl_setopt($curl,CURLOPT_USERPWD,'test_username:test_pwd'); // 设置登录ftp服务器的用户名和密码
// 文件下载下来后保存的位置
$outfile = fopen('dest.txt','wb');
curl_setopt($curl,CURLOPT_FILE,$outfile);
$output = curl_exec($curl); //执行
if(! curl_errno($curl)){  // 如果执行的过程中出错了,将错误打印出来
    echo $output;
}else{
    echo 'curl error:'.curl_error($curl);
}
curl_close($curl); // 关闭 curl

 5、将本地文件上传至 ftp 服务器

/*
 * 将本地文件上传至 ftp 服务器
 * 假如服务器地址为:ftp:192.168.1.100/server_upload_file.txt
 * */
$url = 'ftp:192.168.1.100/server_upload_file.txt';
$localfile = 'localfile.txt';
$fp = fopen($localfile,'r');
$curl = curl_init();  // 初始化 curl
curl_setopt($curl,CURLOPT_URL,$url); // 设置访问的 url
curl_setopt($curl,CURLOPT_HEADER,0); // 不设置 header
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true); // CURLOPT_RETURNTRANSFER 设为 tuue,表示执行结果不直接打印出来,以便对结果做一些后续的处理
curl_setopt($curl,CURLOPT_TIMEOUT,300); // 设置下载超时时间
curl_setopt($curl,CURLOPT_USERPWD,'test_username:test_pwd'); // 设置登录ftp服务器的用户名和密码
// 以下三行为文件上传的关键设置
curl_setopt($curl,CURLOPT_UPLOAD,1);   // 文件上传的操作,CURLOPT_UPLOAD 必须设为1
curl_setopt($curl,CURLOPT_INFILE,$fp); // 指定上传的文件(所打开文件的句柄)
curl_setopt($curl,CURLOPT_INFILESIZE,filesize($localfile)); // 告诉 curl 上传文件的大小,让 curl 知道大概需要上传多长时间
$output = curl_exec($curl); //执行
if(! curl_errno($curl)){  // 如果执行的过程中出错了,将错误打印出来
    echo 'uploaded successfully';
}else{
    echo 'curl error:'.curl_error($curl);
}
curl_close($curl); // 关闭 curl

 

附:一个 curl 的常规方法:

    /**
     * @Purpose :   curl 方法
     * @Params  :   string      $url        访问地址
     *          :   boole       $https      是否为https方式,true代表是
     *          :   string      $method     是get还是post
     *          :   array/json  $data       是传键值对的数组还是传json,跟header的设置有关
     *          :   array       $httpHeader 当为post方式访问的时候,需要设置header
     * @Author  :   daicr
     * @Time    :   2018-11-20
     */
    public function httpCurl($url,$https=false,$method='get',$data,$httpHeader)
    {
        $curl = curl_init();  // 初始化 curl
        curl_setopt($curl,CURLOPT_URL,$url); // 设置访问的 url
        curl_setopt($curl,CURLOPT_HEADER,0); // 不设置 输出header
        curl_setopt($curl,CURLOPT_RETURNTRANSFER,true); // CURLOPT_RETURNTRANSFER 设为 tuue,表示执行结果不直接打印出来,以便对结果做一些后续的处理
        curl_setopt($curl, CURLOPT_VERBOSE , true); // CURL报告每一件意外的事情,设置这个选项为一个非零值

        //http 基础权限,当需要传账号和密码时使用
        //curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
       // curl_setopt($curl, CURLOPT_USERPWD, "admin:123456");

        // 若为 https ,不验证
        if($https){
            curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
            curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);
        }
        if($method == 'post'){
            curl_setopt($curl,CURLOPT_POST,true);  // 通过 post 的方式请求
            curl_setopt($curl,CURLOPT_POSTFIELDS,$data); // 设置请求的参数
            curl_setopt($curl,CURLOPT_HTTPHEADER,$httpHeader); // 设置 httpheader
            //curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); //声明浏览器用于 HTTP 请求的用户代理头的值。简单来说,就是“声明用什么浏览器来打开目标网页”,当抓取网页资源不能正确返回结果时,可以加入这一项
        }
        curl_setopt($curl, CURLOPT_TIMEOUT,30);   // curl的最长执行时间为 30s
        $output = curl_exec($curl); //执行
        if(! curl_errno($curl)){  // 如果执行的过程中出错了,将错误打印出来
            return $output;
        }else{
            $curlError = 'curl error: ' . curl_error($curl);
            $this->writeLog($curlError,$this->logDir,$this->fileName); // 写日志的方法见 https://www.cnblogs.com/chrdai/p/7082146.html
            return false;
        }
        curl_close($curl); // 关闭 curl
    }

 

如果是 post 上传,通常需要设置 httpheader

常用的 httphader有:

第一种:用键值对的方式上传:

$httpHeader = array(
    'Content-type: application/x-www-form-urlencoded;charset=utf-8',  // 数据被编码为名称/值对的形式,字符集为utf-8
    'content-length: '.strlen($data), // post发送都需要指定一下数据的长度
);

第二种:用json的格式上传:

$httpHeader = array(
    'Content-Type: application/json; charset=utf-8', // 设置为json的格式
    'content-length: '.strlen($data), // post发送都需要指定一下数据的长度
);

更详细的关于 crul 的教学,大家可以参看以下这个视频讲解:https://www.imooc.com/video/2034

如有转载,请注明出处:http://www.cnblogs.com/chrdai/p/8974059.html

 

posted @ 2018-04-30 17:14  Chrdai  阅读(507)  评论(0编辑  收藏  举报