Home >php教程 >php手册 >PHP 利用curl_init发起http请求模仿登录

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

WBOY
WBOYOriginal
2016-05-25 16:50:451501browse

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请求,代码如下:

<?php
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;
}
?>

调用方法,代码如下:

<?php
$params = array();
$params[&#39;id&#39;] = 1$params[&#39;web_name&#39;] = &#39;好脚本&#39;;
$params[&#39;web_url&#39;] = &#39;http://www.phprm.com/&#39;;
$params[&#39;web_miaoshu&#39;] = &#39;脚本编程示例&#39;;
$data = _curl_post($url, $params);
$arr = json_decode($data);
?>

除了http请求之外还有一个https的请求,上次我做人人网的一键登录,它的接口就是https的url,使用上面的函数,最终报错,如果您也遇到这样的问题,你可以参考下面方法解决。

https请求示例,代码如下:

<?php
function _https_curl_post($url, $vars) {
    foreach ($vars as $key => $value) {
        $fields_string.= $key . &#39;=&#39; . $value . &#39;&&#39;;
    }
    $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;
    }
}
?>

               
               

永久链接:

转载随意!带上文章地址吧。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn