Summary of operation Functions of PHP Common Files

Source: Internet
Author: User
Tags html tags readable sort

Recently wrote a number of counter source instances and generate static article CMS, using the php file operation, PHP file operation function is still very powerful, really often used is often a few. So in the study, just remember to use a few of the high frequency on the line, do not have to remember so many useless function code, as for the use of frequency is not very high, as long as you see what it means. The following is a few of the Bo 04ie.com in PHP use a very high frequency function, almost in the use of PHP operation functions often used to, in fact, only six, the first backup down, in the review of PHP knowledge just take it.

First, to determine whether the document exists

if (file_exists ("Data.txt")) {//content;}

Second, open the document

$openfile =fopen ("path and filename", "open Mode"); Open mode: R Read only, W only write, a read-write;

Third, read the file

$str =fread ($openfile, FileSize ("path and filename")); Parameters: Open file, cutoff character position;

Reading file size (in bytes)

FileSize ("path and filename");

V. Write the contents of the file

Fwrite ("path and filename", written content);

Vi. Closing of documents

Fclose ($openfile); Parameters: Open Files

Knowledge: Replace function str_replace ("Original content", "content to be replaced", variable);

The following is a personal summary of the PHP file manipulation function. Of course, that's just part of it, and there's a lot that I haven't listed.

First, parse the path:

1 Get FileName:
BaseName ();
Gives a string containing a full path to a file, which returns the base file name. If the filename ends with suffix, that part will also be removed.
eg


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

2 Get the Contents section:
DirName ();
Gives a string containing a full path to a file, which returns the name of the directory after the file name is removed.
eg


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

3 Get path Associative array
PathInfo ();
Gets 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 documents
1. filetype ();
Returns the type of file. The possible values are fifo,char,dir,block,link,file and unknown.
eg


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

Three, get the given file useful information array (very 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 rather than a filename.
eg


Open File
$fp = fopen ("/etc/passwd", "R");
Get statistical information
$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 filename (analogy fstat ())

Four, calculate the size
1. FileSize ()
Returns the number of bytes in the file size, if error returns false and generates a 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 free Space (in bytes) for the partition on which the directory resides
eg


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


3. Disk_total_space ()
Returns the total disk size of a directory
Eg: (ditto, change 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 (): Final change of time (any data modification)
3. Filemtime (): Last modification 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.
' r+ ' read-write mode opens, pointing the file pointer to the file header.
The ' W ' 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 creating it.
' w+ ' read-write mode opens, points the file pointer to the file header and truncates the file size to zero. If the file does not exist, try creating it.
The ' a ' write mode opens, pointing the file pointer at the end of the file. If the file does not exist, try creating it.
An ' A + ' read-write mode opens, pointing the file pointer to the end of the file. If the file does not exist, try creating 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 in read-write mode, 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-read 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 line breaks. If failure file () returns FALSE.
eg


Code
$lines = File (' http://www.example.com/');
Loops through the array, displaying the source file for 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--reading a row from the file pointer
Reads a row from the file pointed to by handle and returns a string with a maximum length of length-1 bytes. Stops when a line break is encountered (including in the return value), EOF, or after the length-1 byte has been read (see what happens first). 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 $buffer;
}
Fclose ($handle);
}

4. FGETSS--read a row from the file pointer and filter out the HTML tags
Same as fgets () except that FGETSS tries to remove any HTML and PHP tags from the read text.

You can specify which tags are not removed with the optional third argument


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

Code
Note that the!== operator does not exist before 4.0.0-RC2

if ($handle = Opendir ('/path/to/files ')) {
echo "Directory handle: $handlen";
echo "Files:n";

while (false!== ($file = Readdir ($handle))) {
echo "$filen";
}

while ($file = Readdir ($handle)) {
echo "$filen";
}
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 sorted 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);

Print_r ($files 1);
Print_r ($files 2);

Note also:

Seven, the operation of the file properties (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 access files with the username (usually ' nobody ') running webserver. does not count into the security mode limit.

2 whether the file can be written

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 writable checking.

Remember that PHP may only access files with the username (usually ' nobody ') running webserver. Excluding security mode restrictions

3 Check for file existence

Boolfile_exists (string filename)

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

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.