七夕啦,做为开发,妹子没得撩就“撩”下服务器吧,妹子有得撩的同窗那就左拥妹子右抱服务器吧,何况妹子是要礼物的,服务器又不用。好啦,长话短说再长说,祭出今天的工具——CURL(Client URL Library),固然今天以PHP的方式来使用这件工具。php
PHP supports libcurl, a library created by Daniel Stenberg, that allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.react
这是PHP对于curl的一个解释,简单地说就是,curl是一个库,能让你经过URL和许多不一样种的服务器进行勾搭、搭讪和深刻交流,而且还支持许多协议。而且人家还说了curl能够支持https认证、http post、ftp上传、代理、cookies、简单口令认证等等功能啦。git
说了那么多其实没什么感受吧,在应用中才有感受,我起初也是须要在服务器端向另外一个服务器发起一个POST请求才开始接触curl的,而后才有了感受。github
在正式讲怎么用以前啊,先提一句,你得先在你的PHP环境中安装和启用curl模块,具体方式我就不讲了,不一样系统不一样安装方式,能够google查一下,或者查阅PHP官方的文档,还挺简单的。web
工具到手,先要把玩,试试顺不顺手,否则一拿来就用,把你本身的代码搞得乌烟瘴气还怎么去撩服务器呢?json
好比咱们以著名的“测试网络是否链接”的网站——百度为例,来尝试下curl后端
<?php // create curl resource $ch = curl_init(); // set url curl_setopt($ch, CURLOPT_URL, "baidu.com"); //return the transfer as a string curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // $output contains the output string $output = curl_exec($ch); //echo output echo $output; // close curl resource to free up system resources curl_close($ch); ?>
当你在本地环境浏览器打开这个php文件时,页面出现的是百度的首页,特么我刚才输入的“localhost”呢?数组
上面的代码和注释已经充分说明了这段代码在干啥。浏览器
$ch = curl_init()
,建立了一个curl会话资源,成功返回一个句柄; curl_setopt($ch, CURLOPT_URL, "baidu.com")
,设置URL,不用说; 安全
上面两句能够合起来变一句$ch = curl_init("baidu.com")
;
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0)
这是设置是否将响应结果存入变量,1是存入,0是直接echo出;
$output = curl_exec($ch)
执行,而后将响应结果存入$output
变量,供下面echo;
curl_close($ch)
关闭这个curl会话资源。
PHP中使用curl大体就是这么一个形式,其中第二步,经过curl_setopt
方法来设置参数是最复杂也是最重要的,感兴趣能够去看官方的关于可设置参数的详细参考,长地让你看得想吐,仍是根据须要熟能生巧吧。
小结一下,php中curl用法就是:建立curl会话 -> 配置参数 -> 执行 -> 关闭会话。
下面咱们来看一些经常使用的情景,咱们须要如何“打扮本身”(配置参数)才能正确“撩妹”(正确撩到服务器)。
先和服务器打个招呼吧,给服务器发个Hello看她怎么回,这里最方便的方式就是向服务器发出GET请求,固然POST这种小纸条也OK咯。
咱们以“在某著名同性交友网站github中搜索关键词”为例
//经过curl进行GET请求的案例 <?php // create curl resource $ch = curl_init(); // set url curl_setopt($ch, CURLOPT_URL, "https://github.com/search?q=react"); //return the transfer as a string curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // $output contains the output string $output = curl_exec($ch); //echo output echo $output; // close curl resource to free up system resources curl_close($ch); ?>
好像和以前那个例子没啥差异,但这里有2个能够提的点:
1.默认请求方式是GET,因此不须要显式指定GET方式;
2.https请求,非http请求,可能有人在各个地方看到过HTTPS请求须要加几行代码绕过SSL证书的检查等方式来成功请求到资源,可是这里好像并不须要,缘由是什么?
The two Curl options are defined as:
CURLOPT_SSL_VERIFYPEER - verify the peer's SSL certificate CURLOPT_SSL_VERIFYHOST - verify the certificate's name against host
They both default to true in Curl, and shouldn't be disabled unless you've got a good reason. Disabling them is generally only needed if you're sending requests to servers with invalid or self-signed certificates, which is only usually an issue in development. Any publicly-facing site should be presenting a valid certificate, and by disabling these options you're potentially opening yourself up to security issues.
即,除非用了非法或者自制的证书,这大多数出如今开发环境中,你才将这两行设置为false
以避开ssl证书检查,否者不须要这么作,这么作是不安全的作法。
那如何进行POST请求呢?为了测试,先在某个测试服务器传了一个接收POST的脚本:
//testRespond.php <?php $phpInput=file_get_contents('php://input'); echo urldecode($phpInput); ?>
而后在本地写一个请求:
<?php $data=array( "name" => "Lei", "msg" => "Are you OK?" ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://测试服务器的IP马赛克/testRespond.php"); curl_setopt($ch, CURLOPT_POST, 1); //The number of seconds to wait while trying to connect. Use 0 to wait indefinitely. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60); curl_setopt($ch, CURLOPT_POSTFIELDS , http_build_query($data)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); echo $output; curl_close($ch); ?>
浏览器运行结果是:
name=Lei&msg=Are you OK?
这里咱们是构造了一个数组做为POST数据传给服务器:
curl_setopt($ch, CURLOPT_POST, 1)
代表是POST请求;
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60)
设置一个最长的可忍受的链接时间,秒为单位,总不能一直等下去变成木乃伊吧;
curl_setopt($ch, CURLOPT_POSTFIELDS , http_build_query($data))
设置POST的数据域,由于这里是数组数据形式的(等会来说json格式),因此用http_build_query
处理一下。
<?php $data='{"name":"Lei","msg":"Are you OK?"}'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://测试服务器的IP马赛克/testRespond.php"); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length:' . strlen($data))); curl_setopt($ch, CURLOPT_POSTFIELDS , $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); echo $output; curl_close($ch); ?>
浏览器执行,显示:
{"name":"Lei","msg":"Are you OK?"}
已经和服务器勾搭上了,这时候得要个照片来看一看了吧,你也得把本身的照片发上去让人看一看了,虽然两我的在一块儿外貌不重要,可是男俊女靓老是最棒的。
一样远程服务器端咱们先传好一个接收脚本,接收图片而且保存到本地,注意文件和文件夹权限问题,须要有写入权限:
<?php if($_FILES){ $filename = $_FILES['upload']['name']; $tmpname = $_FILES['upload']['tmp_name']; //保存图片到当前脚本所在目录 if(move_uploaded_file($tmpname,dirname(__FILE__).'/'.$filename)){ echo ('上传成功'); } } ?>
而后咱们再来写咱们本地服务器的php curl
部分:
<?php $data = array('name'=>'boy', "upload"=>"@boy.png"); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://远程服务器地址马赛克/testRespond.php"); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60); curl_setopt($ch, CURLOPT_POSTFIELDS , $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); echo $output; curl_close($ch); ?>
浏览器中运行一下,什么都米有,去看一眼远程的服务器,仍是什么都没有,并无上传成功。
为何会这样呢?上面的代码应该是你们搜索curl php POST图片
最多见的代码,这是由于我如今用的是PHP5.6以上版本,@
符号在PHP5.6
以后就弃用了,PHP5.3
依旧能够用,因此有些同窗发现能执行啊,有些发现不能执行,大抵是由于PHP版本的不一样,并且curl在这两版本中实现是不兼容的,上面是PHP5.3
的实现。
下面来说PHP5.6及之后的实现,:
<?php $data = array('name'=>'boy', "upload"=>""); $ch = curl_init(); $data['upload']=new CURLFile(realpath(getcwd().'/boy.png')); curl_setopt($ch, CURLOPT_URL, "http://115.29.247.189/test/testRespond.php"); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60); curl_setopt($ch, CURLOPT_POSTFIELDS , $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); echo $output; curl_close($ch); ?>
这里引入了一个CURLFile
对象进行实现,关于此的具体可查阅文档进行了解。这时候再去远程服务器目录下看看,发现有了一张图片了,并且确实是咱们刚才上传的图片。
服务器妹子也挺实诚的,看了照骗以为我长得挺慈眉善目的,就大方得拿出了她本身的照片,可是有点害羞的是,她不肯意主动拿过来,得咱们本身去取。
远程服务器在她本身的目录下存放了一个图片叫girl.jpg
,地址是她的web服务器根目录/girl.jpg
,如今我要去获取这张照片。
<?php $ch = curl_init(); $fp=fopen('./girl.jpg', 'w'); curl_setopt($ch, CURLOPT_URL, "http://远程服务器地址马赛克/girl.jpg"); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60); curl_setopt($ch, CURLOPT_FILE, $fp); $output = curl_exec($ch); $info = curl_getinfo($ch); fclose($fp); $size = filesize("./girl.jpg"); if ($size != $info['size_download']) { echo "下载的数据不完整,请从新下载"; } else { echo "下载数据完整"; } curl_close($ch); ?>
如今,在咱们当前目录下就有了一张刚拿到的照片啦,是否是很激动呢!
这里值得一说的是curl_getinfo
方法,这是一个获取本次请求相关信息的方法,对于调试颇有帮助,要善用。
这个时候呢,服务器的家长说这个咱们女儿还过小,不能找对象,就将她女儿关了起来,而且上了一个密码锁,所谓的HTTP认证,服务器呢偷偷托信鸽将HTTP认证的用户名和密码给了你,要你去见她,带她私奔。
那么拿到了用户名和密码,咱们怎么经过PHP CURL
搞定HTTP认证呢?
PS:这里偷懒就不去搭HTTP认证去试了,直接放一段代码,咱们分析下。
function curl_auth($url,$user,$passwd){ $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_USERPWD => $user.':'.$passwd, CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true ]); $result = curl_exec($ch); curl_close($ch); return $result; } $authurl = 'http://要请求HTTP认证的地址'; echo curl_auth($authurl,'vace','passwd');
这里有一个地方比较有意思: curl_setopt_array
这个方法能够经过数组一次性地设置多个参数,防止有些须要多处设置的出现密密麻麻的curl_setopt
方法。
这时你成功见到了服务器妹子,想带她私奔,可是无奈没有盘缠走不远,服务器妹子说,她妈服务器上有金库,能够登录上去搞一点下来。
首先咱们先来分析一下,这个事情分两步,一是去登录界面经过帐号密码登录,而后获取cookie,二是去利用cookie模拟登录到信息页面获取信息,大体的框架是这样的。
<?php //设置post的数据 $post = array ( 'email' => '帐户', 'pwd' => '密码' ); //登陆地址 $url = "登录地址"; //设置cookie保存路径 $cookie = dirname(__FILE__) . '/cookie.txt'; //登陆后要获取信息的地址 $url2 = "登录后要获取信息的地址"; //模拟登陆 login_post($url, $cookie, $post); //获取登陆页的信息 $content = get_content($url2, $cookie); //删除cookie文件 @ unlink($cookie); var_dump($content); ?>
而后咱们思考下下面两个方法的实现:
login_post($url, $cookie, $post)
get_content($url2, $cookie)
//模拟登陆 function login_post($url, $cookie, $post) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 0); curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post)); curl_exec($curl); curl_close($curl); }
//登陆成功后获取数据 function get_content($url, $cookie) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie); $rs = curl_exec($ch); curl_close($ch); return $rs; }
至此,总算是模拟登录成功,一切顺利啦,经过php CURL
“撩”服务器就是这么简单。
固然,CURL
的能力远不止于此,本文仅但愿就后端PHP开发中最经常使用的几种场景作一个整理和概括。最后一句话,具体问题具体分析。