How to proxy another page in PHP
I'm looking for the fastest and easiest way to proxy a page in PHP. I don't want the user to be redirected, I just want my script to return the same content, response code 开发者_JAVA技巧and headers as another remote URL.
echo file_get_contents('proxypage');
Would that work?
EDIT:
First answer was a bit short, and I don't believe it will handle headers as you would like.
However you can also do this:
function get_proxy_site_page( $url )
{
$options = [
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => true, // return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
];
$ch = curl_init($url);
curl_setopt_array($ch, $options);
$remoteSite = curl_exec($ch);
$header = curl_getinfo($ch);
curl_close($ch);
$header['content'] = $remoteSite;
return $header;
}
This will return you an array containing lots of information on the remote page. $header['content']
will have both the content of the website and the headers, $header[header_size]
will contain the length of that header so you can use substr
to split those up.
Then it's just a matter of using echo
and header
to proxy the page.
You can use the PHP cURL functions to achieve this functionality:
http://www.php.net/curl
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// grab URL and pass it to the browser
$urlContent = curl_exec($ch);
From this point, you would grab the response header information using http://www.php.net/curl-getinfo. (There are several values you can grab, all listed in the documentation).
// Check if any error occured
if(!curl_errno($ch))
{
$info = curl_getinfo($ch);
header('Content-Type: '.$info['content_type']);
echo $urlContent;
}
Make sure to close out the cURL handle.
// close cURL resource, and free up system resources
curl_close($ch);
You can get the html of the next page with curl, and then echo the response.
精彩评论