我如何检查一个URL是否存在(不是404)在PHP?
当前回答
get_headers()返回一个数组,其中包含服务器响应HTTP请求时发送的报头。
$image_path = 'https://your-domain.com/assets/img/image.jpg';
$file_headers = @get_headers($image_path);
//Prints the response out in an array
//print_r($file_headers);
if($file_headers[0] == 'HTTP/1.1 404 Not Found'){
echo 'Failed because path does not exist.</br>';
}else{
echo 'It works. Your good to go!</br>';
}
其他回答
检查url是在线还是离线——
function get_http_response_code($theURL) {
$headers = @get_headers($theURL);
return substr($headers[0], 9, 3);
}
检查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;
}
在某些服务器中不能使用curl 你可以用这个代码
<?php
$url = 'http://www.example.com';
$array = get_headers($url);
$string = $array[0];
if(strpos($string,"200"))
{
echo 'url exists';
}
else
{
echo 'url does not exist';
}
?>
function URLIsValid($URL)
{
$exists = true;
$file_headers = @get_headers($URL);
$InvalidHeaders = array('404', '403', '500');
foreach($InvalidHeaders as $HeaderVal)
{
if(strstr($file_headers[0], $HeaderVal))
{
$exists = false;
break;
}
}
return $exists;
}
推荐文章
- 格式化字节到千字节,兆字节,千兆字节
- 如何在PHP中获得变量名作为字符串?
- 用“+”(数组联合运算符)合并两个数组如何工作?
- 创建url的安全字符是什么?
- Laravel PHP命令未找到
- 如何修复从源代码安装PHP时未发现xml2-config的错误?
- 在PHP中对动态变量名使用大括号
- 如何从对象数组中通过对象属性找到条目?
- 如何从关联数组中删除键及其值?
- PHP字符串中的花括号
- PHP -如何最好地确定当前调用是否来自CLI或web服务器?
- 无法打开流:没有这样的文件或目录
- 在php中生成一个随机密码
- 如何通过PHP检查URL是否存在?
- 如何防止页面刷新时重新提交表单(F5 / CTRL+R)