Home > Backend Development > PHP Tutorial > Basic Introduction to PHP - File and Directory Operations_PHP Tutorial

Basic Introduction to PHP - File and Directory Operations_PHP Tutorial

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-07-13 16:59:53
Original
877 people have browsed it

An article about the various operating functions and example applications of files and directories for friends who are getting started with PHP. Friends in need can simply refer to it.

This chapter can be regarded as a continuation of the previous chapter, introducing additional information besides the actual content of the file, including the file size, directory, access permissions, etc. Some functions in the file system are only valid when the server is a specific system, such as the function symlink() that changes symbolic links, the function chmod() that sets file access permissions, and the function umask() that sets directory access permissions. Etc. These are only valid in Linux systems, not Windows systems. The DirectoryIterator class provided by PHP5 and later also encapsulates many practical directory operations

The code is as follows Copy code
 代码如下 复制代码

//------------- 采用DirectoryIterator类迭代目录中的文件 -------------
foreach(new directoryIterator('/usr/local/images') as $file){
 print $file->getPathname()."n";
}

//------------- PHP5之前版本的实现方式 -------------
$d = opendir('/usr/local/images') or die($php_errormsg);
while(false !==($f = readdir($d))){
 print $f."n";
}

//------------- Use the DirectoryIterator class to iterate files in the directory -------------
foreach(new directoryIterator('/usr/local/images') as $file){
print $file->getPathname()."n";
} //------------- Implementation method of previous versions of PHP5 -------------
$d = opendir('/usr/local/images') or die($php_errormsg);
while(false !==($f = readdir($d))){
print $f."n";
}

closedir($d);File information function
Function name What file information does the function provide?
file_exists() Whether the file exists
fileatime() last access time
filectime() The last modification time of file inode
filegroup() gets the file group (returns an integer)
fileinode() gets the number of information nodes of the file (returns an integer)
filemtime() gets the time when the file data block was last written (returns Unix timestamp)
fileowner() gets the owner of the file (returns user ID)
fileperms() obtains file permissions
filesize() gets the file size in bytes
filetype() gets the file type, may return fifo, char, dir, block, link, file and unknown
is_dir() determines whether the given file name is a directory
is_executable() determines whether the given file name is executable (available for Windows since PHP5.0.0)
is_file() determines whether the given file name is a normal file
is_link() determines whether the given file name is a symbolic link
is_readable() determines whether the given file name is readable
is_writable() determines whether the given file name is writable

Directory related functions
Function name What file information does the function provide?
mkdir() creates a new directory, the second parameter can be used to set access permissions
rmdir() delete directory
rename() renames a file or directory

Directory class related methods
The DirectoryIterator class encapsulates many directory-related methods

Method name What directory information does the function provide?
isDir() determines whether the given DirectoryIterator item object is a directory
isDot() determines whether the current DirectoryIterator item object is ‘.’ or ‘..’
isFile() determines whether the current DirectoryIterator item object is a valid file
isLink() determines whether the current DirectoryIterator item object is a connection
isReadable() determines whether the current DirectoryIterator item object is readable
isWritable() determines whether the current DirectoryIterator item object is writable
isExecutable() determines whether the current DirectoryIterator item object is executable
getATime() gets the last access time of the current Iterator item
getCTime() Gets the last modification time of the current Iterator item
getMTime() Gets the time when the current Iterator item file data block was last written
getFilename() Gets the current Iterator item file name (with extension)
getPathname() gets the current Iterator item path name
getPath() gets the current Iterator item path name and file name
getGroup() gets the current Iterator item group ID
getOwner() gets the current Iterator item owner ID
getPerms() Gets the current Iterator item permissions
getSize() gets the current Iterator item file size
getType() gets the current Iterator item type, which may be file, link or dir
getInode() gets the inode node number of the current Iterator item

File timestamps solved
The touch() function modifies the update time of the file

The fileatime() function returns the last time the file was opened for reading or writing

