Example analysis of how PHP determines whether local and remote files exist

黄舟
Release: 2023-03-15 19:28:01
Original
1497 people have browsed it

This article introduces the method of using PHP to determine whether a file exists, supports local and remote file determination, and provides complete calling code and demonstration.

1. Determine whether the local file exists

To determine whether the local file exists, you can use the file_exists method to determine.

<?php
$file = &#39;test.jpg&#39;;
var_dump(file_exists($file));?>
Copy after login

2. Determine whether the remote file exists

To determine whether the remote file exists, you cannot use the file_exists method, but get the header of the remote file to determine whether it exists, such as The returned HTTP_CODE is 200 or 304.

<?php
// 屏蔽域名不存在等访问问题的警告
error_reporting(E_ALL ^ (E_WARNING|E_NOTICE));
$remote_file = &#39; 
$header = get_headers($remote_file, true);
var_dump(isset($header[0]) && (strpos($header[0], &#39;200&#39;) || strpos($header[0], &#39;304&#39;)));?>
Copy after login

3. Complete code

<?php/**
 * 判断文件是否存在,支持本地及远程文件
 * @param  String  $file 文件路径
 * @return Boolean
 */function check_file_exists($file){

    // 远程文件
    if(strtolower(substr($file, 0, 4))==&#39;http&#39;){        
    $header = get_headers($file, true);        
    return isset($header[0]) && (strpos($header[0], &#39;200&#39;) || strpos($header[0], &#39;304&#39;));    // 本地文件
    }else{        
    return file_exists($file);
    }

}
// 屏蔽域名不存在等访问问题的警告
error_reporting(E_ALL ^ (E_WARNING|E_NOTICE));
$file1 = &#39;test.jpg&#39;;$file2 = &#39;http://www.csdn.net/css/logo.png&#39;;

var_dump(check_file_exists($file1)); // false
var_dump(check_file_exists($file2)); // true
?>
Copy after login

The above is the detailed content of Example analysis of how PHP determines whether local and remote files exist. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!