方法1:使用CURL
$url = http://www.zhixing123.cn/login.php; //请求地址
$ref_url = http://www.baidu.com; //来源页面
$data = array( //提交的数据
"username" => "zhixing123.cn",
"password" => www.zhixing123.cn,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_REFERER, $ref_url);
curl_setopt($ch, CURLOPT_POST, TRUE); //以POST方式提交
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //超时时间
$contents = curl_exec($ch); //执行并获取返回数据
curl_close($ch);
方法2:使用socket
(1) GET实例
假设HttpWatch抓取浏览器的HTTP请求数据为:
GET /index.aspx?action=read HTTP/1.1
Accept-Language: zh-cn
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0;
.NET CLR 2.0.50727)
Accept-Encoding: gzip, deflate
Host: zhixing123.cn
Connection: Keep-Alive
Cookie: ASP.NET_SessionId=zfyaimqgtt1bfiewq0najgah
PHP代码:
<?
$host = "zhixing123.cn";
$path = "/index.aspx?action=read";
$cookie = "ASP.NET_SessionId=zfyaimqgtt1bfiewq0najgah";
$fp = fsockopen($host, 80, $errno, $errstr, 30);
if (!$fp) {
print "$errstr ($errno)<br />\n";
exit;
}
$out = "GET ".$path." HTTP/1.1\r\n";
$out .= "Host: ".$host."\r\n"; //Host不能包括“http://”
$out .= "Connection: Close\r\n";
$out .= "Cookie: ".$cookie."\r\n\r\n";
fwrite($fp, $out); //将请求写入socket
while (!feof($fp)) { //获取server端的响应
echo fgets($fp, 128);
}
fclose($fp);
(2) POST实例
假设HttpWatch抓取浏览器的HTTP请求数据为:
POST /Login.aspx HTTP/1.1
Accept-Language: zh-cn
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0;
.NET CLR 2.0.50727)
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
Host: example.com
Connection: Keep-Alive
Cache-Control: no-cache
Cookie: ASP.NET_SessionId=zfyaimqgtt1bfiewq0najgah
username=zhixing123&password=www.zhixing123.cn
PHP代码:
<? $host = "zhixing123.cn";
$path = "/Login.aspx";
$cookie = "ASP.NET_SessionId=zfyaimqgtt1bfiewq0najgah";
$params = "username=zhixing123&password=www.zhixing123.cn";
$fp = fsockopen($host, 80, $errno, $errstr, 30);
if (!$fp) {
print "$errstr ($errno)<br />\n";
exit;
}
$out = "POST ".$path." HTTP/1.1\r\n";
$out .= "Host: ".$host."\r\n";
$out .= "Connection: Close\r\n";
$out .= "Cookie: ".$cookie."\r\n\r\n";
$out .= $params;
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);