我试图让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使用proxy(tcpdump -i any -A host 114.ip-147-135-210.eu),但stream_socket_client只是省略它并直接转到google.com。我究竟做错了什么?我的最终目标是通过代理连接到RabbitMQ(AMQP协议),但我甚至无法使用简单的HTTP连接。
答案 0 :(得分:0)
如果有人来这里苦苦挣扎,我最终通过首先连接到代理,然后发出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")