检索重定向网址的内容 |卷曲与上下文
Retrieving contents of re-directed url | curl vs. contexts
我正在使用这样的file_get_contents
file_get_contents( $url1 ).
但是,实际网址的内容来自$url 2。
这是一个具体案例:
$url1 = gmail.com
$url2 = mail.google.com
我需要一种方法在PHP或JavaScript中以编程方式抓取$url 2。
我相信
您可以通过创建上下文来做到这一点:
$context = stream_context_create(array('http' =>
array(
'follow_location' => false
)));
$stream = fopen($url, 'r', false, $context);
$meta = stream_get_meta_data($stream);
$meta应包括(除其他事项外)用于保存重定向 URL 的状态代码和位置标头。如果$meta表示 200,则可以使用以下方法获取数据:
$meta = stream_get_contents($stream)
不利的一面是,当您获得 301/302 时,您必须使用 Location 标头中的 url 再次设置请求。 起泡,冲洗,重复。
如果你想
提取当前的网址,在JS中你可以使用window.location.hostname
我不明白为什么你想要PHP或JavaScript。我的意思是。。。他们在处理问题方面有点不同。
假设你想要一个服务器端的PHP解决方案,这里有一个全面的解决方案。代码太多,无法逐字复制,但是:
function follow_redirect($url){
$redirect_url = null;
//they've also coded up an fsockopen alternative if you don't have curl installed
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
//extract the new url from the header
$pos = strpos($response, "Location: ");
if($pos === false){
return false;//no new url means it's the "final" redirect
} else {
$pos += strlen($header);
$redirect_url = substr($response, $pos, strpos($response, "'r'n", $pos)-$pos);
return $redirect_url;
}
}
//output all the urls until the final redirect
//you could do whatever you want with these
while(($newurl = follow_redirect($url)) !== false){
echo $url, '<br/>';
$url = $newurl;
}
相关文章:
- 通过javascript重定向html传递php变量
- JavaScript下拉菜单-点击按钮并根据所选值重定向到url
- 使用angular重定向到html页面
- 如何在chrome扩展中重定向到html页面
- 无法从jquery Mobile导航栏重定向到另一个页面
- ng视图外的链接重定向到ng视图内的页面
- 在phonegap应用程序内部重定向不起作用
- CORS-重定向到第二个GET正在接收的页面
- AJAX不会在文件上传后重定向到网页-POST方法
- 重定向时角度刷新浏览器
- 通过链接重定向不;我不在jstree中工作
- 根据select选项元素将表单重定向到不同的URL
- 通过JQuery重定向到另一个页面
- 重定向到“父窗口”
- 重定向iFrame中的父URL
- PHP-如何重定向到同一页面并更改DOM's
- chrome.tabs.update() 重定向到 'chrome-extension://invalid/'
- 我们如何在不更改url的情况下使用锚点点击从一个页面重定向到另一个页面
- 使用AngularJS中的UI路由器将状态重定向到默认子状态
- 检索重定向网址的内容 |卷曲与上下文