2

我正在尝试让 stream_socket_client 与代理服务器一起工作。

代码和平:

<?php 
$context = stream_context_create(['http' => ['proxy' => '147.135.210.114:54566', 'request_fulluri' => true]]);
//$file = file_get_contents("http://www.google.com", false, $context);
$fp = stream_socket_client("tcp://www.google.com:80", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $context);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    fputs($fp, "GET / HTTP/1.0\r\nHost: www.google.com\r\nAccept: */*\r\n\r\n");
    while (!feof($fp)) {
        echo fgets($fp, 1024);
    }
    fclose($fp);
}
?>

而 file_get_contents 使用代理 (tcpdump -i any -A host 114.ip-147-135-210.eu) stream_socket_client 只是忽略它并直接转到 google.com。我究竟做错了什么?我的最终目标是通过代理连接到 RabbitMQ(AMQP 协议),但我什至无法让简单的 HTTP 连接正常工作。

4

1 回答 1

1

如果有人来这里挣扎,我最终通过先连接到代理然后发出 http 标头来获取我想要的内容来解决这个问题。

首先创建到代理的套接字:

 $sock = stream_socket_client(
        "tcp://$proxy:$port",
        $errno,
        $errstr,30,
        STREAM_CLIENT_CONNECT,
        stream_context_create()
 );

第二次连接到您想要的目标主机:

$write =  "CONNECT www.example.org HTTP/1.1\r\n";
$write .= "Proxy-Authorization: Basic ".base64_encode("$proxy_user:$proxy_pass)."\r\n";
$write .= "\r\n";
fwrite($sock, $write);

这应该返回一个 200 代码:

preg_match('/^HTTP\/\d\.\d 200/', fread($sock, 1024));

现在您可以发出 GET(确保您发送所有 HTTP 标头):

fwrite($sock, "GET / HTTP/1.1\r\n")

这有更多细节:https ://stackoverflow.com/a/55010581/687976

于 2019-12-04T03:26:33.107 回答