Razvan Surdu Personal Blog

19Aug/090

Retrieving a web page behind a proxy in php

If you need to retrieve a web page or file from the web and you are behind a proxy that requires authentication you can use this methods:

$params = array
(
	'http' => array
	(
		'method' => 'GET',
		'header'  => 'Proxy-Authorization: Basic ' . base64_encode(PROXY_USERNAME . ':' . PROXY_PASSWORD) . "\r\n\r\n",
		'proxy' => 'tcp://PROXY_ADDRESS:PROXY_PORT',
		'request_fulluri' => true,
	)
);
$context = stream_context_create($params);

echo file_get_contents('http://www.google.com', null, $context);

For this method you need to have curl extension enabled:

$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL,"http://www.google.com/");
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 0);
curl_setopt($ch, CURLOPT_PROXY, 'proxyAddress:proxyPort');
curl_setopt ($ch, CURLOPT_PROXYUSERPWD, "username:password");
$page = curl_exec($ch);
echo($page);
Filed under: Examples, Php Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.