Home  >  Article  >  Backend Development  >  A detailed discussion of the basic operations of PHP file directories_PHP Tutorial

A detailed discussion of the basic operations of PHP file directories_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 10:14:21882browse

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:

详谈PHP文件目录基础操作 帮客之家

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:

详谈PHP文件目录基础操作 帮客之家

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<10; $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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/909796.htmlTechArticleTalk in detail about the basic operations of PHP file directories. We know that temporarily declared variables are stored in memory, even if they are static Variables will also be released after the script is finished running, so if you want to keep them for a long time...
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