PHP Basic Tutorial 15 file, directory operation

Source: Internet
Author: User
Tags fread php language


Objective


When we develop, sometimes we need to involve images, upload and download files and other operations. For example, when registering an account, sometimes you need to upload pictures of the picture, this time you need to use the file processing, and the file style has many kinds such as txt,word,excel.

How files are transmitted

Manipulating files in the PHP language and even other languages is essentially a flow of operations. PHP has two streams (byte stream, binary stream) which are divided into input and output streams in the same way as output.

The stream of the file is referenced in memory, and if the data is stored from the memory of the disk file, we are called the output stream, in turn, if it is from a file that wants memory flow, we call the input stream.

How files are manipulated

The way files are manipulated in PHP is divided into two types:

    • Local operations

    • Remote operation

The local operation is to make the file on its own computer and other operations such as pruning and checking.

Remote operation is the remote access server, the file on the server for the operation of the additional deletion and checking.

From the Help document, you can see the functions about the action file:

Here's just a list of some of the functions, and more functions to see the Help document. You can see that there are 81 functions in the Help document, but we don't have to master them all, and the ones that are commonly used.

Operations on files

Read information about a file

When we operate the file, sometimes need to know the relevant information about the file, such as the size of the file, file type, file creation time, modification time, access time and other information, here will be used to read the file related information technology, in PHP in two forms to obtain the file information.

The first way to read information about a file

<?php    //write a path to a variable record file    $file _path = "D:/config.txt";    if (file_exists ($file _path)) {        //file exists        if ($fp = fopen ($file _path, ' R ')) {            //$type is an array that holds the file information            $type = Fstat ($FP);            The byte of the echo ' <br> file is: '. $type [' size '];            Echo ' <br> file creation time is: '. Date (' y-m-d h:i:s ', $type [' CTime ']);            Echo ' <br> file access time is: '. Date (' y-m-d h:i:s ', $type [' atime ']);            Echo ' <br> file modification time is: '. Date (' y-m-d h:i:s ', $type [' mtime ']);            Close Resource            fclose ($FP);        } else{            Echo ' File open failed ';        }    } else{        echo ' file does not exist ';    }    ...... The result ...    .. The bytes of the file are: \ 2016-10-12 The file was    created: 20:34:56    file access time is: 2016-10-12 20:34:56    file modified by: 2016-10-12 20:35:08

1. We define a path that is the file we access, which can be a relative path or an absolute path.
2. File_exists ($path) function to determine whether a file exists, there is a return of true, there is no return false.
3. Through fopen ($path, Access form), the function opens a file, returns a pointer to the file, and points to the first line. The first parameter is the path to the file, the second parameter is the file's Access form, and "R" means that the file is read.
4. Fstat (file pointer) obtains the file information through the open file pointer, returns an array, some associative arrays are the values we want.
5. Use the resources, remember to close, or sometimes there will be unexpected errors.

Second way to read file information

<?php    $file _path = ' d:/config.txt ';    The type of echo ' <br> file is: '. FileType ($file _path);    The size of the echo ' <br> file is: '. FileSize ($file _path);    Echo ' <br> file creation time is: '. Date (' y-m-d h:i:s ', Filectime ($file _path));    The echo ' <br> file's access time is: '. Date (' y-m-d h:i:s ', Fileatime ($file _path));    The change time for Echo ' <br> file is: '. Date (' y-m-d h:i:s ', Filemtime ($file _path));    ..... The result ...    .. The file type is: The file    file size is: The    creation time of the 2016-10-12 20:34:56 file is:    2016-10-12 20:34:56    file was modified when : 2016-10-12 20:35:08

This is a simple way to get information about a file directly through a function, but you should open the file at the bottom of each function.

Read the contents of a file

We often need to read the contents of the file, PHP provides three ways to read the file.

The first way to read a file

