PHP obtains the response content of the web server through the socket

WBOY
Release: 2016-07-28 08:27:38
Original
1047 people have browsed it

$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.1rn";
$in .= "Host: ".$url."rn";
$in .= "Connection: Closernrn";
$out = '';
echo "Sending HTTP HEAD request...";
socket_write($socket, $in, strlen($in));
echo "OK.n";
echo "Reading response:nn";
while ($out = socket_read($socket, 2048)) {
    echo $out;
}
echo "Closing socket...";
socket_close($socket);
echo "OK.nn";
?>

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template