Home > Backend Development > PHP Tutorial > Simple methods and techniques for php to obtain all file names in a directory and determine files and directories

Simple methods and techniques for php to obtain all file names in a directory and determine files and directories

黄舟
Release: 2023-03-06 11:40:02
Original
4155 people have browsed it

The following editor will bring you a simple method of getting all the file names in the directory and judging the files and directories in PHP. The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor and take a look.

1. PHP gets all the file names in the directory

1. Open the directory handle of the directory to be operated

Code example:

//打开当前目录下的目录pic下的子目录common。
$handler = opendir('pic/common');
Copy after login

2. Loop to read all files in the directory

Code example:

/*其中$filename = readdir($handler)
每次循环时将读取的文件名赋值给$filename,$filename !== false。
一定要用!==,因为如果某个文件名如果叫'0′,或某些被系统认为是代表false,用!=就会停止循环
*/
while( ($filename = readdir($handler)) !== false ) 
{
 //略过linux目录的名字为'.'和‘..'的文件
 if($filename != “.” && $filename != “..”)
 {  
  //输出文件名
   echo $filename;
  }
}
Copy after login

3. Close the directory

Code example:

closedir($handler);
Copy after login

2, PHP file and directory judgment function

<?php
//检查上级目录下的目标对象logo.jpg是否是文件。
$checkResult = is_file(&#39;../logo.jpg&#39;);
Copy after login

Description: If the target object is a file, the system returns true, otherwise it returns false.

Code example:

<?php
//检查上级目录下的目标对象logo.jpg是否是目录。
$checkResult = is_dir(&#39;../logo.jpg&#39;);
Copy after login

Description: Returns true if the target object is a directory system, otherwise returns false.

The above is the content of simple methods and techniques for PHP to obtain all file names in a directory and determine files and directories. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!

Related labels:
php
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