Amir
Amir

Reputation: 49

How to make a proxy stream through socks5 for PHP?

I have this code:

$opt = array(
    'socks5' => array( 
        'proxy' => 'tcp://proxyIP:port', 
        'request_fulluri' => true,
    )
);

$stream = stream_context_create($opt);

if ($s = file_get_contents("http://yandex.ru/internet",FILE_USE_INCLUDE_PATH,$stream))
echo $s;

It doesn't work I guess, because getting site shows my IP instead of proxy IP.

If I put 'http' instead of 'socks5' it works and shows me the proxy IP.

In my proxy server for 'http' I have port = 4000, for 'socks5' port = 5000.

But I really need to connect through SOCKS5. How can I do this?

Upvotes: 2

Views: 4037

Answers (1)

20AMax
20AMax

Reputation: 466

I think it is imposible to make stream_context_create() to work with socks5. The best solution is to use curl. Example according your needs, change $proxyIP and $proxyPort

<?php

//$opt = array('socks5' => array( 
//                            'proxy' => 'tcp://proxyIP:port', 
//                            'request_fulluri' => true,
//                        )
//            );
//
//$stream = stream_context_create($opt);
//
//if ($s = file_get_contents("http://yandex.ru/internet",FILE_USE_INCLUDE_PATH,$stream))
//echo $s;

$url = 'https://yandex.ru/internet';
$proxyIP = '0.0.0.0';
$proxyPort = 0;
//$proxy_user = '';
//$proxy_pass = '';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
//curl_setopt($ch, CURLOPT_PROXYUSERPWD, "{$proxy_user}:{$proxy_pass}");
curl_setopt($ch, CURLOPT_PROXY, $proxyIP);
curl_setopt($ch, CURLOPT_PROXYPORT, $proxyPort);

$s = curl_exec($ch);
curl_close($ch);

if ($s) {
    echo $s;
}

In case if you cannot use curl or want to use sockets please read this https://stackoverflow.com/a/31010287/3904683 answer

Upvotes: 1

Related Questions