PHP - fetching file behind a proxy

Posted on October 27, 2014 by

To use file_get_content over/through a Proxy that doesn't require Authentication, something like this should do:

Without Authentication

//Proxy bypass code
<?php
 // Define the default, system-wide context.
 $r_default_context = stream_context_get_default
 (
  array
     (
     'http' => array
      ( // All HTTP requests are passed through the local NTLM proxy server on port 8080.Change the proxy IP as required.
          'proxy' => 'tcp://192.168.23.32:3128',
          'request_fulluri' => True
      ),
     )
 );
 
// Though we said system wide, some extensions need a little coaxing.
 libxml_set_streams_context($r_default_context);
?>
 
//fetching data
<?php
   $var = file_get_contents("http://www.example.com/file.txt");
?>

If authentication is required. Then pass login details as well.

With Authentication

//Proxy bypass code
<?php
 // Define login details
 $auth = base64_encode('USERID:PASSWORD');

 // Define the default, system-wide context.
 $r_default_context = stream_context_get_default
 (
  array
     (
     'http' => array
      ( // All HTTP requests are passed through the local NTLM proxy server on port 8080.Change the proxy IP as required.
          'proxy' => 'tcp://192.168.23.32:3128',
          'request_fulluri' => True,
		  'header' => "Proxy-Authorization: Basic $auth" //Here you are passing login details
      ),
     )
 );
 
// Though we said system wide, some extensions need a little coaxing.
 libxml_set_streams_context($r_default_context);
?>
 
//fetching data
<?php
   $var = file_get_contents("http://www.example.com/file.txt");
?>
This website is made possible by displaying online advertisements to our visitors.
Please consider supporting by disabling your ad blocker.
loading comments...