2

I'm trying to get stream_socket_client working with proxy server.

Peace of code:

<?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);
}
?>

While file_get_contents uses proxy (tcpdump -i any -A host 114.ip-147-135-210.eu) stream_socket_client simply omits it and goes directly to google.com. What am I doing wrong? My final goal is to connect to RabbitMQ (AMQP protocol) via proxy, but I can't even get simple HTTP connection working.

chudzini
  • 29
  • 4

1 Answers1

1

if anyone came here struggling, I ended up solving this by connecting to the proxy first then issuing http headers to get the content I wanted.

First create the socket to the proxy:

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

Second connect to the destination host you want:

$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);

This should return a 200 code:

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

Now you can just issue GET (make sure you send all the HTTP header):

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

This has more details: https://stackoverflow.com/a/55010581/687976

M.Alnashmi
  • 582
  • 1
  • 4
  • 15