最近在做一个项目需要用到判断文件是否存在,接下来吾爱编程就为大家介绍一下关于php判断本地文件及远程文件是否存在的方法,有需要的小伙伴可以参考一下:
1、判断本地文件是否存在:
file_exists函数可以检查文件或目录是否存在,如果由 filename 指定的文件或目录存在则返回 TRUE,否则返回 FALSE。<?php
$filename = '/static/images/logo.png';
if (file_exists($filename)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
?>
2、判断远程文件是否存在
我们可以使用get_headers函数来取得服务器响应一个 HTTP 请求所发送的所有标头,如果包含200或者304即存在。<?php
$remote_file = 'http://www.itbiancheng.com/static/images/logo.png';
$header = get_headers($remote_file, true);
var_dump(isset($header[0]) && (strpos($header[0], '200') || strpos($header[0], '304')));
如果判断的文件地址是https的,需要在get_headers函数执行之前添加如下代码:stream_context_set_default( [
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
],
]);
以上就是吾爱编程为大家介绍的php判断本地文件及远程文件是否存在的方法,了解更多相关文章请关注吾爱编程网!