Basic operations of file directories in PHP_PHP tutorial

WBOY
Release: 2016-07-13 10:14:34
Original
793 people have browsed it

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...
Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template