Skip to content

Instantly share code, notes, and snippets.

@artoodetoo
Created February 20, 2016 18:56
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save artoodetoo/fe41d07e825f765f062d to your computer and use it in GitHub Desktop.
Save artoodetoo/fe41d07e825f765f062d to your computer and use it in GitHub Desktop.
Use file_get_contents() with cookies and proxy (optionally with auth)
<?php
function file_get_contents_ex($url, $cookie = null, $proxy = null, $auth = null)
{
$opts = array(
'http' => array(
'method' => 'GET',
'user-agent'=> 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36',
'header' => "Accept-language: en\r\n" .
(!empty($auth) ? "Proxy-Authorization: Basic {$auth}\r\n" : '') .
(!empty($cookie) ? "Cookie: ".implode('; ', (array)$cookie)."\r\n" : ''),
)
);
if (!empty($proxy)) {
$opts['http']['proxy'] = $proxy;
$opts['http']['request_fulluri'] = true;
}
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
return file_get_contents($url, false, $context);
}
$cookie = array(
'foo=bar',
'session-token=0Cz+zmPOQ7rIWQQe2Z6HBi14Tjqir/GhDAeGK5KTPxuhJs56YtJAje9RipLHpwPDzuW0XX5NU915iFLqkM+Mq8PaL/Km1sR0nKtL6itVihwfAm0k4g/n4lmIV1ByWhDFnRH9j+ELWwxBR2tsJQvgIjDHsoDBp/hEe61HdNqcr5WLdtHMgYToRr5mXyb5WlVTUfFJego6jkIoxEWuoFZOFbOUEiWOJOs+xZHE80+hB1UvZgsy4bNoqnEDsQBSGFNY'.
);
// See proxy list: http://www.google-proxy.net/
$proxy = 'tcp://104.236.153.33:3128';
$auth = null; // base64_encode('login:password');
$url = 'http://example.com/path/to/page';
echo file_get_contents_ex($url, $cookie, $proxy, $auth);
@bublick
Copy link

bublick commented Dec 16, 2020

Great example of headers. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment