PHP directory and file Operation example Tutorial

Source: Internet
Author: User
Tags echo date flock php class

First , the directory operation is the function read from the directory, Opendir (), Readdir (), Closedir (), when using the first open the file handle, and then the iteration list:

    1. $base _dir= "filelist/";
    2. $fso =opendir ($base _dir);
    3. echo $base _dir. " ";
    4. while ($flist =readdir ($FSO)) {
    5. echo $flist. "
      ";
    6. }
    7. Closedir ($FSO)
    8. ?>
Copy Code

This is the return file directory under which the file is already in the directory program (0 file will return false).

Sometimes you need to know the directory information, you can use DirName ($path) and basename ($path), respectively, return the directory portion of the path and the file name part, the Disk_free_space ($path) to return to view the space remaining space.

Create command: mkdir ($path, 0777): 0777 is the permission code, and the Umask () function is set under non-window. RmDir ($path): will delete the path in the $path file.

Second, the file operation

Create a new file first, determine the permissions of the directory where you want to create the new file; The recommended device is 777. Then, the name of the new file is recommended to use an absolute path.

    1. $filename = "Test.txt";
    2. $FP =fopen ("$filename", "w+"); Open file pointer, create file
    3. if (!is_writable ($filename)) {
    4. Die ("File:". $filename. " Not writable, please check! ");
    5. }
    6. Fwrite ($filename, "anything you want-to-write to $filename.";
    7. Fclose ($FP); Close pointer
Copy Code

read the file first is a file to see if it can be read (permission problem), or there is no, we can use the Is_readable function to obtain information.:

    1. $file = ' dirlist.php ';
    2. if (is_readable ($file) = = False) {
    3. Die (' file does not exist or cannot be read ');
    4. } else {
    5. echo ' presence ';
    6. }
    7. ?>
Copy Code

The function of judging the existence of a file is also file_exists (shown below), but this is obviously not is_readable comprehensive. When a file exists, it can be used

    1. $file = "filelist.php";
    2. if (file_exists ($file) = = False) {
    3. Die (' file does not exist ');
    4. }
    5. $data = file_get_contents ($file);
    6. echo htmlentities ($data);
    7. ?>
Copy Code

However, the file_get_contents function is not supported on earlier versions, you can create a handle to the file first, and then read all with the pointer:

There is also a way to read a binary file:$data = Implode (', File ($file));

write the file and read the file the same way, first see if it can write:

    1. $file = ' dirlist.php ';
    2. if (is_writable ($file) = = False) {
    3. Die ("write!");
    4. }
    5. ?>
Copy Code

If you can write it, you can use the File_put_contents function to write:

    1. $file = ' dirlist.php ';
    2. if (is_writable ($file) = = False) {
    3. Die (' I'm chicken feathers, I can't ');
    4. }
    5. $data = ' I am contemptible, I want to ';
    6. File_put_contents ($file, $data);
    7. ?>
Copy Code

file_put_contents function in the php5 of the newly introduced function (do not know the existence of the function_exists function first to judge) the lower version of PHP is not available, you can use the following way:

    1. $f = fopen ($file, ' w ');
    2. Fwrite ($f, $data);
    3. Fclose ($f);
Copy Code

Replace it.

When writing a file, you sometimes need to lock and then write:

    1. function Cache_page ($pageurl, $pagedata) {
    2. if (! $fso =fopen ($pageurl, ' W ')) {
    3. $this->warns (' cannot open cache file. '); /trigger_error
    4. return false;
    5. }
    6. if (!flock ($fso, lock_ex)) {//LOCK_NB, exclusive type lock
    7. $this->warns (' cannot lock cache file. '); /trigger_error
    8. return false;
    9. }
    10. if (!fwrite ($fso, $pagedata)) {//write byte stream, serialize write to other format
    11. $this->warns (' cannot write to cache file. '); /trigger_error
    12. return false;
    13. }
    14. Flock ($fso, lock_un);//Release lock
    15. Fclose ($FSO);
    16. return true;
    17. }
Copy Code

copy, delete files php Delete files very easy, with the unlink function simple operation:

    1. $file = ' dirlist.php ';
    2. $result = @unlink ($file);
    3. if ($result = = False) {
    4. Echo ' Mosquitoes have driven away ';
    5. } else {
    6. Echo ' cannot be driven away ';
    7. }
    8. ?>
Copy Code

Can.

To copy a file :

    1. $file = ' yang.txt ';
    2. $newfile = ' ji.txt '; # The parent folder of this file must be able to write
    3. if (file_exists ($file) = = False) {
    4. Die (' sample not online, cannot copy ');
    5. }
    6. $result = Copy ($file, $newfile);
    7. if ($result = = False) {
    8. echo ' Copy memory OK ';
    9. }
    10. ?>
Copy Code

You can use the rename () function to rename a folder. The other operations are done by combining these functions.

Get file properties

I say a few common functions: Get the Last Modified time:

    1. $file = ' test.txt ';
    2. echo Date (' R ', Filemtime ($file));
    3. ?>
Copy Code

Returns a timestamp that says Unix, which is commonly used in caching techniques.

The related also gets the time that was last accessed Fileatime (), Filectime () when the permissions of the file, the owner, the metadata in all groups or other inode is updated, the Fileowner () function returns the file owner $owner = posix_ Getpwuid (Fileowner ($file));(Non-Window System), Ileperms () Gets the file permissions,

    1. $file = ' dirlist.php ';
    2. $perms = substr (sprintf ('%o ', Fileperms ($file)),-4);
    3. Echo $perms;
    4. ?>
Copy Code

FileSize () returns the number of bytes in the file size:

    1. Output similar to: somefile.txt:1024 bytes

    2. $filename = ' somefile.txt ';

    3. Echo $filename. ': ' . FileSize ($filename). ' bytes ';
    4. ?>

Copy Code

To get all the information for a file, there is a function stat () function that returns an array:

    1. $file = ' dirlist.php ';
    2. $perms = stat ($file);
    3. Var_dump ($perms);
    4. ?>
Copy Code

you may be interested in the article:PHP File Operation class Code a sample PHP file operation Small Example a nice text file operation PHP class PHP file operation Method FAQ php directory and file operation detailed

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