欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php通过socket套接字获取web服务器的响应内容

程序员文章站 2022-05-04 08:06:35
...
$url="www.baidu.com"; //域名
$path="/"; //路径
$type="GET"; //请求方法
error_reporting(E_ALL);
echo "

TCP/IP Connection

\n";
/* 获取端口号 */
$service_port = getservbyname('www', 'tcp');
/* 获取ip地址. */
$address = gethostbyname($url);
/* 创建 TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
} else {
echo "OK.\n";
}
echo "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
echo "OK.\n";
}
$in = $type." ".$path." HTTP/1.1\r\n";
$in .= "Host: ".$url."\r\n";
$in .= "Connection: Close\r\n\r\n";
$out = '';
echo "Sending HTTP HEAD request...";
socket_write($socket, $in, strlen($in));
echo "OK.\n";
echo "Reading response:\n\n";
while ($out = socket_read($socket, 2048)) {
echo $out;
}
echo "Closing socket...";
socket_close($socket);
echo "OK.\n\n";
?>

以上就介绍了 php通过socket套接字获取web服务器的响应内容,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。