本文實例講述了PHP實現模仿socket請求返回頁面的方法。分享給大家供大家參考。具體實現方法如下:
復制代碼 代碼如下:<?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為可返回字節數
$return .= $data;
}
}
fclose($fp);
print_r($return);
}
希望本文所述對大家的PHP程序設計有所幫助。
1.用js的setInterval+ajax來請求,PHP裡面加條件判斷是否成功;
2.用PHP遞歸循環來做,如:
<?php
function test($url)
{
echo $url.'\t\n--------';
$r = @file_get_contents($url);//我這裡返回的是頁數,如果沒有下一頁的時候返回0,停止執行
echo $r;
if($r > 0)
{
$url = 'test.com/1.php?p='.$r;
test($url);
}
else
{
echo 'fail';
}
}
$url = 'test.com/1.php?p=1';
$res = test($url);
?>
<?php
function GETBySocket($URL, $port=80) {
//get host from url
preg_match('/\/\/.*\//sU',$URL,$host_array);
if(!$host_array[0]) {
$URL.='/';
preg_match('/\/\/.*\//sU',$URL,$host_array);
}
$host=substr($host_array[0],2,-1);
//connect
$fp = stream_socket_client("$host:$port", $errcode, $errstr, 1);// or die("get ". $host ." failed");
//
$header = "GET ". $URL. " HTTP/1.1\r\n";
$header .= "Accept: */*\r\n";
$header .= "Accept-Language: zh-cn\r\n";
//$header .= "HTTP_CONNECTION: Keep-Alive\r\n";
$header .= "HTTP_ACCEPT: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\n";
$header .= "HTTP_ACCEPT_CHARSET: gbk,*,utf-8\r\n";
//$header .= "Accept-Encoding: gzip, deflate\r\n";
$header .= "User-Agent: Mozilla/4.0(compatible; MSIE 6.0; Windows NT 5.1;)\r\n";
$header .= "Host: ". $host ."\r\n";
//$header .= "Connection: Keep-Alive\r\n";
//$header .= "Cookie: cnzz02=2; rtime=1; ltime=1148456424859; cnzz_eid=566......余下全文>>