如何检查页面是否存在

How to check if page exists?

本文关键字:是否 存在 检查 何检查      更新时间:2023-09-26

可能重复:
如何使用PHP检查远程文件是否存在
如何检查网页是否存在。jQuery和/或PHP

如何使用php或javascript检查来自不同域的页面是否存在?

我试过这个:

function getURL($url, $includeContents = false)
{
  if($includeContents)
    return @file_get_contents($url);
  return (@file_get_contents($url, null, null, 0, 0) !== false);
}

$test = getURL("http://www.google.com");
echo "<script language='javascript'>alert('$test');</script>";

但它不起作用。

如果我使用本地url,它是有效的。


如何解决这个问题?

要从其他页面读取内容,我正在使用CURL并像一样进行操作

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$page_content = curl_exec($ch);   
curl_close($ch); 
if ($page_content != "false") {
 // do something with content  
} else {
  // this page is not available
}

这是纯Javascript无法完成的。

在PHP中,请求页面并检查它是否有200http响应代码。这个结果可以通过ajax调用返回给JS,这样JavaScript就可以相应地显示消息或执行其他操作。