如何检查网页是否存在. jQuery和/或PHP [英] How to check if a webpage exists. jQuery and/or PHP
问题描述
我希望能够验证表单以检查网站/网页是否存在.如果返回404错误,则绝对不应该验证.如果有重定向...我愿意接受建议,有时重定向会转到错误页面或主页,有时它们会转到您要查找的页面,所以我不知道.也许对于重定向,可能会有一条特别的提示向用户建议目标地址.
I want to be able to validate a form to check if a website/webpage exists. If it returns a 404 error then that definitely shouldn't validate. If there is a redirect...I'm open to suggestions, sometimes redirects go to an error page or homepage, sometimes they go to the page you were looking for, so I don't know. Perhaps for a redirect there could be a special notice that suggests the destination address to the user.
到目前为止,我发现的最好的事情是这样的:
The best thing I found so far was like this:
$.ajax({url: webpage ,type:'HEAD',error:function(){
alert('No go.');
}});
这对于404和200来说没有问题,但是如果对URL执行'http://xyz'
之类的操作,它只会挂起. 302之类的东西也会触发错误处理程序.
That has no problem with 404's and 200's but if you do something like 'http://xyz'
for the url it just hangs. Also 302 and the like trigger the error handler too.
这是一个足够通用的问题,如果有人可以创建一个完整的工作代码示例,我想得到一个完整的示例.对于许多人来说,这可能很方便.
This is a generic enough question I would like a complete working code example if somebody can make one. This could be handy for lots of people to use.
推荐答案
听起来好像您并不在乎网页的内容,只想看看它是否存在.这是我在PHP中的处理方式-我可以阻止PHP占用页面内容的内存.
It sounds like you don't care about the web page's contents, you just want to see if it exists. Here's how I'd do it in PHP - I can stop PHP from taking up memory with the page's contents.
/*
* 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);
}
为了减少冗长,将上面函数的内容替换为此.
For less verbosity, replace the above function's contents with this.
return ($includeContents) ?
@file_get_contents($url) :
(@file_get_contents($url, null, null, 0, 0) !== false)
;
有关如何指定HTTP的详细信息,请参见 http://www.php.net/file_get_contents 标头使用流上下文.
See http://www.php.net/file_get_contents for details on how to specify HTTP headers using a stream context.
干杯.
这篇关于如何检查网页是否存在. jQuery和/或PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!