我如何检查一个URL是否存在(不是404)在PHP?
当前回答
以上所有解决方案+额外的糖。(终极AIO解决方案)
/**
* Check that given URL is valid and exists.
* @param string $url URL to check
* @return bool TRUE when valid | FALSE anyway
*/
function urlExists ( $url ) {
// Remove all illegal characters from a url
$url = filter_var($url, FILTER_SANITIZE_URL);
// Validate URI
if (filter_var($url, FILTER_VALIDATE_URL) === FALSE
// check only for http/https schemes.
|| !in_array(strtolower(parse_url($url, PHP_URL_SCHEME)), ['http','https'], true )
) {
return false;
}
// Check that URL exists
$file_headers = @get_headers($url);
return !(!$file_headers || $file_headers[0] === 'HTTP/1.1 404 Not Found');
}
例子:
var_dump ( urlExists('http://stackoverflow.com/') );
// Output: true;
其他回答
cURL可以返回HTTP代码,我不认为所有额外的代码是必要的?
function urlExists($url=NULL)
{
if($url == NULL) return false;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($httpcode>=200 && $httpcode<300){
return true;
} else {
return false;
}
}
检查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 = 'http://google.com';
$not_url = 'stp://google.com';
if (@file_get_contents($url)): echo "Found '$url'!";
else: echo "Can't find '$url'.";
endif;
if (@file_get_contents($not_url)): echo "Found '$not_url!";
else: echo "Can't find '$not_url'.";
endif;
// Found 'http://google.com'!Can't find 'stp://google.com'.
这是一个解决方案,只读取源代码的第一个字节…如果file_get_contents失败,返回false…这也适用于远程文件,如图像。
function urlExists($url)
{
if (@file_get_contents($url,false,NULL,0,1))
{
return true;
}
return false;
}
到目前为止使用get_headers()的最佳和最简单的答案 最好检查字符串“200 ok”。这比检查要好得多
$file_headers = @get_headers($file-path);
$file_headers[0];
因为有时数组键值会变化。所以最好的办法是检查“200 ok”。任何URL都将在get_headers()响应的任何地方有“200 ok”。
function url_exist($url) {
$urlheaders = get_headers($url);
//print_r($urlheaders);
$urlmatches = preg_grep('/200 ok/i', $urlheaders);
if(!empty($urlmatches)){
return true;
}else{
return false;
}
}
现在检查函数是否为真或假
if(url_exist(php-url-variable-here)
URL exist
}else{
URL don't exist
}
推荐文章
- 格式化字节到千字节,兆字节,千兆字节
- 如何在PHP中获得变量名作为字符串?
- 用“+”(数组联合运算符)合并两个数组如何工作?
- 创建url的安全字符是什么?
- Laravel PHP命令未找到
- 如何修复从源代码安装PHP时未发现xml2-config的错误?
- 在PHP中对动态变量名使用大括号
- 如何从对象数组中通过对象属性找到条目?
- 如何从关联数组中删除键及其值?
- PHP字符串中的花括号
- PHP -如何最好地确定当前调用是否来自CLI或web服务器?
- 无法打开流:没有这样的文件或目录
- 在php中生成一个随机密码
- 如何通过PHP检查URL是否存在?
- 如何防止页面刷新时重新提交表单(F5 / CTRL+R)