通过curl可进行远程一键登录或制作采集程序的模拟登陆
添加post提交数据时,可以提交数组,也可以提交json数据。可根据实际情况选择,例如钉钉获取用户信息的接口
/**
* [httpRequest 模拟发起网络请求]
* @param [type] $url [发起网络请求的地址]
* @param [array|json] $post [需要提交的数据]
* @param [string]$cookie [cookie文件的储蓄路径]
* @param [int] $action [进行哪种操作]
* @return [object] [description]
*/
private function httpRequest($url,$post=array(),$action=0,$cookie='')
{
$header = array();
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, false); //是否显示头信息
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);//是否自动显示返回的信息
curl_setopt($curl, CURLOPT_TIMEOUT, 500);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
if($post) {
curl_setopt($curl, CURLOPT_POST, 1);
if(is_array($post)){
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));//为了兼容更多浏览器,这里必须这么写
}else if($this->is_json($post)){
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);//json本就是字符串,不需要转换
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
}
}
switch ($action) {
case '0':
# 获取cookie
if ($cookie) {
curl_setopt($curl, CURLOPT_COOKIEJAR, $cookie); //设置cookie信息保存在指定的文件夹中
}
break;
case '1':
# 发送cookie
if ($cookie) {
curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie);
}
break;
case '2':
# 发送cookie
if ($cookie) {
curl_setopt($curl, CURLOPT_COOKIE, $cookie);
}else{
curl_setopt($curl, CURLOPT_COOKIE, $_SERVER['HTTP_COOKIE']);
}
break;
default:
# 删除cookie
if ($cookie) {
@unlink($cookie_file);
}
break;
}
$res = curl_exec($curl);
curl_close($curl);
return json_decode($res);
}
需要一个自动检测是否为合法的json格式数据的方法
function is_json($string) {
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}