The filemtime() function returns the last time the file content was modified

The filectime() function returns the last time the file content or metadata was modified

Get file information
An array containing file-related information can be obtained through stat(). Similar to this function is the fstat() function. This function takes a file handle as a parameter (returned by fopen() or popen()). lstat() is used to Get information about a symbol or file connection.

Numeric index String index Description
0 dev device number
1 ino information node number
2 mode protection mode
3 nlink Number of connected connections
4 uid owner user ID
5 gid group ID
6 rdev device type, if it is an inode device
7 size file size in bytes
8 atime time of last access (Unix timestamp)
9 mtime Last modified time (Unix timestamp)
10 ctime Last changed time (Unix timestamp)
11 blksize file system IO block size
12 blocks The number of blocks occupied

Modify file permissions
The chmod() function modifies file permissions

The chown() function modifies the owner of the file

The chgrp() function modifies the group to which the file belongs

Note: The above 3 functions are invalid in Windows system
Get information about each part of the file name
The basename() function can obtain the file name, the dirname() function can obtain the path name, and pathinfo() obtains the associative array of the directory name, complete file name, extension, and file name (that is, without extension). The key names are [ dirname], [basename], [extension], [filename]

The current directory path (physical path, often used to reference other PHP files) is often obtained through the combination of dirname(__FILE__)

Delete files
Use the unlink() function to delete a file. If the deletion fails, an E_WARNING error will be generated

Tip: After PHP5.0.0, this function can also be used to delete remote files, such as FTP, etc.
Copy or move files
Use the copy(old_dir, new_dir) function to copy files, and use rename(old_dir, new_dir) to move files. The new_dir here can rename the file name.

Pattern matching file name list (fuzzy query)
If you want to query all jpg files (*.jpg) in a directory like the command line, you can use the FileterIterator subclass accept() method or glob() function of the DirectoryIterator class to obtain matching file names.

//Implementation code of FileterIterator

foreach (new ImageFilter(new DirectoryIterator('/usr/local/images')) as $img) { Print "
The code is as follows
 代码如下 复制代码

class ImageFilter extends FilterIterator {
    public function accept() {
        return preg_match('@.(gif|jpe?g|png)$@i',$this->current());
    }
}
foreach (new ImageFilter(new DirectoryIterator('/usr/local/images')) as $img) {
    print "

n";
}

Copy code

 代码如下 复制代码
foreach (glob('/usr/local/docs/*.txt') as $file) {
   $contents = file_get_contents($file);
   print "$file contains $contentsn";
class ImageFilter extends FilterIterator {

Public function accept() {
           return preg_match('@.(gif|jpe?g|png)$@i',$this->current());

}
 代码如下 复制代码

$dir = new RecursiveDirectoryIterator('/usr/local');
$totalSize = 0;
foreach (new RecursiveIteratorIterator($dir) as $file) {
    $totalSize += $file->getSize();
}
print "The total size is $totalSize.n";

}
n";

}

//------------- Implementation code of glob function ------------
The code is as follows Copy code
foreach (glob('/usr/local/ docs/*.txt') as $file) { $contents = file_get_contents($file); Print "$file contains $contentsn"; }Files in recursive directories
If you want to get the file size of a directory and its subdirectories, you can use RecursiveDirectoryIterator (provides the function of subdirectory acquisition) and RecursiveIteratorIterator (flattening)
The code is as follows Copy code
$dir = new RecursiveDirectoryIterator('/usr/local'); $totalSize = 0; foreach (new RecursiveIteratorIterator($dir) as $file) { $totalSize += $file->getSize(); } print "The total size is $totalSize.n"; http://www.bkjia.com/PHPjc/631305.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/631305.htmlTechArticleAn article about the various operating functions and example applications of files and directories for friends who are getting started with PHP, if necessary Friends can simply refer to it. This chapter can be regarded as a continuation of the previous chapter...
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template