一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

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

时间:2013-06-26 编辑:简简单单 来源:一聚教程网

备注:使用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.111com.net/';
$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;
    }
}

热门栏目