加入收藏 | 设为首页 | 会员中心 | 我要投稿 汽车网 (https://www.0577qiche.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP 采用curl_init发起http请求模仿登录

发布时间:2023-05-29 13:52:35 所属栏目:PHP教程 来源:
导读:http请求包括两种,一种是我们普通的http请求登录,另一种是另一种https请求登录,下面我来分别给各位同学详细介绍利用curl_init来实现http与https进行登录。

备注:使用curl_init函数,必须要打开这个php扩展。

1.
http请求包括两种,一种是我们普通的http请求登录,另一种是另一种https请求登录,下面我来分别给各位同学详细介绍利用curl_init来实现http与https进行登录。

备注:使用curl_init函数,必须要打开这个php扩展。

1.打开php.ini,开启extension=php_curl.dll

2.检查php.ini的extension_dir值是哪个目录,检查有无php_curl.dll,没有的请下载php_curl.dll,再把php目录中的libeay32.dll,ssleay32.dll拷到c:/windows/system32里面。

发起http请求,代码如下:

function _http_curl_post($url,$data)  
{  
    $ch = curl_init();  
    curl_setopt($ch, CURLOPT_URL, $url);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);  
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 4);  
    curl_setopt($ch, CURLOPT_TIMEOUT,4);  
           
    if($data){  
        curl_setopt($ch, CURLOPT_POST, 1);  
        curl_setopt($ch, CURLOPT_POSTFIELDS, "value=".json_encode($data));  //请求参数转为json格式  
    }  
    curl_setopt($ch, CURLOPT_HEADER, false);  
    $string = curl_exec($ch);  
    curl_close($ch);  
    return $string;  

调用方法,代码如下:

$params = array();  
$params['id']       = 1  
$params['web_name']   = '好脚本';  
$params['web_url']    = 'http://www.Cuoxin.com/';  
$params['web_miaoshu'] = '脚本编程示例';  
$data = _curl_post($url,$params);  
$arr =json_decode($data); 
除了http请求之外还有一个https的请求,上次我做人人网的一键登录,它的接口就是https的url,使用上面的函数,最终报错,如果您也遇到这样的问题,你可以参考下面方法解决。

https请求示例,代码如下:

function _https_curl_post($url, $vars)   
{   
    foreach($vars as $key=>$value)  
    {  
        $fields_string .= $key.'='.$value.'&' ;  
    }   
    $fields_string = substr($fields_string,0,(strlen($fields_string)-1)) ;  
    $ch = curl_init();    
    curl_setopt($ch, CURLOPT_URL,$url);   
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  2);  
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);  // this line makes it work under https  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);  
    curl_setopt($ch, CURLOPT_POST, count($vars) );  
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);       
    $data = curl_exec($ch);          
    curl_close($ch);    
         
    if ($data)  
    {  
        return $data;  
    }  
    else 
    {  
        return false;  
    }  
}

(编辑:汽车网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章