Detailed Introduction to PHP directory operations and file operations _php tutorial

Source: Internet
Author: User
Tags flock vars
About PHPIn the directory operation and file operation, also introduced, but some people still do not understand. The following is a detailed description of PHP directory operations and file operations.

In any computer device, files are all necessary objects, and in Web programming, the operation of the file has always been a headache for the web programmer, and, the operation of the file in the CMS system this is necessary, very useful, we often encounter generate files directory, file (clip) editing operations, and now I put These functions in PHP are summarized in more detail and examples demonstrate how to use them. For a detailed description of the corresponding function, please refer to the PHP manual. Here is a summary of the key points. And where attention is needed. (This is not in the PHP manual.)

First, directory operations

The first introduction is a function read from the directory, Opendir (), Readdir (), Closedir (), using the file handle is opened first, and then the iteration is listed:

 
 
  1. $base _dir = "filelist/" ;
  2. $fso = Opendir ($base _dir);
  3. Echo $base _dir. "
  4. " ;
  5. while ($flist=readdir ($fso)) {
  6. Echo $flist. "
  7. " ;
  8. }
  9. Closedir ($fso)
  10. ?>

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 see space free space.

To create a command:

mkdir ($path, 0777), 0777 is the permission code, the Umask () function is set RmDir ($path) under Non-window

The path to the $path file will be deleted.

DIR--The Directory class is also an important class to manipulate the file directory, there are 3 methods, Read,rewind,close, this is a copy object-oriented class, it first uses the open file handle, and then read by the way of the pointer. Here's a look at the PHP manual:

 
 
  1. $d = Dir ("/ETC/PHP5");
  2. Echo "Handle:" . $d ->handle. "n" ;
  3. Echo "Path:" . $d ->path. "n" ;
  4. while (False!== ($entry = $d->read ())) {
  5. Echo $entry. "n" ;
  6. }
  7. $d ->close ();
  8. ?>

Output:

 
  
  
  1. Handle:resource ID #2
  2. Path:/ETC/PHP5
  3. .
  4. ..
  5. Apache
  6. Cgi

The properties of the file are also very important, including the creation time, the last modified time, the owner, the file group, the type, the size, and so on.

Here we focus on file operations.

Second, the file operation

A, read the file

The first is a file to see if it can read (permission problems), 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. }

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. $datafile_get_contents($file);
  6. Echo htmlentities ($data);

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:

 
  
  
  1. $fsofopen($cacheFile' r ');
  2. $datafread($fsofilesize( $cacheFile ));
  3. fclose ($fso

There is also a way to read a binary file:

 
  
  
  1. $data = implode (', file ($file

B, write the file

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

 
  
  
  1.  
  2. $file' dirlist.php ';
  3. if (is_writable($file) = = False) {
  4. die ("I am chicken feathers, I cannot") ;
  5. }

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

 
  
  
  1. !--? php span>
  2. $file = ' dirlist.php ' ;
  3. if ( is_writable ( $file ) = = False) {
  4. die ( ");
  5. }
  6. $data = " I am despicable, I want ' ;
  7. file_put_contents ( $file , $data );
  8. ?>

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. $ffopen($file' W ');
  2. fwrite ($f$data);
  3. fclose ($f

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, row-type locking
  7. $this ->warns (' Unable to 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 cache file. ' ) ); //trigger_error
  12. return false;
  13. }
  14. Flock ($fso, lock_un); //Release lock
  15. fclose ($fso);
  16. return true;
  17. }

C, copy, delete files

PHP Delete Files is 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. }

Can.

Copying files is also easy:

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

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

D. Get file attributes

I say a few common functions:

Gets the last modified time:

 
  
  
  1. $file' test.txt ';
  2. echodate(' R 'filemtime( $file));

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

Related to the last time accessed Fileatime (), Filectime () when the permissions of the file, the owner, the metadata in all groups or other inode are updated, the Fileowner () function returns the file owner

 
  
  
  1. $owner = Posix_getpwuid (fileowner($file

(Non-Window System), Ileperms () Gets the file permissions,

 
  
  
  1. $file' dirlist.php ';
  2. $permssubstr(sprintf ('%o 'fileperms ($file)),-4);
  3. echo$perms;

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 ';

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);

The key corresponds to what can be consulted in detail, which is not expanded here.

Iv. concluding remarks

Above I briefly summed up a few file operations, if you are familiar with the above listed functions, there is no big problem in operation, PHP file operation function Changes relatively fast, is now very powerful, the file is also a very important part of learning PHP, I hope not to ignore.


http://www.bkjia.com/PHPjc/445748.html www.bkjia.com true http://www.bkjia.com/PHPjc/445748.html techarticle The directory operations and file operations in PHP have also been introduced, but some people still do not understand. The following is a detailed description of PHP directory operations and file operations. On any computer device ...

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