tags:

views:

1097

answers:

3

At work we have to use a proxy to basically access port 80 for example, we have our own custom logins for each user.

My temporary workaround is using curl to basically login as myself through a proxy and access the external data I need.

Is there some sort of advanced php setting I can set so that internally whenever it tries to invoke something like file_get_contents it always goes through a proxy? I'm on Windows ATM so it'd be a pain to recompile if that's the only way.

The reason my workaround is temporary is because I need a solution that's generic and works for multiple users instead of using one user's credentials ( Ive considered requesting a separate user account solely to do this but passwords change often and this technique needs to be deployed throughout a dozen or more sites ). I don't want to hard-code credentials basically to use the curl workaround.

A: 

Depending on how the proxy login works stream_context_set_default might help you.

$context  = stream_context_set_default(
  array(
    'http'=>array(
      'header'=>'Authorization: Basic ' . base64_encode('username'.':'.'userpass')
    )
  )
);
$result = file_get_contents('http://..../...');
VolkerK
+6  A: 

Hi,

To use file_get_content over/through a Proxy that doesn't require Authentication, sometihing like this should do :
(I'm not able to test this one : my proxy requires an authentication)

$aContext = array(
    'http' => array(
        'proxy' => 'tcp://192.168.0.2:3128',
        'request_fulluri' => true,
    ),
);
$cxContext = stream_context_create($aContext);

$sFile = file_get_contents("http://www.google.com", False, $cxContext);

echo $sFile;

Of course, remplacing the IP and Port of my proxy by those which are OK for yours ;-)


If you're getting that kind of error :

Warning: file_get_contents(http://www.google.com) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 407 Proxy Authentication Required

It means your proxy requires an authentication.


If the proxy requires an authentication, you'll have to add a couple of lines, like this :

$auth = base64_encode('LOGIN:PASSWORD');

$aContext = array(
    'http' => array(
        'proxy' => 'tcp://192.168.0.2:3128',
        'request_fulluri' => true,
        'header' => "Proxy-Authorization: Basic $auth",
    ),
);
$cxContext = stream_context_create($aContext);

$sFile = file_get_contents("http://www.google.com", False, $cxContext);

echo $sFile;

Same thing about IP and Port, and, this time, also LOGIN and PASSWORD ;-)

Now, you are passing an Proxy-Authorization header to the proxy, containing your login and password.

And... The page should be displayed ;-)


Hope this helps ! Have fun !

If you understand french, you can take a look at this article, which helped me ^^ : Utilisation avancée de file_get_contents (PHP)

(Even if you don't understand french, the code examples might be useful)

Pascal MARTIN