POST和GET在curl中应用

在做爬虫,抓取网站,做同步,api开发,以及微信公众号开发中,curl使用非常重要,下面就来介绍curl使用;

函数两枚

//post提交
function post($url,$msg){//post ssl
$ch = curl_init();

if (class_exists('\CURLFile')) {
    curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
} else {
    if (defined('CURLOPT_SAFE_UPLOAD')) {
        curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
    }
}
//$msg = array('media'=>"@".$filepath);
//5.6+ $msg = array('media'=>new \CURLFile($filepath));
preg_match('/https:\/\//',$url)?$ssl=TRUE:$ssl=FALSE;
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL,$url);
if($ssl){
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
}
curl_setopt($ch, CURLOPT_POSTFIELDS,$msg);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
    }

//get获取
function get($url){   
 $ch = curl_init();
 preg_match('/https:\/\//',$url)?$ssl=TRUE:$ssl=FALSE;
 curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HEADER, 0);
if($ssl){
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$data  =  curl_exec($ch);
curl_close($ch);
return $data; 
}

两个函数都支持ssl,也就是https开头访问,能够自动判断是否是https网站;
特别注意5.6以上包括5.6版本php 上传可是和以前完全不一样,这是一个大坑


扫码二维码阅读

标签: php, 微信, 函数, ssl, false, url, curl_setopt, msg

添加新评论