我正在寻找用PHP代理页面的最快速,最简单的方法.我不希望重定向用户,我只是希望我的脚本返回相同的内容,响应代码和标题作为另一个远程URL.
kle*_*tte 13
echo file_get_contents('proxypage');
那会有用吗?
编辑:
第一个答案有点短,我不相信它会像你想的那样处理标题.
但是你也可以这样做:
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;
}
Run Code Online (Sandbox Code Playgroud)
这将返回一个包含远程页面上大量信息的数组.$header['content'] 将同时拥有网站内容和标题,$header[header_size]将包含该标题的长度,以便您可以使用它substr来分割它们.
然后,这只是使用echo和header代理页面的问题.
小智 5
您可以使用PHP 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);
Run Code Online (Sandbox Code Playgroud)
从这一点开始,您将使用http://www.php.net/curl-getinfo获取响应头信息。(您可以获取多个值,所有值都在文档中列出)。
// Check if any error occured
if(!curl_errno($ch))
{
$info = curl_getinfo($ch);
header('Content-Type: '.$info['content_type']);
echo $urlContent;
}
Run Code Online (Sandbox Code Playgroud)
确保关闭cURL句柄。
// close cURL resource, and free up system resources
curl_close($ch);
Run Code Online (Sandbox Code Playgroud)