<?php    Header ("Content-type:text/html;charset = Utf-8");    $file _path = ' d:/config.txt ';    if (file_exists ($file _path)) {        if ($fp = fopen ($file _path, ' R ')) {            //Gets the size of the file            $file _size = Fstat ($fp) [' Size ' ];            $content = Fread ($fp, $file _size);            Encode the Chinese in the file            $content = iconv (' GBK ', ' utf-8 ', $content);            Replace the line break.            $content = Str_replace ("\ r \ n", "<br>", $content);            echo $content;            Fclose ($FP);        } else{            Echo ' File open failed ';        }    } else{        echo ' file does not exist ';    }    ...... The result ...    .. Here are some configuration file information.    user = ABC;    Password = 122;
    • Define the full path of the file

    • File_exists ($path) determine if a file exists

    • fopen ($path, Access form) There are many forms of access in this function, and we use only three kinds:

      1. R, the file read operation, the file pointer pointing to the head

      2. W, write to the file operation, if the file exists, the file pointer points to the head, and the contents of the inside empty, if the file does not exist will create a file.

      3. A, write to the file operation, if the file exists, the file pointer pointing to the tail, will not empty the contents, if the file does not exist will create a file.

    • Fread (file pointer, size) This function is to file the degree of operation, by obtaining the size of the file, the whole of a file to write to the $content.

    • Iconv (input character set, output character set, string) This function is to encode the function inside the file, stored in the file GBK, in the page is stored in Utf-8,

    • Str_replace (the character to replace, the ring character, the string) This function is to convert the line breaks in the file, in Windows, the file line break is "\ r \ n", the content of the file is displayed on the Web page, the page line break is "<\br>", Note the escape character must be enclosed in double quotation marks.

    • Close File pointer resource

Second way to read files

In the first way, read the file is a one-time read all, when the file is very large, this way is unreasonable, you can use the second way, using the loop read, first read part, merge, read part, merge.

<?php    $file _path = ' d:/config.txt ';    if (file_exists ($file _path)) {        if ($fp = fopen ($file _path, ' R ')) {            //file too large, sub-byte            $size = 1024;//Read 1024 bytes each time            $tmp _content = ";//Store the contents of a read            $content =";//Store the total content.            while (!feof ($fp)) {                $tmp _content = fread ($fp, $size);                $content. = $tmp _content;            }            $content = Iconv (' GBK ', ' utf-8 ', $content);            $content = Str_replace ("\ r \ n", "<br>", $content);            echo $content;            Fclose ($FP);        } else{            Echo ' File open failed ';        }    } else{        echo ' file does not exist ';    }    ...... The result ...    .. Here are some configuration file information.    user = ABC;    Password = 122;

-From the above code can be seen, read the contents of the file is chunked read, read once, stitching to the total content.
-feof (file pointer) tests if the file pointer is to the end of the file, when the file pointer points to the end without looping.
-Close File pointer resource

Third Way to read files

<?php    $file _path = ' d:/config.txt ';    $content =  file_get_contents ($file _path);    $content = Iconv (' GBK ', ' utf-8 ', $content);    $content = Str_replace ("\ r \ n", "<br>", $content);    echo $content;    ...... The result ...    .. Here are some configuration file information.    user = ABC;    Password = 122;

The third way is the simplest way to read the whole through the file_get_contents () method.

Creating files and writing files

The first way to create files and write files

<?php    //definition file path    $file _path = ' d:/test.txt ';    if (!file_exists ($file _path)) {        //file does not exist        //fopen () function uses w this access form,        if ($fp = fopen ($file _path, ' W ')) {            $str = ";            for ($i = 0; $i < $i + +) {                $str. = "hello,php\r\n";            }            Write data to the file            fwrite ($fp, $str);            Fclose ($FP);        }    }

-When the file does not exist using the fopen () open file is automatically created file, here the file Access form is W, the file pointer to the head, empty the contents of the file.
-Use the Fread () function to write files in the file.
-When the file exists, we can use the ' a ' as the Access form to write the contents of the file appended.

Create a file and write a file the second way

<?php    //definition file path    $file _path = ' d:/test.txt ';    if (!file_exists ($file _path)) {        $str = ';        for ($i = 0; $i < $i + +) {            $str. = "hello,php\r\n";        }        File_put_contents ($file _path, $str);    }

-Write the file using the File_put_contents () function, which also creates the file when the file does not exist.
-If we append new content to the file through the File_put_contents function, we should take the third parameter file_append when using the File_put_contents function.

deleting files

<?php    $file _path = ' d:/test.txt ';    if (file_exists ($file _path)) {        if (unlink ($file _path)) {            echo ' file deleted successfully ';        } else{            echo ' file deletion failed ';        }    }

-Delete files by unlink (file path) function.

Modify the name of the file

<?php    $file _path = ' d:/test.txt ';    $file _newpath = ' d:/newtest.txt ';    if (file_exists ($file _path)) {        if (rename ($file _path, $file _newpath)) {            echo ' filename modified successfully ';        } else{            echo ' filename modification failed ';        }    }

-The name of the modified file can be changed by rename (

The new file name) is modified and returns True when the modification succeeds, and the failure returns false. This function can also move the location of the file.


Operations on a directory

In PHP file programming, the directory is also a file, is a special file, so the operation of the directory has a fixed method of operation, the Main method has three Is_dir,rmdir,mkdir

    • Is_dir determine if it is a directory

    • RmDir Delete a directory that cannot be deleted when there are files or directories under it.

    • mkdir Creating a Directory

      <?php    $dir _path = ' d:/test ';    Determine if the directory exists if    (Is_dir ($dir _path)) {        echo ' directory exists ';    } else{        //directory does not exist, create directory        if (mkdir ($dir _path)) {            echo ' directory created successfully ';        } else{            Echo ' directory creation failed ';        }    }
    • The above first determines whether the directory exists, does not exist using the mkdir () function to create the directory.

The above code can only create a first-level directory, when the path name to $dir_path = ' d:/test/a/b/c/d ', in the test directory, there is a directory, this time with the above method will be error, can not create a multilevel directory. This can also be created using the mkdir () function, but there are two more parameters in the function, and these two parameters are meaningless for development under the Windows system.

<?php    $dir _path = ' d:/test/a/b/c/d ';    Determine if the directory exists if    (Is_dir ($dir _path)) {        echo ' directory exists ';    } else{        //directory does not exist, create directory        if (mkdir ($dir _path,0777,true)) {            echo ' directory created successfully ';        } else{            Echo ' directory creation failed ';        }    }
    • You can see that you can create a multilevel directory by adding two parameters to the function that created the table of contents. 0777 is the maximum access under Linux, and True indicates the creation of a multilevel directory.

Delete Directory

<?php    $dir _path = ' d:/test ';    if (Is_dir ($dir _path)) {        //directory exists        if (rmdir ($dir _path)) {            echo ' directory deletion succeeded ';        } else{            Echo ' directory deletion failed ';        }    }

-delete the directory by rmdir (directory path).
-When deleting a directory, there is no directory or file present.
-The RmDir () function can delete only one directory, cannot delete multiple directories, delete multiple directories, and can use recursive deletions.

 <?php//The full directory under the test directory is: d:/test/a/b/c/d $dir _path = ' d:/test ';        Deldir ($dir _path);            function Deldir ($dir _path) {//Open the current directory $dir = Opendir ($dir _path);                Use the Readdir function to get all directories under the directory while (false!== ($fileName = Readdir ($dir))) {//splicing the current directory if ($fileName! = '. ' && $fileName! = ' ... ') {$dir _name = $dir _path. '/' .                    $fileName;                        if (Is_dir ($dir _name)) {//is a directory that is judged by recursion.                        Deldir ($dir _name);                    The recursion is complete, the current directory is empty, and the directory is deleted.                        }else if (is_file ($dir _name)) {//is a file delete file.                    Unlink ($dir _name);            }}} closedir ($dir);        RmDir ($dir _path); }

The file delete operation is encapsulated in the function, and if there is no file in the directory, the while loop does not enter the loop, but deletes the directory directly. When there is a directory or file, you can recursively execute the function in the loop, knowing that the encountered file or directory is empty (datum condition).

Copy of File

<?php    //The file path that is currently required to be copied.    $file _path = ' d:/desert.jpg ';    The path to which to copy    $path = "e:/desert.jpg";    if (file_exists ($file _path)) {        if (copy ($file _path, $path)) {            echo ' copy succeeded ';        } else{            echo ' replication failed ';        }    } else{        echo ' file does not exist ';    }
    • The full path of the defined file

    • Defines the path to the destination.

    • Copying copies directly using the copy function, the first parameter is the path to the file, and the second parameter is the path to the target.

Traverse Directory

<?php    $dir _path = ' d:/test ';    Isdir ($dir _path);    function Isdir ($dir _path) {        if (Is_dir ($dir _path)) {            //exists file            $dir = Opendir ($dir _path);            Open Directory while            (($fileName = Readdir ($dir))!== false) {                if ($fileName! = '. ' && $fileName! = ' ... ') {                    if (Is_dir ($dir _path). '/' . $fileName) {                        echo ' <br> directory name is: '. $fileName;                        Isdir ($dir _path. '/' . $fileName);                    } else if (Is_file ($dir _path. '/' . $fileName) {                        echo ' <br> filename is: '. $fileName;}                    }            }            Close Resource            closedir ($dir);        }    }    ...... The result ...    .. The directory name is: A file name is: A.txt directory name is: B directory name is:    C directory name is: D file name is:    n.doc    file name is: C.txt

* Recursively iterate through all directories and files under a directory for output.
* There are two useless directories hidden under each directory, so filter out the two useless directories by the If judgment.

the size of the statistics directory.

<?php $dir _path = ' d:/test ';    Echo getsize ($dir _path);        function GetSize ($dir _path) {//define bytes.        $size = 0;            Determine if the directory if (Is_dir ($dir _path)) {//Open Directory $dir = opendir ($dir _path);            Determine if each directory exists.                while (false!== ($fileName = Readdir ($dir))) {//filter unused two directories. if ($fileName! = '. ' && $fileName! = ' ... ') {if (Is_dir ($dir _path). '/' .                        $fileName)) {//Gets the byte size by recursive loop. $size + = GetSize ($dir _path. '/' .                     $fileName); }else if (Is_file ($dir _path. '/' . $fileName) {$size +=filesize ($dir _path. '/' .                    $fileName);        }}}}//Close the resource.        Fclose ($dir);    return $size;                                                                                                                                                                   }                                                                                                                                                                                                                                                    . ......    Results....... 47

    • Gets the byte of the directory to be completed by recursion. Defines the size of each file that $size records, and returns.

Summarize

PHP in the operation of the file is still very important, for the file operation to be flexible application of different functions.

The above is the PHP basic tutorial 15 file, directory operation content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.