Table of Contents
Basic operations of file directories in PHP
Home Backend Development PHP Tutorial Basic operations of file directories in PHP_PHP tutorial

Basic operations of file directories in PHP_PHP tutorial

Jul 13, 2016 am 10:14 AM
Base document Table of contents

Basic operations of file directories in PHP

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 of the ways is to write it to a file and put to a hard drive or server, for which file operations must be familiar.
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, printers), dir (directory types, directories 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. The Linux scumbag said that he must work hard on Linux-_-, he is completely 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), access time (access) of the file, all return timestamp;
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:
Copy code
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';
}
}
Copy code
filesize returns data in bytes. If the file is large or very large, you can process the numbers first. The code is as follows
Copy code
// Process file size
function getSize($path = '', $size = -1){
if($path !== null && $size == -1){ // Calculate the size by passing only the path, or you can 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';
    }
}
Copy code
Now let’s get the file information comprehensively. The code is as follows:
Copy code
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)){ // is the directory, return to the directory
echo dirname($path).' is a directory
';
} }
echo 'file type:'.getFileType($path).'
'; // Get the file type
echo 'file size:'.getSize($path).'
'; // Get the file size
if(is_readable($path)){ // Is it readable
echo basename($path).' is readable
';
} }
if(is_writeable($path)){ // Is it 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
}
Copy code
The effect is as follows:
The code also uses functions such as file permissions and groups. 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:
Copy code
// Directory reading
$dir = 'F://';
echo 'details in '.$dir.'
';
if(is_dir($dir)){
if(($handle = opendir($dir)) == false){ // Get the directory handle
echo 'open dir failed';
return;
} }
while(($name = readdir($handle)) != false){ // Loop to read the contents of the directory
$filepath = $dir.'/'.$name;
echo 'name: '.$name.' type: '.filetype($filepath).'
';
    }
closedir($handle);
}
else{
echo $dir.' is not a directory';
}
Copy code
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 a directory, we know that the size of a file can be obtained by filesize, but there is no function in PHP that specifically calculates the size of a 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:
Copy code
// Directory size calculation
function getDirSize($dirpath){
$size = 0;
if(false != ($handle = opendir($dirpath))){
while(false != ($file = readdir($handle))){
                                                                                                                                                                                                                                           
                  continue;
                                                                             
                                                                                                                                  $filepath = $dirpath.'/'.$file;
If (IS_FILE ($ Filepath)) {// is the file calculation size
$size += filesize($filepath);
        }
            else if(is_dir($filepath)){                                                                                                                                                   use   using   use using   using   using   using   using         use using ’ through   use   use using   use through using using out through out using out through off using ’ s ’ through ’ s ’ through ’'s ‐ to ‐‐ ‐‐‐ ‐ to,
                      $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
Copy code
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:
Copy code
// 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 thrown automatically
echo 'remove successfully
';
Copy code
So here comes the question, 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:
Copy code
// 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))){
                                                                                                                                                                                                                                 
continue;
$filename = $dirpath.'/'.$name;
                                                                                                                                                                                     
clearDir($filename);
                                                                                                                                                                         
                  @unlink($filename);
        }
closedir($handle);
                                                                                                                                                                                     
      }
else{
              return false;
      }
    }
else{
            return false;
    }
return true;
}
Copy code
I have to say that a big pitfall I encountered here is that these two ghost things (dot and dot) are . and .. 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 file copy 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
Certain file reading operations in php are very similar to C language, so they are relatively simple. The steps are to first open the file to get the handle, check for errors, then read and write, and 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:
Copy code
// Write fwrite(alias fputs)
$filepath = 'F:/10m.txt';
function writeSome($filepath){
if(($handle = fopen($filepath, 'r+')) == true){
for($i=0; $i<10; $i++)
                                                                                                                                                                                                                                 
fclose($handle);
} }
}
file_put_contents($filepath, 'use file_put_contents function', FILE_APPEND); // Additional content
Copy code
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:
Copy code
// fread read
function readSome($filepath){
if(($handle = @fopen($filepath, 'r')) == true){
While (! Feof ($ handle)) {// Determine whether to reach the end of the file
                                                                                                                                                                                                                           
echo $str.'
';
      }
} }
}
Copy code
If you want a more flexible reading method, you must use it with 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:
Copy code
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 will automatically move back 3 bytes
echo 'read content: '.$str.'
';
echo 'current position: '.ftell($handle).'
';
                                                                                                                                                                                                                                                                         
echo 'current position: '.ftell($handle).'
';
$str = fread($handle, 5);
echo 'read content: '.$str.'
';
echo 'current position: '.ftell($handle).'
';
                                                                                                                                                                                                                                                                                                    .
echo 'current position: '.ftell($handle).'
';
fseek($handle, 0, SEEK_END); // Move to the end of the file
echo 'current position: '.ftell($handle).'
';
                                                                                                                                                                                           
} }
}
http://www.bkjia.com/PHPjc/909451.html

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/909451.htmlTechArticleBasic operations of PHP file directory We know that temporarily declared variables are stored in memory, even static variables , it will also be released after the script is finished running, so, if you want to save it for a long time...
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can Tmp format files be deleted? Can Tmp format files be deleted? Feb 24, 2024 pm 04:33 PM

