我正在尝试获得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.0rnHost: www.google.comrnAccept: */*rnrn");
while (!feof($fp)) {
echo fgets($fp, 1024);
}
fclose($fp);
}
?>
而file_get_contents使用代理(tcpdump -i any -a主机114.ip-147-135-210.eu(stream_socket_client简单地省略它并直接转到Google.com。我究竟做错了什么?我的最终目标是通过代理连接到RabbitMQ(AMQP协议(,但我什至无法获得简单的HTTP连接。
如果有人来这里苦苦挣扎,我最终通过先连接到代理,然后发出HTTP标头来获取我想要的内容。
首先创建代理的套接字:
$sock = stream_socket_client(
"tcp://$proxy:$port",
$errno,
$errstr,30,
STREAM_CLIENT_CONNECT,
stream_context_create()
);
第二个连接到您想要的目标主机:
$write = "CONNECT www.example.org HTTP/1.1rn";
$write .= "Proxy-Authorization: Basic ".base64_encode("$proxy_user:$proxy_pass)."rn";
$write .= "rn";
fwrite($sock, $write);
这应该返回200代码:
preg_match('/^HTTP/d.d 200/', fread($sock, 1024));
现在您可以发出get(确保发送所有HTTP标头(:
fwrite($sock, "GET / HTTP/1.1rn")
这有更多详细信息:https://stackoverflow.com/a/55010581/687976