


A detailed discussion of the basic operations of PHP file directories_PHP Tutorial
Talk in detail about the basic operations of PHP file directories
We know that temporarily declared variables are stored in memory, even static variables will be released after the script is finished running. So, if you want to save the contents of a variable for a long time, one way is to write it to a file and put it on the hard disk or server. For this, you must be familiar with file operations.
1. Obtain the attribute information of the file
First of all, files have types. Under Linux, there are block (block devices, such as disk partitions, CD-ROMs), char (devices that use characters as input, such as keyboards and printers), and dir (directory types, which are also files. A kind of), fifo (named pipe, the explanation is to transfer information from one process to another process), file (ordinary file), link (link, similar to the shortcut under win), unknown (unknown type) 7 major Class, under win, there are only 3 classes: file, dir and unknown. Linux scumbag said that he must work hard on Linux-_-, he was born for Linux.
There are several functions for obtaining types: filetype: obtain the type; is_file: determine whether it is a normal file; is_link: determine whether it is a link.
There are several functions for obtaining attributes:
file_exists: Determine whether the file or directory exists;
filesize: Get the file size;
is_readable, is_writable, is_executable: whether it is readable, writable, and executable;
filectime, filemtime, fileatime: Get the creation time (create), modification time (modify), and access time (access) of the file, all returning timestamps;
stat: Get some basic information of the file and return a mixed array of index and association.
For example, you can determine the file type like this:
The code is as follows:
function getFileType($path){ // Get file type
switch(filetype($path)){
case 'file': return 'ordinary file';
case 'dir': return 'directory';
case 'block': return 'block device file';
case 'char': return 'transfer device base on char';
case 'fifo': return 'named pipes';
case 'link': return 'symbol link';
default: return 'unknown type';
}
}
filesize returns data in bytes. If the file number is large or very large, you can process the number first. The code is as follows
The code is as follows:
// Handle file size
function getSize($path = '', $size = -1){
if($path !== null && $size == -1){ // Calculate the size by passing only the path, or you can also make it only process numbers
$size = filesize($path);
}
if($size >= pow(2, 40)){
return round($size/pow(2, 40), 2).'TB';
}
else if($size >= pow(2, 30)){
return round($size/pow(2, 30), 2).'GB';
}
else if($size >= pow(2, 20)){
return round($size/pow(2, 20), 2).'MB';
}
else if($size >= pow(2, 10)){
return round($size/pow(2, 10), 2).'KB';
}
else{
return round($size, 2).'Byte';
}
}
Now to get the file information comprehensively, the code is as follows:
The code is as follows:
function getFileInfo($path){
if(!file_exists($path)){ // Determine whether the file exists
echo 'file not exists!
';
return;
}
if(is_file($path)){ // It is a file, print the basic file name
echo basename($path).' is a file
';
}
if(is_dir($path)){ // It is a directory, return the directory
echo dirname($path).' is a directory
';
}
echo 'file type:'.getFileType($path).'
'; // Get file type
echo 'file size:'.getSize($path).'
'; // Get file size
if(is_readable($path)){ // Is it readable
echo basename($path).' is readable
';
}
if(is_writeable($path)){ // Whether it is writable
echo basename($path).' is writeable
';
}
if(is_executable($path)){ // Whether it is executable
echo basename($path).' is executable
';
}
// The touch function can modify these times
echo 'file create time: '.date('Y-m-d H:i:s', filectime($path)).'
'; // Creation time
echo 'file modify time: '.date('Y-m-d H:i:s', filemtime($path)).'
'; // Modification time
echo 'last access time: '.date('Y-m-d H:i:s', fileatime($path)).'
'; // Last access time
echo 'file owner: '.fileowner($path).'
'; // File owner
echo 'file permission: '.substr(sprintf('%o', (fileperms($path))), -4).'
'; // File permission, octal output
echo 'file group: '.filegroup($path).'
'; // The group where the file is located
}
The effect is as follows:
File permissions, group and other functions are also used in the code. It is necessary to explain it (please correct it if it is wrong). The permissions of a file are divided into readable, writable and executable. It is generally expressed as: rwx. The corresponding letters indicate readable, writable and executable. The specified values from front to back are 4, 2, 1. The result of adding the three values is the largest. is 7, so 0666 is expressed in octal, which looks very convenient. If it is 7, it means that this file has these three permissions, so why is 0666 printed? We all know that there is a user under Windows. Under Linux, similar to Windows, there is also a user logged in, so a file may be owned by the user. A user also has its own group and the system. There are other groups in the file (guessing that this division should be a management need), so for 0666, the first 6 represents the user's permissions on the file, and the second 6 represents the user's group's permissions on the file. Permissions, the third 6 indicates the permissions of other groups (so that you don’t have to distinguish other users except this group one by one), 6 means that the file is readable and writable (you will know if it is executable under win) is an .exe file).
2. Directory operations
Directory reading, opendir: open a directory and return a handle pointing to the content in the directory. If the content in the directory is regarded as sequential data, such as an array arranged in order, this handle will Points to the beginning of this array. In fact, the system will sort the contents of this directory according to dictionary, whether it is a file or a subdirectory. readdir: Read the contents of the next directory, return the file name, and automatically point to the next file/directory in the directory, so reading the contents of a directory, excluding the contents of subdirectories, requires a loop to control, in After reading, the handle variable must be closed. The same is true when C language reads files. Open and close. Take my machine as an example:
The code is as follows:
//Read directory
$dir = 'F://';
echo 'details in '.$dir.'
';
if(is_dir($dir)){
if(($handle = opendir($dir)) == false){ // Get directory handle
echo 'open dir failed';
return;
}
while(($name = readdir($handle)) != false){ // Loop to read the contents of this directory
$filepath = $dir.'/'.$name;
echo 'name: '.$name.' type: '.filetype($filepath).'
';
}
closedir($handle); // Close directory handle
}
else{
echo $dir.' is not a directory
}
The effect is as follows:
You can see that the system actually sorts the contents of the directory in a dictionary that ignores case.
To calculate the size of the directory, we know that the size of the file can be obtained by filesize, but there is no function in PHP that specifically calculates the size of the directory. Of course, there are functions disk_total_space (calculating the total hard disk space) and disk_free_space (calculating the available hard disk space) in PHP to calculate the size of the hard disk, but I tried disk_free_space and it seemed that the calculation was wrong. Because filesize calculates the size of a file, recursion needs to be used. When it is a directory, go in and continue to calculate the size of the subdirectory. If it is a file, get the file size and add the return. The code is as follows:
The code is as follows:
// Directory size calculation
function getDirSize($dirpath){
$size = 0;
if(false != ($handle = opendir($dirpath))){
while(false != ($file = readdir($handle))){
if($file == '.' || $file == '..') //Pay attention to the dots and dots in the filter directory
continue;
$filepath = $dirpath.'/'.$file; // Be preceded by the path
if(is_file($filepath)){ // It is the calculated file size
$size += filesize($filepath);
}
else if(is_dir($filepath)){ // If it is a directory, continue to calculate the files in the directory
$size += getDirSize($filepath);
}
else{
$size += 0;
}
}
closedir($handle);
}
return $size;
}
$dirsize = 'F:/size';
$size = getDirSize($dirsize);
echo 'dir size: '.getSize(null, $size).'
'; // Call the previous data processing function
I created a size file on the F drive and randomly created some subdirectories and documents. The effect is as follows. The left side is obtained by the program, and the right side is obtained by right-clicking to view the folder properties for comparison.
The creation and deletion of directories are mainly used, mkdir: create a new directory, rmdir: delete a non-empty directory, note that it can only be non-empty, the code is as follows:
The code is as follows:
//Create and delete directories
$newDirPath = 'F:/newDir';
if(true == @mkdir($newDirPath, 0777, true)){ // Add @ because php itself may throw a warning
when the file already exists echo 'create directory '.$newDirPath.' successfully
';
}
else{
if(file_exists($newDirPath))
echo 'directory '.$newDirPath.' has existed
';
else
echo 'create directory '.$newDirPath.' failed
';
}
if(true == @rmdir('F:/aaa')) //Only non-empty directories can be deleted. If a non-existing directory is deleted, a warning
will be automatically thrown echo 'remove successfully
';
Then the question is, what if you want to delete a non-empty directory? You have to write it yourself. The idea is still recursive, because PHP only provides the delete file function unlink, so when deleting a directory, opendir first, and then Enter, if it is a file, delete it directly. If it is a directory, continue to enter and use this method to process. Of course, a bool variable can be returned to indicate whether the deletion is successful. The code is as follows:
The code is as follows:
// Delete file unlink
// Delete the contents of the directory, then delete the directory
function clearDir($dirpath){
if(file_exists($dirpath)){
if(false != ($handle = opendir($dirpath))){
while(false != ($name = readdir($handle))){
if($name == '.' || $name == '..')
continue;
$filename = $dirpath.'/'.$name;
if(is_dir($filename))
clearDir($filename);
if(is_file($filename))
@unlink($filename);
}
closedir($handle);
rmdir($dirpath);
}
else{
return false;
}
}
else{
return false;
}
return true;
}
I have to say that a big pitfall encountered here is the two ghost things (dot and dot). Under every folder in the operating system, there will be . and.., They represent the current directory and the superior directory of the current directory. What's terrible is that it was not displayed when reading the directory, causing the recursive function to become an infinite loop, because . and .. are at the front of each directory and must be read first. If they are not filtered, they will first read ., which represents this directory, and then recursively enter this directory... These two are the default ones under the operating system, and they are the connectors between this directory and the upper-level directory.
By calculating the size of the directory and deleting the code for non-empty directories, it is very easy to write copy and cut directories. Very similar recursive ideas require the use of the copy file function copy and the file movement function rename. This is quite interesting, rename , literally rename, but doesn’t renaming it to another directory mean cutting it? -_-
3. File reading and writing
Some file reading operations in PHP are very similar to C language, so it is relatively simple. The steps are to first open the file to get the handle, check for errors, then read and write, then close. Get into the habit of closing after opening and processing. It’s a good habit to remember that if a file in C language is not closed, an error will be reported if it is opened twice. I don’t know if I remember correctly, so strict programs have a lot of processing, such as first verifying that the file exists, and then verifying that it is readable. Writability, then close it first, and then open it again. When you open it, you have to check whether it was opened correctly... When opening a file, you must choose the mode to open the file, which determines whether we read or write the file. , of course, is useful for functions that require such operations.
Write files. There are only a few file writing functions: fwrite, fputs, and file_put_contents. Among them, fwrite has the same effect as fputs. file_put_contents writes some content to the file at one time. It does not need to specify the open mode. At the same time, it can also be appended. Or overwrite existing file content, such as:
The code is as follows:
// write fwrite(alias fputs)
$filepath = 'F:/10m.txt';
function writeSome($filepath){
if(($handle = fopen($filepath, 'r+')) == true){
for($i=0; $i fwrite($handle, $i." write somethingrn"); //windws uses rn as the newline character
fclose($handle);
}
}
file_put_contents($filepath, 'use file_put_contents function', FILE_APPEND); // Additional content
Read files. There are many functions for reading files, including fread (read specified bytes), fgetc (read one), fgets (read one line), file (read all, allocated to an array by line) (return in), file_get_contents (read all returned strings by default), readfile (directly output the contents of the file to the cache, the effect is to output directly on the browser), as fread, fget, fgets run, the file pointer will automatically go to Go later. Therefore, continuous reading is best controlled by loop. What to do when the end of the file is reached? The EOF flag indicates that the end of the file has been reached. It is best to use feof to detect whether the end of the file has been reached. Without further ado, let’s look at the code:
The code is as follows:
// fread read
function readSome($filepath){
if(($handle = @fopen($filepath, 'r')) == true){
while(!feof($handle)){ // Determine whether the end of the file is reached
$str = fread($handle, 10); // When fread reads, the file pointer automatically moves backward
echo $str.'
';
}
}
}
If you want a more flexible reading method, you must use fseek and rewind. They can move the file pointer to a specific position. fseek is very flexible and can be moved directly to the beginning or end, or moved forward or backward from the current position. , read the desired content, ftell can also inform the current location, such as:
The code is as follows:
function readFun($filepath){
if(($handle = @fopen($filepath, 'r')) != false){
echo 'current position: '.ftell($handle).'
'; // Output the current file pointer position of the file, in bytes, 0 means the beginning
$str = fread($handle, 3); // Read 3 bytes, and the pointer automatically moves back 3 bytes
echo 'read content: '.$str.'
';
echo 'current position: '.ftell($handle).'
';
fseek($handle, 5, SEEK_CUR); // Move the file pointer back 5 bytes from the current position
echo 'current position: '.ftell($handle).'
';
$str = fread($handle, 5);
echo 'read content: '.$str.'
';
echo 'current position: '.ftell($handle).'
';
rewind($handle); // Return to the beginning of the file
echo 'current position: '.ftell($handle).'
';
fseek($handle, 0, SEEK_END); // Move to the end of the file
echo 'current position: '.ftell($handle).'
';
fclose($handle); // Close file
}
}
For example, I am now using this method to read a text file written from a to z and see the effect:
The above is all about PHP directory file operations. It is also a personal understanding record. I hope it will be helpful to everyone

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 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 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 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.

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 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.

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

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version
Chinese version, very easy to use

WebStorm Mac version
Useful JavaScript development tools