horshoo
horshoo
发布于 2周前

php 实现http协议 客户端

使用 stream_socket_client 创建一个http 客户端。

代码:

$fp = stream_socket_client("tcp://127.0.0.1:8080", $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    fwrite($fp, "GET / HTTP/1.0\r\nHost: www.example.com\r\nAccept: */*\r\n\r\n");
    while (!feof($fp)) {
        echo fgets($fp, 1024);
    }
    fclose($fp);
}

输出:

HTTP/1.1 200 ok
Accept-Ranges: bytes
content-type: text/html; charset=utf-8

The local time is 2019-08-03 10:04:56