fsockopen is a relatively practical function in PHP. Now I will introduce the program that uses the fsockopen function to collect web pages. Friends in need can refer to it.
Usage
int fsockopen(string hostname, int port, int [errno], string [errstr], int [timeout]);
An example of collecting web pages
The code is as follows 代码如下 | 复制代码 | function get_url ($url,$cookie=false) { $url = parse_url($url); $query = $url[path].”?”.$url[query]; echo “Query:”.$query; $fp = fsockopen( $url[host], $url[port]?$url[port]:80 , $errno, $errstr, 30); if (!$fp) { return false; } else { $request = “GET $query HTTP/1.1rn”; $request .= “Host: $url[host]rn”; $request .= “Connection: Closern”; if($cookie) $request.=”Cookie: $cookien”; $request.=”rn”; fwrite($fp,$request); while(!@feof($fp)) { $result .= @fgets($fp, 1024); } fclose($fp); return $result; } } //获取url的html部分,去掉header function GetUrlHTML($url,$cookie=false) { $rowdata = get_url($url,$cookie); if($rowdata) { $body= stristr($rowdata,”rnrn”); $body=substr($body,4,strlen($body)); return $body; } return false; } ?> | |
Copy code function get_url ($url,$cookie=false) { $url = parse_url($url);$query = $url[path] ."?".$url[query]; echo "Query:".$query;$fp = fsockopen( $url[host], $url[port]?$url[port]:80 , $errno, $errstr, 30); if (!$fp) { 代码如下 | 复制代码 | $fp = fsockopen($host, 80, $errno, $errstr, 30); 或 $fp = fsockopen($host, $port, $errno, $errstr, $connection_timeout); 修改后: $fp = stream_socket_client("tcp://".$host."80", $errno, $errstr, 30); 或 $fp = stream_socket_client("tcp://".$host.":".$port, $errno, $errstr, $connection_timeout); | return false; | } else { $request = “GET $query HTTP/1.1rn”; |
$request .= “Host: $url[host]rn”;
$request .= “Connection: Closern”;if($cookie) $request.=”Cookie: $cookien”;
$request.=”rn”;
fwrite($fp,$request);while(!@feof($fp)) {$result .= @fgets($fp, 1024) ;}fclose($fp);return $result;}}//Get the html part of the url, remove the headerfunction GetUrlHTML($url ,$cookie=false){$rowdata = get_url($url,$cookie);if($rowdata)
{$body= stristr($rowdata,”rnrn ”);
$body=substr($body,4,strlen($body));}<🎜><🎜> return false;<🎜>}<🎜> ?> Solution after being disabledThe server also disables fsockopen pfsockopen, then use other functions instead, such as stream_socket_client(). Note: The parameters of stream_socket_client() and fsockopen() are different. Replace fsockopen( with stream_socket_client(, then delete the port parameter "80" in the original fsockopen function and add it to $host.Example