在PHP中有一个函数fsockopen
,它可以打开一个网络连接或者一个Unix套接字连接,看看使用方法
resource fsockopen ( string $hostname [, int $port = -1 [, int &$errno
[, string &$errstr [, float $timeout = ini_get("default_socket_timeout") ]]]] )
开启
要想使用这个函数,首先需要在php.ini
配置文件中开启allow_url_open
GET请求
// 琼台博客 www.qttc.net
// Open
$fp = fsockopen("www.qttc.net", 80, $errno, $errstr, 30);
if(!$fp){
die($errstr);
}
set_time_limit(0);
// Header
$http = "GET / HTTP/1.1\r\n";
$http .= "Host: www.qttc.net\r\n";
$http .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
$http .= "Connection: Close\r\n\r\n";
// Send
fwrite($fp, $http);
// Response
$out = '';
while (!feof($fp)) {
$out .= fgets($fp, 128);
}
echo $out;
fclose($fp);
POST请求
// 琼台博客 www.qttc.net
// Open
$fp = fsockopen("www.qttc.net", 80, $errno, $errstr, 30);
if(!$fp){
die($errstr);
}
set_time_limit(0);
// Data
$data = "Hi"
// Header
$http = "POST / HTTP/1.1\r\n";
$http .= "Accept: */*\r\n";
$http .= "Content-Type: application/x-www-form-urlencoded\r\n"
$http .= "Host: www.qttc.net\r\n";
$http .= "Content-Length: ".strlen($data)."\r\n";
$http .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
$http .= "Connection: Close\r\n\r\n";
$http .= $post;
// Send
fwrite($fp, $http);
// Response
$out = '';
while (!feof($fp)) {
$out .= fgets($fp, 128);
}
echo $out;
fclose($fp);
报头部分遵循HTTP协议拼接好报头就好