Tmp format files are a temporary file format usually generated by a computer system or program during execution. The purpose of these files is to store temporary data to help the program run properly or improve performance. Once the program execution is completed or the computer is restarted, these tmp files are often no longer necessary. Therefore, for Tmp format files, they are essentially deletable. Moreover, deleting these tmp files can free up hard disk space and ensure the normal operation of the computer. However, before deleting Tmp format files, we need to

What to do if the 0x80004005 error code appears. The editor will teach you how to solve the 0x80004005 error code. What to do if the 0x80004005 error code appears. The editor will teach you how to solve the 0x80004005 error code. Mar 21, 2024 pm 09:17 PM

When deleting or decompressing a folder on your computer, sometimes a prompt dialog box &quot;Error 0x80004005: Unspecified Error&quot; will pop up. How should you solve this situation? There are actually many reasons why the error code 0x80004005 is prompted, but most of them are caused by viruses. We can re-register the dll to solve the problem. Below, the editor will explain to you the experience of handling the 0x80004005 error code. Some users are prompted with error code 0X80004005 when using their computers. The 0x80004005 error is mainly caused by the computer not correctly registering certain dynamic link library files, or by a firewall that does not allow HTTPS connections between the computer and the Internet. So how about

How to transfer files from Quark Cloud Disk to Baidu Cloud Disk? How to transfer files from Quark Cloud Disk to Baidu Cloud Disk? Mar 14, 2024 pm 02:07 PM

Quark Netdisk and Baidu Netdisk are currently the most commonly used Netdisk software for storing files. If you want to save the files in Quark Netdisk to Baidu Netdisk, how do you do it? In this issue, the editor has compiled the tutorial steps for transferring files from Quark Network Disk computer to Baidu Network Disk. Let’s take a look at how to operate it. How to save Quark network disk files to Baidu network disk? To transfer files from Quark Network Disk to Baidu Network Disk, you first need to download the required files from Quark Network Disk, then select the target folder in the Baidu Network Disk client and open it. Then, drag and drop the files downloaded from Quark Cloud Disk into the folder opened by the Baidu Cloud Disk client, or use the upload function to add the files to Baidu Cloud Disk. Make sure to check whether the file was successfully transferred in Baidu Cloud Disk after the upload is completed. That's it

Different uses of slashes and backslashes in file paths Different uses of slashes and backslashes in file paths Feb 26, 2024 pm 04:36 PM

A file path is a string used by the operating system to identify and locate a file or folder. In file paths, there are two common symbols separating paths, namely forward slash (/) and backslash (). These two symbols have different uses and meanings in different operating systems. The forward slash (/) is a commonly used path separator in Unix and Linux systems. On these systems, file paths start from the root directory (/) and are separated by forward slashes between each directory. For example, the path /home/user/Docume

What is hiberfil.sys file? Can hiberfil.sys be deleted? What is hiberfil.sys file? Can hiberfil.sys be deleted? Mar 15, 2024 am 09:49 AM

Recently, many netizens have asked the editor, what is the file hiberfil.sys? Can hiberfil.sys take up a lot of C drive space and be deleted? The editor can tell you that the hiberfil.sys file can be deleted. Let’s take a look at the details below. hiberfil.sys is a hidden file in the Windows system and also a system hibernation file. It is usually stored in the root directory of the C drive, and its size is equivalent to the size of the system's installed memory. This file is used when the computer is hibernated and contains the memory data of the current system so that it can be quickly restored to the previous state during recovery. Since its size is equal to the memory capacity, it may take up a larger amount of hard drive space. hiber

Detailed explanation of the role of .ibd files in MySQL and related precautions Detailed explanation of the role of .ibd files in MySQL and related precautions Mar 15, 2024 am 08:00 AM

Detailed explanation of the role of .ibd files in MySQL and related precautions MySQL is a popular relational database management system, and the data in the database is stored in different files. Among them, the .ibd file is a data file in the InnoDB storage engine, used to store data and indexes in tables. This article will provide a detailed analysis of the role of the .ibd file in MySQL and provide relevant code examples to help readers better understand. 1. The role of .ibd files: storing data: .ibd files are InnoDB storage

Detailed explanation of log viewing command in Linux system! Detailed explanation of log viewing command in Linux system! Mar 06, 2024 pm 03:55 PM

In Linux systems, you can use the following command to view the contents of the log file: tail command: The tail command is used to display the content at the end of the log file. It is a common command to view the latest log information. tail [option] [file name] Commonly used options include: -n: Specify the number of lines to be displayed, the default is 10 lines. -f: Monitor the file content in real time and automatically display the new content when the file is updated. Example: tail-n20logfile.txt#Display the last 20 lines of the logfile.txt file tail-flogfile.txt#Monitor the updated content of the logfile.txt file in real time head command: The head command is used to display the beginning of the log file

Create and run Linux ".a" files Create and run Linux ".a" files Mar 20, 2024 pm 04:46 PM

Working with files in the Linux operating system requires the use of various commands and techniques that enable developers to efficiently create and execute files, code, programs, scripts, and other things. In the Linux environment, files with the extension &quot;.a&quot; have great importance as static libraries. These libraries play an important role in software development, allowing developers to efficiently manage and share common functionality across multiple programs. For effective software development in a Linux environment, it is crucial to understand how to create and run &quot;.a&quot; files. This article will introduce how to comprehensively install and configure the Linux &quot;.a&quot; file. Let's explore the definition, purpose, structure, and methods of creating and executing the Linux &quot;.a&quot; file. What is L

See all articles