file_get_contents behind a proxy?
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://..../...');
Use stream_context_set_default
function. It is much easier to use as you can directly use file_get_contents or similar functions without passing any additional parameters
This blog post explains how to use it. Here is the code from that page.
<?php
// Edit the four values below
$PROXY_HOST = "proxy.example.com"; // Proxy server address
$PROXY_PORT = "1234"; // Proxy server port
$PROXY_USER = "LOGIN"; // Username
$PROXY_PASS = "PASSWORD"; // Password
// Username and Password are required only if your proxy server needs basic authentication
$auth = base64_encode("$PROXY_USER:$PROXY_PASS");
stream_context_set_default(
array(
'http' => array(
'proxy' => "tcp://$PROXY_HOST:$PROXY_PORT",
'request_fulluri' => true,
'header' => "Proxy-Authorization: Basic $auth"
// Remove the 'header' option if proxy authentication is not required
)
)
);
$url = "http://www.pirob.com/";
print_r( get_headers($url) );
echo file_get_contents($url);
?>
To use file_get_contents()
over/through a proxy that doesn't require authentication, something 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, replacing 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 ;-) Check out all valid http options.
Now, you are passing an Proxy-Authorization header to the proxy, containing your login and password.
And... The page should be displayed ;-)