Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to proxy another page in PHP

Tags:

php

proxy

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 and headers as another remote URL.

like image 845
Nathan H Avatar asked Jun 21 '11 13:06

Nathan H


2 Answers

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 echoand header to proxy the page.

like image 166
klennepette Avatar answered Sep 20 '22 23:09

klennepette


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);
like image 41
forgueam Avatar answered Sep 22 '22 23:09

forgueam