|
| 1 | +## curl |
| 2 | +curl 为链接通讯各种服务器,各种协议的工具。php中单独整合了libcurl 库封装对象 curl。提供使用。 |
| 3 | +curl 支持http ftp 等协议。 |
| 4 | +curl_init 为初始化对话,其中支持设置个各参数 通过 curl_setopt 方法。 |
| 5 | +curl_setopt 第一个为会话资源变量,第二个参数为需要设置的参数,第三个为值 |
| 6 | +其中最常用的值为: |
| 7 | + 1,CURLOPT_URL, 访问的请求地址,需要正常加上http或者https 字符串,例如:http://curlsss.xxx.com |
| 8 | + 2, CURLOPT_POST 是否是http请求信息,如果是get 直接设置好 CURLOPT_URL的值为完整的请求值。 |
| 9 | + 3, curl 请求的时候因为浏览器测试访问时,默认转义了http中的特殊字符,当我们没有转义特殊字符,会导致服务器请求失败,而且nginx会导致400错误。400 请求无效。 |
| 10 | + 4, http_build_query 使用转义方法转义防止数据请求错误。 |
| 11 | + 5, 设置请求时间参数 CURLOPT_TIMEOUT 如果不设置会导致,执行脚本进程僵死,可通过ps aux 命令查看异常进程。 |
| 12 | + 6, 请求设置后需要执行 curl_exec 执行抓单,释放资源,curl_close. CURLOPT_RETURNTRANSFER true时候说明数据不打印,直接赋值变量 |
| 13 | + 7, 其中 http 特殊字符 :(+,空格,/ ? %# & )不论使用工具进行补单。 |
| 14 | +`<?php |
| 15 | + |
| 16 | +class CurlClient |
| 17 | +{ |
| 18 | + public function sendHttpRequest($url,$post=[]) |
| 19 | + { |
| 20 | + |
| 21 | + $curl = curl_init(); |
| 22 | + curl_setopt($curl, CURLOPT_URL, $url); |
| 23 | + curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)'); |
| 24 | + curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); |
| 25 | + curl_setopt($curl, CURLOPT_AUTOREFERER, 1); |
| 26 | + curl_setopt($curl, CURLOPT_REFERER, "http://XXX"); |
| 27 | + if( !empty($post) ) { |
| 28 | + curl_setopt($curl, CURLOPT_POST, 1); |
| 29 | + curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post)); |
| 30 | + } |
| 31 | + if($cookie) { |
| 32 | + curl_setopt($curl, CURLOPT_COOKIE, $cookie); |
| 33 | + } |
| 34 | + curl_setopt($curl, CURLOPT_HEADER, $returnCookie); |
| 35 | + curl_setopt($curl, CURLOPT_TIMEOUT, 30);// 平台仅仅支持 30s |
| 36 | + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); |
| 37 | + $data = curl_exec($curl); |
| 38 | + if (curl_errno($curl)) { |
| 39 | + return curl_error($curl); |
| 40 | + } |
| 41 | + curl_close($curl); |
| 42 | + $output = $data; |
| 43 | + |
| 44 | + return $output; |
| 45 | + } |
| 46 | +} |
| 47 | +` |
0 commit comments