1. 拿来先试试手
比如我们以著名的“测试网络是否连接”的网站——百度为例,来尝试下curl
// 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会话 -> 配置参数 -> 执行 -> 关闭会话。
下面我们来看一些常用的情景,我们需要如何“打扮自己”(配置参数)才能正确“撩妹”(正确撩到服务器)。
2.GET和POST请求以及HTTPS协议处理
2.1 GET请求
我们以“在某网站github中搜索关键词”为例
//通过curl进行GET请求的案例
// 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证书检查,否者不需要这么做,这么做是不安全的做法。
2.2 POST请求
那如何进行POST请求呢?为了测试,先在某个测试服务器传了一个接收POST的脚本:
//testRespond.php
$phpInput=file_get_contents('php://input');
echo urldecode($phpInput);
?>
发送普通数据
然后在本地写一个请求: