(Advanced article) PHP commonly used file operation function

Source: Internet
Author: User
The following is a php file manipulation function. Of course, this is only part of it, and there are a lot of them that I didn't list.

First, the parse path:

1 Get the file name:

BaseName ();
Give a string containing a full path to a file, this function returns the base file name. If the file name ends in suffix, then this part will be removed as well.
eg

$path = "/home/httpd/html/index.php"; $file = basename ($path, ". php"); $file is set to "index"

2 Getting the Catalog section:
DirName ();
Gives a string containing a full path to a file, which returns the directory name after removing the file name.
eg

$path = "/etc/passwd"; $file = DirName ($path); $file is set to "/etc"

3 Getting the path associative array
PathInfo ();
Gets the three parts of a specified path: directory name, base name, extension.
eg

$pathinfo = PathInfo ("www/test/index.html"), Var_dump ($pathinfo),//$path [' dirname '] $path [' basename '] $path [' Extenssion ']


Ii. Types of files
1. filetype ();
Returns the type of the file. The possible values are fifo,char,dir,block,link,file and unknown.
eg

echo filetype ('/etc/passwd '); Fileecho filetype ('/etc/');        Dir


Iii. getting an array of useful information for a given file (useful)

1. Fstat ();
Get file information from an open file pointer
Gets the statistics for the file opened by the file pointer handle. This function is similar to the stat () function except that it acts on an open file pointer instead of a filename.
eg

Open File $fp = fopen ("/etc/passwd", "R");//Get statistics $fstat = Fstat ($FP);//Close File fclose ($FP);//show only associative array parts print_r (Array_slice ( $fstat, 13));

2. Stat ()
Gets the statistics for the file specified by the filename (analogy fstat ())

Iv. Calculation of size
1. FileSize ()
Returns the number of bytes in the file size, returns False if an error occurs, and generates an e_warning-level error.
eg

Output similar to: somefile.txt:1024 bytes$filename = ' somefile.txt '; Echo $filename. ': ' . FileSize ($filename). ' bytes ';


2. Disk_free_space ()
Get the free space (in bytes) of the disk partition where the directory resides
eg

$DF contains the number of bytes available in the root directory $df = Disk_free_space ("/");//Under Windows: Disk_free_space ("C:");d isk_free_space ("D:");


3. Disk_total_space ()
Returns the total disk size of a directory
Eg: (ditto, replace function)

Another: If you need to calculate a directory size, you can write a recursive function to implement

Code

function Dir_size ($dir) {$dir _size = 0;if ($dh = @opendir ($dir)) {while (($filename = Readdir ($DH))! = False) {if ($filename! = '. ' and $filename! = ' ... ') {     if (is_file ($dir. '/'. $filename)) {$dir _size +=filesize ($dir. '/'. $filename);} else if (Is_dir ($dir. '/'. $filename)) {      $dir _size +=dir_size ($dir. '/'. $filename);}}                   } #end while            }# end Opendir@closedir ($DH); return $dir _size;} #end function

V. Time of visit and modification
1. Fileatime (): Last Access time
2. Filectime (): Last Change of time (modification of any data)
3. Filemtime (): Last Modified time (refers to content modification only)

Vi. file I/O operations

1. fopen--Open file or URL

Mode description
The ' R ' read-only mode opens, pointing the file pointer to the file header.
The ' r+ ' read-write mode opens, pointing the file pointer to the file header.
The ' W ' Write method opens, pointing the file pointer to the file header and truncating the file size to zero. If the file does not exist, try to create it.
The ' w+ ' read-write mode opens, pointing the file pointer to the file header and truncating the file size to zero. If the file does not exist, try to create it.
' A ' writes open, pointing the file pointer at the end of the file. If the file does not exist, try to create it.
The ' A + ' read-write mode opens, pointing the file pointer at the end of the file. If the file does not exist, try to create it.
' X ' is created and opened in writing, pointing the file pointer to the file header. If the file already exists, the fopen () call fails and returns FALSE,
' x+ ' is created and opened as read-write, pointing the file pointer to the file header. If the file already exists, the fopen () call fails and returns FALSE
eg

$handle = fopen ("/home/rasmus/file.txt", "R");

2. File-Reads the entire file into an array (this function is useful)
As with file_get_contents (), only file () is returned as an array. Each cell in the array is the corresponding line in the file, including the newline character. FALSE If the failed file () is returned.
eg

Code

$lines = File (' http://www.example.com/');//Loop through the array, displaying the source file of the HTML and adding the line number. foreach ($lines as $line _num = + $line) {echo "line #<b>{$line _num}</b>:". Htmlspecialchars ($line). "<br/>\n";} Another example reads a Web page into a string. See File_get_contents (). $html = Implode (', File (' http://www.example.com/'));


3. Fgets--Reads a line from the file pointer
Reads a row from the file pointed to by handle and returns a string of up to length-1 bytes in length. Stop after encountering a newline character (included in the return value), EOF, or having read the length-1 byte (see first the case). If length is not specified, the default is 1 K, or 1024 bytes.
eg

$handle = @fopen ("/tmp/inputfile.txt", "R"), if ($handle) {while (!feof ($handle)) {$buffer = Fgets ($handle, 4096); Echo $bu Ffer;} Fclose ($handle);}

4. FGETSS--Reads a line from the file pointer and filters out HTML tags
Same as fgets () except that FGETSS attempts to remove any HTML and PHP markup from the text that is being read.

You can use the optional third parameter to specify which tags are not removed


Another: The operation of the directory:
1. Opendir--Open the directory handle and open a directory handle that can be used for subsequent closedir (), Readdir (), and Rewinddir () calls.
2. Readdir--Reads the entry from the directory handle, returning the file name of the next file in the directory. The file name is returned as a sort in the file system.
eg

Code

Note the!== operator if ($handle = Opendir ('/path/to/files ')) {echo "Directory handle: $handle \ n"; echo "files:\n" is not present before 4.0.0-RC2 ;  while (false!== ($file = Readdir ($handle))) {echo "$file \ n";}   while ($file = Readdir ($handle)) {echo "$file \ n";}     Closedir ($handle);}


3. Scandir--Lists the files and directories in the specified path (useful), returns an array containing the files and directories in the directory.
The default sort order is arranged alphabetically. If you use the optional parameter Sorting_order (set to 1), the sort order is sorted alphabetically.
eg

$dir    = '/tmp '; $files 1 = Scandir ($dir); $files 2 = Scandir ($dir, 1);p Rint_r ($files 1);p Rint_r ($files 2);

Also note:

Seven, the operation of the file attributes (operating system environment, may be different, this should be noted)

1 whether the file is readable:

       Boolis_readable (string filename)

Returns TRUE if the file or directory specified by filename exists and is readable.

Remember that PHP may only be able to access the file by running the webserver user name (usually ' nobody '). Restrictions that do not count toward Safe mode.

2 File is writable

         BOOL Is_writable (string filename)

Returns TRUE if the file exists and is writable. The filename parameter can be a directory name that allows for a writable check.

Remember that PHP may only be able to access the file by running the webserver user name (usually ' nobody '). Restrictions that do not count toward Safe mode

3 checking if a file exists

    Boolfile_exists (string filename)

Returns TRUE if the file or directory specified by filename is present, otherwise FALSE


Above is (Advanced article) PHP commonly used file operation function 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.