Details php file directory base Operation _php Instance

Source: Internet
Author: User
Tags create directory fread mkdir parent directory pow readable rewind file permissions

We know that the temporary declarations of variables are stored in memory, even static variables, after the script is finished will be released, so, want to save the content of a variable for a long time, one way is to write to the file, put on the hard disk or server, this file operation must be very familiar.

1. Property information acquisition of the file

First file has a type, under Linux, there are blocks (block devices, such as disk partitions, CD-ROM), char (with character input device, such as keyboard, printer), dir (directory type, directory is one of the files), FIFO (named pipe, The explanation is to transfer information from one process to another, file (ordinary file), link (link, similar to the shortcut below win), Unknow (unknown type) 7 categories, below win, only 3 categories: file, dir and unknown. Linux Slag said that must do a good linux-_-, people are entirely for Linux and life.

There are so many functions about type acquisition: filetype: getting the type; Is_file: Judging whether it is a normal file; Is_link: Deciding whether it is a link.

There are several functions for obtaining a property:

File_exists: To determine whether a file or directory exists;

FileSize: Get file size;

Is_readable, is_writable, is_executable: Readable, writable, executable;

Filectime, Filemtime, fileatime: Get the file creation time (create), modify time (modify), Access time (access), all return the timestamp;

Stat: Gets some basic information about the file, and returns an array of indexes and associative mixtures.

For example, you can judge a file type this way:

Copy Code code as follows:



<?php


function Getfiletype ($path) {//Get file type


Switch (filetype ($path)) {


Case ' file ': Return ' ordinary file ';


Case ' dir ': Return ' directory ';


Case ' blocks ': 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 the large file number or large, you can deal with the number first, the code is as follows

Copy Code code as follows:



<?php


Working with file size


function GetSize ($path = ', $size =-1) {


if ($path!== null && $size = = 1) {//Only the path is calculated to size, or it can be processed only by 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 a comprehensive file information, the code is as follows:

Copy Code code as follows:



<?php


function GetFileInfo ($path) {


if (!file_exists ($path)) {//To determine if a file exists


echo ' File not exists!<br> ';


Return


}


if (Is_file ($path)) {//is a file, print the underlying file name


Echo basename ($path). ' is a file<br> ';


}


if (Is_dir ($path)) {//is a directory, return directory


echo dirname ($path). ' is a directory<br> ';


}


echo ' File type: '. Getfiletype ($path). '  <br> '; Get file type


echo ' File size: '. GetSize ($path). '  <br> '; Get File size


if (is_readable ($path)) {//Is readable


Echo basename ($path). ' Is readable<br> ';


}


if (is_writeable ($path)) {//Is writable


Echo basename ($path). ' Is writeable<br> ';


}


if (is_executable ($path)) {//IS executable


Echo basename ($path). ' Is executable<br> ';


}


The touch function can modify these times


Echo ' File Create Time: '. Date (' y-m-d h:i:s ', Filectime ($path)). '   <br> '; Creation time


Echo ' File modify Time: '. Date (' y-m-d h:i:s ', Filemtime ($path)). '   <br> '; Modified Time


Echo ' last access: '. Date (' y-m-d h:i:s ', Fileatime ($path)). '   <br> '; Last Access time


Echo ' File owner: '. Fileowner ($path). '   <br> '; File owner


Echo ' file permission: '. substr (sprintf ('%o ', (Fileperms ($path)),-4). '   <br> '; File permissions, octal output


Echo ' file group: '. Filegroup ($path). '   <br> '; 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 (say wrong, please amend). The permissions of a file are divided into readable writable executables, generally this means: rwx, letters corresponding to the expression of readable writable executable, the previous set value of 4, 2, 1, three values added the result of the maximum is 7, so 0666 with the octal said, so it looks very convenient. 7 means that the file has these three permissions, so why print 0666? As we all know, access to Windows below 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 (guessing that this should be a management requirement), so for 0666, for the first 6, it represents the user's permissions to the file, and the second 6 indicates the user's group's permissions to the file. The third 6 indicates the permissions of the other groups (so you don't have to distinguish between the other users of this group), and 6 knows that the file is readable and writable (win under the executable is known as the. exe file).

2. Directory operation

Directory read, Opendir: Open a directory, returns a handle to the contents of the directory, if the contents of the directory as a sequential data, such as an ordered array of arrays, this handle points to the beginning of the array, in fact, the system will be the contents of the directory sorted by dictionary, Whether it is a file or a subdirectory. Readdir: Read the next directory content, returns the file name, and automatically points to the next file/directory in the directory, so read the contents of a directory, not including the contents of subdirectories, need a loop to control, after reading, but also to close the handle variables, C language Read the file is also the case, Open it and there is a shutdown. Take my machine for example:

Copy Code code as follows:



<?php


Read the Directory


$dir = ' f:/';


Echo ' details in '. $dir. ' <br> ';


if (Is_dir ($dir)) {


if (($handle = Opendir ($dir)) = = False) {//Get directory Handle


Echo ' Open dir failed ';


Return


}


while (($name = Readdir ($handle))!= false) {//loop read the contents of the directory


$filepath = $dir. '/'. $name;


Echo ' name: '. $name. ' type: '. FileType ($filepath). ' <br> ';


}


Closedir ($handle); Close a directory handle


}


else{


echo $dir. ' is not a directory<r> ';


}


The effect is as follows:

You can see that in fact, the system gives the contents of the directory a dictionary sort that ignores the case.

The size of the catalog, 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 PHP has a function to calculate the size of the hard disk disk_total_space (calculate the total space of the hard disk), Disk_free_space (Calculate the free space on the hard disk), but I tried to disk_free_space, seemingly wrong calculation. Because there is a filesize to calculate the size of the file, so you need to use recursion, when it is a directory, go in and continue to compute the size of the subdirectory, if it is a file, get the file size and add it back, the code is as follows:

Copy 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 = = ' ... ') Notice the dots and dots in the filter directory.


Continue


$filepath = $dirpath. '          /'. $file; To connect to the path before


if (Is_file ($filepath)) {//is the file calculation size


$size + + filesize ($filepath);


}


else if (Is_dir ($filepath)) {//is the directory continues to compute 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). '  <br><br> '; Call the preceding data-processing function


I built a size file in F, and I just got the idea directory and documents, the effect is as follows, the left is the program to find the right side is the right to see folder properties, to compare.

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

Copy Code code as follows:



<?php


New and deleted directory


$newDirPath = ' F:/newdir ';


if (true = = @mkdir ($newDirPath, 0777, True)) {//@ is because the file already exists, PHP itself may throw a warning


echo ' Create directory '. $newDirPath. ' Successfully<br> ';


}


else{


if (file_exists ($newDirPath))


echo ' directory '. $newDirPath. ' has existed<br> ';


Else


echo ' Create directory '. $newDirPath. ' Failed<br> ';


}


if (true = = @rmdir (' f:/aaa '))//Only a non-empty directory can be deleted, if the deletion does not exist the directory is automatically thrown warning


Echo ' Remove successfully<br> ';


So the question is, if you want to delete a non-empty directory, have to write their own, thought is still recursive, because PHP only provides delete file function unlink, so in the deletion of a directory, first Opendir, and then enter, if the file is deleted directly, if the directory, continue to enter the use of the method processing, Of course, you can also return a bool variable to indicate whether the deletion was successful, as in the following code:

Copy Code code as follows:



<?php


Delete File 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;


}


Here I have to say a big hole in the face, that is. And.. These two ghost things (dots and dots), in the operating system under each folder, there will be. And.. , which represent the current directory and the parent directory of the current directory, which is abhorrent to the fact 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 table of contents, we must first 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 for the Non-empty directory, write-copy and cut directories are very easy, very similar recursive ideas, need to use Copy file function copy, file Move function rename, this is very interesting, rename, literally renaming, But isn't renaming to another directory a cut?-_-

3. File reading and writing

Some of PHP's file reads are very similar to the C language, so it's easier to the first step is to open the file to get the handle, check the error, and then read and write processing, and then closed, into the open processing after the closure of good habits, remember that in the C language of the file is not closed, open two times is the error, do not know remember wrong, So strict procedures have a lot of processing, such as the first verify that the file exists, and then verify the readable and writable, and then close the first, and then open again, open the check to open the wrong ... When you open a file, you choose to open the file mode, which determines whether we read or write the file, of course, is useful for the function that needs to be done.

Write a file, write a file function only fwrite, fputs, file_put_contents a few, where 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 contents, such as:

Copy 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 a newline character
Fclose ($handle);
}
}
File_put_contents ($filepath, ' Use file_put_contents function ', file_append); Additional content

Read the file, read the file more functions, there are fread (read the specified byte), fgetc (read one), fgets (read a row), file (read all, assigned to a row in an array of returns), file_get_contents (the default read all return string), ReadFile (directly to the contents of the file output to the cache, the effect is directly in the browser output), with the Fread, Fget, fgets run, the file pointer will automatically go backwards. Therefore, continuous reading is preferably a circular control. What to do with the end of the file, the EOF identification indicates that the end of the file is reached, preferably feof to the end of the file. Not much to say, look at the code:

Copy Code code as follows:

<?php
Fread Read
function Readsome ($filepath) {
if (($handle = @fopen ($filepath, ' r ')) = = True) {
while (!feof ($handle)) {//Determine whether to reach the end of the file
$str = Fread ($handle, 10); When Fread read, the file pointer automatically moves backwards
echo $str. ' <br> ';
}
}
}

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

Copy Code code as follows:



&lt;?php


function Readfun ($filepath) {


if (($handle = @fopen ($filepath, ' R '))!= false) {


Echo ' Current position: '. Ftell ($handle). '  &lt;br&gt; '; The current file pointer position of the output file, in bytes, 0 for the beginning


$str = Fread ($handle, 3); Reads 3 bytes While the pointer automatically moves 3 bytes


Echo ' Read content: '. $str. ' &lt;br&gt; ';


Echo ' Current position: '. Ftell ($handle). ' &lt;br&gt; ';


Fseek ($handle, 5, seek_cur); Moves the file pointer 5 bytes from the current position


Echo ' Current position: '. Ftell ($handle). ' &lt;br&gt; ';


$str = Fread ($handle, 5);


Echo ' Read content: '. $str. ' &lt;br&gt; ';


Echo ' Current position: '. Ftell ($handle). ' &lt;br&gt; ';


Rewind ($handle); Returns the beginning of a file


Echo ' Current position: '. Ftell ($handle). ' &lt;br&gt; ';


Fseek ($handle, 0, seek_end); Move to end of file


Echo ' Current position: '. Ftell ($handle). ' &lt;br&gt; ';


Fclose ($handle); Close File


}


}


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

The above is php about directory file operation of the entire content, but also a personal understanding of the record bar, I hope to help you

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.