我如何检查一个URL是否存在(不是404)在PHP?
当前回答
检查URL是否有效的其他方法可以是:
<?php
if (isValidURL("http://www.gimepix.com")) {
echo "URL is valid...";
} else {
echo "URL is not valid...";
}
function isValidURL($url) {
$file_headers = @get_headers($url);
if (strpos($file_headers[0], "200 OK") > 0) {
return true;
} else {
return false;
}
}
?>
其他回答
检查url是在线还是离线——
function get_http_response_code($theURL) {
$headers = @get_headers($theURL);
return substr($headers[0], 9, 3);
}
在检查报头是否有404错误时,需要考虑的一件事是站点不会立即生成404错误。
很多网站会检查PHP/ASP(等等)源代码中是否存在某个页面,然后将您转到404页面。在这些情况下,头基本上是由生成的404头扩展的。在这种情况下,404错误不会出现在头文件的第一行,而是第10行。
$array = get_headers($url);
$string = $array[0];
print_r($string) // would generate:
Array (
[0] => HTTP/1.0 301 Moved Permanently
[1] => Date: Fri, 09 Nov 2018 16:12:29 GMT
[2] => Server: Apache/2.4.34 (FreeBSD) LibreSSL/2.7.4 PHP/7.0.31
[3] => X-Powered-By: PHP/7.0.31
[4] => Set-Cookie: landing=%2Freed-diffuser-fig-pudding-50; path=/; HttpOnly
[5] => Location: /reed-diffuser-fig-pudding-50/
[6] => Content-Length: 0
[7] => Connection: close
[8] => Content-Type: text/html; charset=utf-8
[9] => HTTP/1.0 404 Not Found
[10] => Date: Fri, 09 Nov 2018 16:12:29 GMT
[11] => Server: Apache/2.4.34 (FreeBSD) LibreSSL/2.7.4 PHP/7.0.31
[12] => X-Powered-By: PHP/7.0.31
[13] => Set-Cookie: landing=%2Freed-diffuser-fig-pudding-50%2F; path=/; HttpOnly
[14] => Connection: close
[15] => Content-Type: text/html; charset=utf-8
)
检查URL是否有效的其他方法可以是:
<?php
if (isValidURL("http://www.gimepix.com")) {
echo "URL is valid...";
} else {
echo "URL is not valid...";
}
function isValidURL($url) {
$file_headers = @get_headers($url);
if (strpos($file_headers[0], "200 OK") > 0) {
return true;
} else {
return false;
}
}
?>
这是一个解决方案,只读取源代码的第一个字节…如果file_get_contents失败,返回false…这也适用于远程文件,如图像。
function urlExists($url)
{
if (@file_get_contents($url,false,NULL,0,1))
{
return true;
}
return false;
}
在这里:
$file = 'http://www.example.com/somefile.jpg';
$file_headers = @get_headers($file);
if(!$file_headers || $file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}
else {
$exists = true;
}
从这里和上面帖子的正下方,有一个卷曲的解决方案:
function url_exists($url) {
return curl_init($url) !== false;
}
推荐文章
- 格式化字节到千字节,兆字节,千兆字节
- 如何在PHP中获得变量名作为字符串?
- 用“+”(数组联合运算符)合并两个数组如何工作?
- 创建url的安全字符是什么?
- Laravel PHP命令未找到
- 如何修复从源代码安装PHP时未发现xml2-config的错误?
- 在PHP中对动态变量名使用大括号
- 如何从对象数组中通过对象属性找到条目?
- 如何从关联数组中删除键及其值?
- PHP字符串中的花括号
- PHP -如何最好地确定当前调用是否来自CLI或web服务器?
- 无法打开流:没有这样的文件或目录
- 在php中生成一个随机密码
- 如何通过PHP检查URL是否存在?
- 如何防止页面刷新时重新提交表单(F5 / CTRL+R)