php 请求方法,PHP中进行HTTP请求的两种方法

方法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)
\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)
\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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值