Home  >  Article  >  Backend Development  >  How to determine whether local and remote files exist through php

How to determine whether local and remote files exist through php

jacklove
jackloveOriginal
2018-06-08 16:50:022483browse

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));?>

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;http://www.csdn.net/css/logo.png&#39;;$header = get_headers($remote_file, true);
var_dump(isset($header[0]) && (strpos($header[0], &#39;200&#39;) || strpos($header[0], &#39;304&#39;)));?>

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)); // falsevar_dump(check_file_exists($file2)); // true?>

This article explains how to determine whether local and remote files exist through php. For more related content, please pay attention to the php Chinese website.

Related recommendations:

Explanation on the method of converting rows and columns of mysql table data

Explanation on the PHP log class

How to combine multiple one-dimensional arrays into a two-dimensional array through PHP

The above is the detailed content of How to determine whether local and remote files exist through php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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