search
HomeBackend DevelopmentPHP TutorialBasic Introduction to PHP - File and Directory Operations_PHP Tutorial

Basic Introduction to PHP - File and Directory Operations_PHP Tutorial

Jul 13, 2016 pm 04:59 PM
phpgetting StartedaboutfunctionandBaseoperatedocumentfriendofTable of contents

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
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools