Details PHP file directory Basic operation, _php tutorial

Source: Internet
Author: User
Tags fread pow rewind

Details the php file directory base operation,


We know that the temporary declaration of the variable is stored in memory, even if it is a static variable, the script will be released after the run, so, want to persist the contents of a variable, one way is to write to the file, put on the hard disk or server, for this file operation must be familiar.

1. Obtaining the attribute information of a file

First, the file has a type, under Linux, there are blocks (block devices, such as disk partitions, CD-ROM), char (a device with character input, such as a keyboard, printer), dir (directory type, directory is also a file), FIFO (named pipe, Explanation is to transfer information from one process to another), file (normal file), link (link, like win-bottom shortcut), Unknow (unknown type) 7 categories, under Win, there are only 3 categories: file, dir, and unknown. Linux Slag said must be a good linux-_-, people are completely for Linux and born.

There are several functions for the acquisition of types: filetype: Get type; Is_file: Determine if it is a normal file; Is_link: Determine if it is a link.

There are several functions for obtaining properties:

File_exists: Determine whether a file or directory exists;

FileSize: Get file size;

Is_readable, Is_writable, is_executable: Whether readable, writable, executable;

Filectime, Filemtime, Fileatime: Gets the file creation time (create), the modified time (modify), the access time (access), all returns the timestamp;

Stat: Gets some basic information about the file, returns an index associated with the mixed array.

For example, the file type can be judged like this:

Copy the Code code as follows:
<?php
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 the data in bytes, if it is a large file number or large, you can deal with the number first, the code is as follows

