例子,php模拟post提交数据,可用来网站数据采集、模拟登录等。
完整代码:
<?php
//以论坛登录为例
function bbslogin($user_login, $password, $host, $port = "80") {
//需要提交的post数据
$argv = array('cookie' => array('user_login' => $user_login, 'password' => $password, '_wp_http_referer' => '/bbpress/', 're' => '', 'remember' => true));
foreach ($argv['cookie'] as $key => $value) {
$params[] = $key . '=' . $value;
}
$params = implode('&', $params);
$header = "POST /bbpress/bb-login.php HTTP/1.1rn";
$header .= "Host:$host:$portrn";
$header .= "Content-Type: application/x-www-form-urlencodedrn";
$header .= "Content-Length: " . strlen($params) . "rn";
$header .= "Connection: Closernrn";
$header .= $params;
$fp = fsockopen($host, $port);
fputs($fp, $header);
while (!feof($fp)) {
$str = fgets($fp);
//以下是逻辑代码,模拟cookie,可用来同步登陆
if (!(strpos($str, "Set-Cookie:") === false)) {
$tmparray = explode(" ", $str);
$cookiearray = explode("=", $tmparray[1]);
$cookiepaths = explode("=", $tmparray[6]);
$cookiename = urldecode($cookiearray[0]);
$cookievalue = urldecode(substr($cookiearray[1], 0, strlen($cookiearray[1]) - 1));
$cookietime = time() + 3600 * 24 * 7;
$cookiepath = urldecode(substr($cookiepaths[1], 0, strlen($cookiepaths[1]) - 1));
setcookie($cookiename, $cookievalue, $cookietime, $cookiepath);
}
}
fclose($fp);
}
?>
注:上述不支持https协议,下面才支持:
function vpost($url,$data){ // 模拟提交数据函数
$c curl_init(); // 启动一个CURL会话
curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
$tmpInfo = curl_exec($curl); // 执行操作
if (curl_errno($curl)) {
echo 'Errno'.curl_error($curl);//捕抓异常
}
curl_close($curl); // 关闭CURL会话
return $tmpInfo; // 返回数据
}
$url = "https://xxx.xxx.xxx/xxx";
$data ="x=xxxxxx";
$result = vpost($url,$data);
>>> 更多 php模拟登录 文章,专题链接:php模拟登录 php curl模拟登录教程大全