PHP實現(xiàn)模仿socket請求返回頁面的方法
更新時間:2014年11月04日 11:42:15 投稿:shichen2014
這篇文章主要介紹了PHP實現(xiàn)模仿socket請求返回頁面的方法,是socket通信非常實用的技巧,需要的朋友可以參考下
本文實例講述了PHP實現(xiàn)模仿socket請求返回頁面的方法。分享給大家供大家參考。具體實現(xiàn)方法如下:
復(fù)制代碼 代碼如下:
<?php
$url = "www.XXXX.com"; //自己做替換
$parse = parse_url($url); //對URL進行解析,返回起組成部分。
$host = $parse['host'];
$path = $parse['path'];
$port = 80;
$timeout = 80;
$fp = @fsockopen($host, $port, $errno, $errstr, $timeout); //打開socket鏈接
if (!$fp){
echo $errno."--".$errstr; //如果錯誤,則返回錯誤代碼和錯誤信息
} else {
$out = "POST $path HTTP/1.1\r\n"; //以下是HTTP請求頭信息
$out .= "Host: ".$host."\r\n";
$out .= "Accept: */*\r\n";
$out .= "Connection: Close\r\n";
$out .= "Cookie: $cookie\r\n\r\n";
@fwrite($fp, $out); //把請求信息寫到鏈接中
$status = stream_get_meta_data($fp);
if(!$status['timed_out']) {
while (!feof($fp)) {
if(($header = @fgets($fp)) && ($header == "\r\n" || $header == "\n")) {
break;
}
}
$stop = false;
while(!feof($fp) && !$stop) {
$data = fread($fp,8192); //8192為可返回字節(jié)數(shù)
$return .= $data;
}
}
fclose($fp);
print_r($return);
}
$url = "www.XXXX.com"; //自己做替換
$parse = parse_url($url); //對URL進行解析,返回起組成部分。
$host = $parse['host'];
$path = $parse['path'];
$port = 80;
$timeout = 80;
$fp = @fsockopen($host, $port, $errno, $errstr, $timeout); //打開socket鏈接
if (!$fp){
echo $errno."--".$errstr; //如果錯誤,則返回錯誤代碼和錯誤信息
} else {
$out = "POST $path HTTP/1.1\r\n"; //以下是HTTP請求頭信息
$out .= "Host: ".$host."\r\n";
$out .= "Accept: */*\r\n";
$out .= "Connection: Close\r\n";
$out .= "Cookie: $cookie\r\n\r\n";
@fwrite($fp, $out); //把請求信息寫到鏈接中
$status = stream_get_meta_data($fp);
if(!$status['timed_out']) {
while (!feof($fp)) {
if(($header = @fgets($fp)) && ($header == "\r\n" || $header == "\n")) {
break;
}
}
$stop = false;
while(!feof($fp) && !$stop) {
$data = fread($fp,8192); //8192為可返回字節(jié)數(shù)
$return .= $data;
}
}
fclose($fp);
print_r($return);
}
希望本文所述對大家的PHP程序設(shè)計有所幫助。
相關(guān)文章
PHP創(chuàng)建文件及寫入數(shù)據(jù)(覆蓋寫入,追加寫入)的方法詳解
這篇文章主要介紹了PHP創(chuàng)建文件及寫入數(shù)據(jù)(覆蓋寫入,追加寫入)的方法,結(jié)合實例形式總結(jié)分析了php文件創(chuàng)建、寫入操作相關(guān)函數(shù)使用技巧,需要的朋友可以參考下2019-02-02PHP大小寫問題:函數(shù)名和類名不區(qū)分,變量名區(qū)分
這篇文章主要介紹了PHP大小寫問題,php中變量名是區(qū)分大小寫的,而函數(shù)名與類名是不區(qū)分的2013-06-06