How to proxy another page in PHP

前端 未结 3 520
旧巷少年郎
旧巷少年郎 2020-12-28 23:08

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

3条回答
  •  佛祖请我去吃肉
    2020-12-28 23:35

    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.

提交回复
热议问题