Created
February 20, 2016 18:56
-
-
Save artoodetoo/fe41d07e825f765f062d to your computer and use it in GitHub Desktop.
Use file_get_contents() with cookies and proxy (optionally with auth)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great example of headers. Thanks!