PHP File Operation example Sharing

Source: Internet
Author: User
Tags flock
This article is mainly to share with you the PHP file operation example, that is, log, directory, file traversal, upload, multi-method to get file extension, file reference method, reference function difference.

1.   File creation: fopen ()
$file = fopen ("Test.txt", "R");

"r+"

Read and write mode open, the file pointer refers to to the file header.

"W"

write open, point the file pointer to The file header and truncates the file size to zero. If the file does not exist, try to create it.

"w+"

Read and write mode open, the file pointer refers to To the file header and truncates the file size to zero. If the file does not exist, try to create it.

"a"

write open, point the file pointer to The end of the file. If the file does not exist, try to create it.

"A +"

Read and write mode open, the file pointer refers to To the end of the file. If the file does not exist, try to create it.

2. File Open close: fopen (), fclose ()
3. End of File check: feof ()
The function detects whether the end of the file has been reached.
4. Files read: fread (), file (), file_get_contents (), fgetc (), fgets ()
1. Fread (file,length)
Reads up to length bytes from file pointer, length (required)
2. file_get_contents (file)
Preferred method for reading the contents of a file into a string
3. File (file)
Reads the entire file into an array, and each cell in the array is the corresponding line in the file, including the newline character.
4. fgetc (file)
Reads a character from the file pointer
5. Fgets (File,length)
Reads a line from the file pointer, encounters a newline character (included in the return value), EOF, or has read the length-1 byte after the stop (depends on the first encounter).
5. File Pointers:
Fseek (file,offset,whence)
Moves the file pointer forward or backward from the current position to a new location, measured in bytes from the beginning of the file header.

whence is optional. Possible values:

Seek_set-the set position equals the offset byte. Default.

Seek_cur-Sets the position to the current position plus offset.

Seek_end-Set the position to add offset to the end of the file (the offset must be a negative value before moving to the end of the file). Fseek ($fp, -2, seek_end);//Move the pointer to the end of the file

Ftell () returns the current position of the file pointer.
Rewind () Moves the file pointer to the beginning of the file.
Another: Php read large file method
Using PHP's fseek for file manipulation
This is the most common way, it does not need to read all the contents of the file, but directly through the pointer to operate, so efficiency is quite efficient.

<?PHP$FP = fopen ($file, "R"); $pos = 0; $t = ""; $data = ""; while (!feof ($FP)) {while    ($t! = "\ n") {        fseek ($fp, $pos);        $t = fgetc ($fp);        $pos + +;    }    $t = "";    $data. = Fgets ($fp);} Fclose ($FP); Echo $data?>

6. Get the file name extension:
1. substr (STRRCHR ($filename, '. '), 1);
2. substr ($filename, Strrpos ($filename, '. ') +1);
3. End (Explode ('. ', $filename));
4. PathInfo ($filename, pathinfo_extension); (PHP Filesystem function)
7. Directory and File Traversal:

function Traverse ($path) {  $current _dir = Opendir ($path);    Opendir () returns a directory handle, failure returns false while  (($file = Readdir ($current _dir))!==false) {//readdir () returns an entry in the Open Directory handle      Sub_dir = $path. Directory_separator ('/'). $file;    Build the subdirectory path if ($file = = '. ' | | $file = = ' ... ') {          continue;      } else if (Is_dir ($sub _dir)) {    //If it is a directory, do recursive          echo ' directory '. $file. ':<br> ';          Traverse ($sub _dir);      } else {    //If it is a file, directly output          echo ' file in Directory '. $path. ': '. $file. ' <br> ';      }} Closedir ($current _dir); }//remember to close the directory handle when you open it!

8. File lock
Flock (File,lock,block)

function to lock or release files. If successful, returns TRUE. If it fails, it returns false.

The Lock parameter can be one of the following values:

· To get a shared lock (read program), set lock to Lock_sh (share)

· To obtain an exclusive lock (written program), set lock to LOCK_EX (exclusive)

· To release a lock (whether shared or exclusive), set lock to Lock_un

· If you do not want flock () to block when locked, add LOCK_NB to lock

Block is optional. If set to 1 or true, the other process is blocked when the lock is made.

<?php$file = fopen ("Test.txt", "w+");//Exclusive Locking if (Flock ($file, lock_ex))  {fwrite (  $file, "Write something") ;  Release lock  Flock ($file, lock_un);  } else  {  echo "Error locking file!";  } Fclose ($file);? >
The difference between a shared lock and an exclusive lock:

1. Shared lock (S-Lock): if transaction T adds a shared lock to data A, the other transaction can only have a plus shared lock, and cannot add an exclusive lock. Transactions that are allowed to share locks can read only data and cannot modify data.

Exclusive lock (x Lock): If transaction T adds an exclusive lock to data A, other transactions can no longer block a with any type. A transaction that is granted an exclusive lock can read and modify data.

2. Shared lock other users can read and query data concurrently. But cannot modify, add, delete data. Resource sharing. [1]

Related Article

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.