如何检查网页是否存在.jQuery和/或PHP

Mos*_*oss 6 javascript php validation url http-status-codes

我希望能够验证表单以检查网站/网页是否存在.如果它返回404错误,那么肯定不应该验证.如果有重定向...我愿意接受建议,有时重定向会转到错误页面或主页,有时他们会转到您要查找的页面,所以我不知道.也许对于重定向,可能会有一个特殊通知,向用户建议目标地址.

到目前为止我发现的最好的事情是这样的:

$.ajax({url: webpage ,type:'HEAD',error:function(){
    alert('No go.');
}});
Run Code Online (Sandbox Code Playgroud)

404和200的问题没有问题,但如果你做了类似'http://xyz'网址的事情就会挂起来.302等也触发错误处理程序.

这是一个通用的问题我想要一个完整的工作代码示例,如果有人可以制作一个.这对很多人来说都很方便.

Sam*_*bee 4

听起来你并不关心网页的内容,你只想看看它是否存在。以下是我在 PHP 中的做法 - 我可以阻止 PHP 占用页面内容的内存。

/*
 * Returns false if the page could not be retrieved (ie., no 2xx or 3xx HTTP
 * status code). On success, if $includeContents = false (default), then we
 * return true - if it's true, then we return file_get_contents()'s result (a
 * string of page content).
 */
function getURL($url, $includeContents = false)
{
  if($includeContents)
    return @file_get_contents($url);

  return (@file_get_contents($url, null, null, 0, 0) !== false);
}
Run Code Online (Sandbox Code Playgroud)

为了减少冗长,请用此替换上面函数的内容。

return ($includeContents) ? 
               @file_get_contents($url) :  
               (@file_get_contents($url, null, null, 0, 0) !== false)
;
Run Code Online (Sandbox Code Playgroud)

有关如何使用流上下文指定 HTTP 标头的详细信息,请参阅http://www.php.net/file_get_contents 。

干杯。