Copy the Code code as follows:
<?php
Working with file sizes
function GetSize ($path = ", $size =-1) {
if ($path!== null && $size = =-1) {//only path is calculated size, or it can be processed only by the number
$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 a comprehensive file information, the code is as follows:

Copy CodeThe code is as follows:
<?php
function GetFileInfo ($path) {
if (!file_exists ($path)) {//Determine if the file exists
echo ' File not exists!
';
Return
}
if (Is_file ($path)) {//is a file that prints the underlying file name
Echo basename ($path). ' is a file
';
}
if (Is_dir ($path)) {//Is directory, return 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 readable
Echo basename ($path). ' Is readable
';
}
if (is_writeable ($path)) {//Is writable
Echo basename ($path). ' Is writeable
';
}
if (is_executable ($path)) {//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 permissions, octal output
Echo ' file group: '. Filegroup ($path). '
'; The group where the file resides
}

The effect is as follows:

The code also uses the file permissions, the group and other functions, it is necessary to explain (said the wrong, please fix). The permissions of a file are divided into readable and writable executable, generally this means: rwx, the letter corresponding to the expression of the readable writable executable, the previous value is 4, 2, 1, three values add up to a maximum of 7, so 0666 with the octal representation, so it looks very convenient. 7 means the file has these three permissions, so why is 0666 printed? As we all know, under Windows There is a user, under Linux, similar to Windows, there is a user logged in, so a file may be owned by the user, a user it also has its own group, And there are other groups in the system (it is assumed that this should be a management need), so for 0666, for the first 6, the user's permissions on the file, and the second 6 indicates the user's group's permissions on the file. The third 6 represents the permissions that other groups have (so that you do not have to distinguish between other users in addition to this group), and 6 know that the file is readable and writable (the. exe file is known as executable under win).

2. Directory Operations

Directory read, Opendir: Open a directory, return a handle to the contents of the directory, if the contents of the directory as a sequential data, such as a sequential array, this handle points to the beginning of the array, in fact, the system will be the contents of the directory in the dictionary sort, Whether it is a file or a subdirectory. Readdir: Reads the next directory content, returns the file name, and automatically points to the next file/directory in the directory, so reading the contents of a directory, not including the contents of subdirectories, need a loop to control, after reading, also close the handle variable, C language read the file is also the case, Turn it on and off. Take my machine for example:

Copy the Code code as follows:
<?php
Reading of the 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 reads the contents of the directory
$filepath = $dir. '/'. $name;
Echo ' name: '. $name. ' type: '. FileType ($filepath). '
';
}
Closedir ($handle); Close the directory handle
}
else{
echo $dir. ' is not a directory ';
}

The effect is as follows:

As you can see, the system actually sorts the contents of the directory in a case-insensitive dictionary.

The size of the directory is calculated, we know that the size of the file can be obtained by filesize, but there is no specific function in PHP to calculate the size of the directory. Of course, PHP has a function to calculate the size of the hard disk disk_total_space (calculate the total disk space), Disk_free_space (Calculate the hard disk free space), but I tried the next disk_free_space, seemingly incorrect calculation. Because there is a filesize to calculate the size of the file, so you need to use recursion, when it is the directory, go in to 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 the Code code as follows:
<?php
Catalog size Calculation
function Getdirsize ($dirpath) {
$size = 0;
if (false! = ($handle = Opendir ($dirpath))) {
while (false! = ($file = Readdir ($handle))) {
if ($file = = '. ' | | $file = = ' ... ')//pay attention to the points and points in the filter directory
Continue
$filepath = $dirpath. ' /'. $file; The path to the front is connected.
if (Is_file ($filepath)) {//is the size of the file calculation
$size + = FileSize ($filepath);
}
else if (Is_dir ($filepath)) {//is directory continues to compute files in this 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 preceding data processing function

I built a size file in the F-disk, randomly made a list of ideas and documents, the effect is as follows, the left is the program, the right side is right-click View folder properties, to compare.

New and deleted directories, mainly used, mkdir: Create a new directory, rmdir: Delete a non-empty directory, note can only be non-empty, the code is as follows:

Copy the Code code as follows:
<?php
New and deleted directories
$newDirPath = ' F:/newdir ';
if (true = = @mkdir ($newDirPath, 0777, True)) {//Add @ is because the file already exists when PHP itself may throw a warning
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 '))//can only delete non-empty directories if the delete nonexistent directory is automatically thrown warning
Echo ' Remove successfully
';

Then the problem comes, if you want to delete a non-empty directory to do, you have to write, the idea is still recursive, because PHP only provides the deletion of the file function unlink, so in the deletion of a directory, the first opendir, and then enter, if the file is deleted directly, if it is a directory, continue to enter the process using the method, Of course, you can also return a bool variable to indicate whether the deletion was successful and the code is as follows:

Copy the Code code as follows:
<?php
deleting files unlink
Delete the contents of the directory, and 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 here is a big hole that I met. And.. The two Ghosts (dots and dots), which are under every folder in the operating system, will be there. And.. , they represent the current directory and the parent directory of the current directory, and it is abhorrent that the previous reading of the directory did not appear, causing the recursive function to become a dead loop, because. And.. At the front of each directory, it is bound to read the two, if not filtered, first read. , which represents this directory, and then recursively enters this directory ... These are the default ones under the operating system, which are the connectors for this directory and the parent directory.

By calculating the size of the directory and deleting the code of the non-empty directory, it is very easy to write and cut the directory, very similar to the recursive idea, need to copy the file function copy, the file movement function rename, this quite interesting, rename, is literally renamed, But renaming to another directory is not cut, is it?-_-

3. File reading and writing

PHP Some of the file read operation is very similar to C language, so it is relatively simple, the step is to open a file to get a handle, check the error, and then read and write processing, and then close, form open processing after the good habit of closing, remember in the C language of the file is not closed, open two times will be error drops, do not know So the strict point of the program has a lot of processing, such as verifying the existence of the file, and then verify the readable writable, and then close the first, and then open, open, you have to check again open the wrong ... When opening a file, it is necessary to choose the mode of opening the file, which determines whether we read or write the file, which is of course useful for functions that need to be done.

Write file, write file function only fwrite, fputs, file_put_contents a few, wherein fwrite and fputs effect, file_put_contents is a one-time write to the file some content, it does not need to specify open mode, It can also be attached or overwritten with existing file content, such as:

Copy the Code code as follows:
<?php
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 something\r\n"); Windws with \ r \ n as line break
Fclose ($handle);
}
}
File_put_contents ($filepath, ' Use file_put_contents function ', file_append); Additional content

Read the file, read the file more functions, there is fread (read the specified bytes), fgetc (read one), fgets (read a row), file (read all, by row assigned to an array returned), file_get_contents (the default read all return strings), ReadFile (directly output the contents of the file to the cache, the effect is directly on the browser output), along with the Fread, Fget, fgets run, the file pointer will automatically go backwards. Therefore, continuous reading is best for cyclic control. Read to the end of the file, the EOF identity indicates the end of the file, it is best to use feof to detect the end of the file. Not much to say, look at the code:

Copy the Code code as follows:
<?php
Fread Read
function Readsome ($filepath) {
if ($handle = @fopen ($filepath, ' r ')) = = True) {
while (!feof ($handle)) {//Determines whether the end of the file is reached
$str = Fread ($handle, 10); Fread The file pointer moves back automatically when read
echo $str. '
';
}
}
}

If you want to read more flexible, with fseek, rewind use, they can move the file pointer to a specific location, fseek is very flexible, you can move directly to the beginning or the end, or move forward or backward from the current position, read the desired content, Ftell can also inform the current location, such as:

Copy the Code code as follows:
<?php
function Readfun ($filepath) {
if ($handle = @fopen ($filepath, ' r ')) = = False) {
Echo ' Current position: '. Ftell ($handle). '
'; Output file Current file pointer position, in bytes, 0 for beginning
$str = Fread ($handle, 3); Reads 3 bytes While 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); Returns the beginning of a file
Echo ' Current position: '. Ftell ($handle). '
';
Fseek ($handle, 0, seek_end); Move to end of file
Echo ' Current position: '. Ftell ($handle). '
';
Fclose ($handle); Close File
}
}

For example, I now use this method to read a text file written from A to Z to see the effect:

The above is the PHP directory file operation of all the content, but also a personal understanding of the record, I hope to help you

http://www.bkjia.com/PHPjc/909339.html www.bkjia.com true http://www.bkjia.com/PHPjc/909339.html techarticle In detail the php file directory base operation, we know that the temporary declaration of the variable is stored in memory, even if the static variable, the script will be released after the run, so, want to long ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.