fsockopen操作类,实现了简单的post和get方法
<?php
/**
* 功 能:fsockopen操作类,实现了简单的post和get方法
* usage:
* //fsocketOper::$header = true; //开启只返回header头
* $data = fsocketOper::Http_get( $posturl ); //get方法
* $data = fsocketOper::Http_post( $posturl , array ( 'one' => 1 ) ); //post方法
* var_dump( $data );
*/
class fsocketOper
{
public static $header = FALSE; //true则返回header头,不返回实体数据
/**
* 功 能:模拟get请求
*
* @param $url 抓取页面的url
*
* @return string 页面内容
*/
public static function Http_get( $url )
{
//解析url
$url = parse_url( $url );
$port = isset( $url[ 'port' ] ) ? $url[ 'port' ] : 80;
$path = isset( $url[ 'path' ] ) ? $url[ 'path' ] : 'index.php';
$queryData = isset( $url[ 'query' ] ) ? $url[ 'query' ] : '';
//请求数据整合
$query = $path . "?" . $queryData;
$fp = fsockopen( $url[ 'host' ] , $port , $errno , $errstr );
if ( !$fp )
{
return $errstr . '(' . $errno . ')';
}
else
{
$request = "GET $query HTTP/1.1\r\n";
$request .= "Host: $url[host]\r\n";
$request .= "Connection: Close\r\n";
$request .= "\r\n";
fwrite( $fp , $request );
$result = '';
while ( !feof( $fp ) )
{
$result .= @fgets( $fp , 1024 );
}
fclose( $fp );
return self::getContents( $result );
}
}
/**
* 功 能:模拟post请求
*
* @param $URL
* @param array $Postdata
* @param string $referer
*
* @return string
*/
public static function HTTP_post( $URL , array $Postdata , $referer = "" )
{
//解析url
$URL_Info = parse_url( $URL );
if ( !isset( $URL_Info[ "port" ] ) )
{
$URL_Info[ "port" ] = 80;
}
//设置post来源
if ( $referer == "" )
{
$referer = 'index.php';
}
//拼接post数据
foreach ( $Postdata as $key => $value )
{
$values[ ] = "$key=" . urlencode( $value );
}
$data_string = implode( "&" , $values );
//请求数据整合
$request = '';
$request .= "POST " . $URL_Info[ "path" ] . " HTTP/1.1\r\n";
$request .= "Host: " . $URL_Info[ "host" ] . "\r\n";
$request .= "Referer: $referer\r\n";
$request .= "Content-type: application/x-www-form-urlencoded\r\n"; //post
$request .= "Content-length: " . strlen( $data_string ) . "\r\n"; //发送post数据的长度
$request .= "Connection: close\r\n";
$request .= "\r\n";
$request .= $data_string . "\r\n";
$fp = fsockopen( $URL_Info[ "host" ] , $URL_Info[ "port" ] , $errno , $errstr );
if ( !$fp )
{
return $errstr . '(' . $errno . ')';
}
fputs( $fp , $request );
$result = '';
while ( !feof( $fp ) )
{
$result .= fgets( $fp , 1024 );
}
fclose( $fp );
return self::getContents( $result );
}
/**
* 功 能:处理得到的数据
* @param $contents 有header的string
*
* @return string
*/
private static function getContents( $contents )
{
if ( self::$header )
{ //获得header信息
$pos = stripos( $contents , "\r\n\r\n" );
$header = substr( $contents , 0 , $pos );
return $header;
}
else
{ //获得body信息
$body = stristr( $contents , "\r\n\r\n" );
$body = substr( $body , 4 , strlen( $body ) );
return $body;
}
}
}