Home > Article > Backend Development > Advanced application of PHP file processing - remote file access and locked files
Advanced application of PHP file processing—remote file access and locking files
In PHP, in addition to basic read and write operations on files, You can also search and locate the file pointer, and lock the file being read.
The previous articles "PHP File Processing—Open/Close File", "PHP File Processing—Read File (One Character, String)" , "PHP File Processing—How to Read Files" and "PHP File Processing—Writing Files and Operating Files" introduce the basic read and write operations of file processing. This section will Learn more about advanced file processing techniques.
1: Remote file access
PHP supports file calling in URL format, just set it in php.ini. Find allow_url_fopen in php.ini and set this option to ON. After restarting the server, you can use the HTTP or FTP URL format,
For example:
fopen("http://http://127.0.0.1/php/1.php","rb");
2: Lock the file
When writing content to a text file, you need to lock the file first to prevent other users from modifying the content of the file. The function to lock the file in PHP is flock(). The syntax format of this function is as follows:
bool flock ( resource $handle , int $operation [, int &$wouldblock ] )
Parameter value | Description |
LOCK_SH | Get shared lock (read file) |
LOCK_EX | Get exclusive lock (write file) |
LOCK_UN | Release lock |
LOCK_NB | Prevent flock() from blocking when locking |
Use flock() function in the following example Lock the file, then write data, and finally unlock and close the file. The specific example code is as follows:
<?php header("Content-Type:text/html; charset=utf-8"); $filename = "tm.txt"; //声明要打开的文件名称 $fd = fopen($filename,"w"); //以w 模式打开文件 flock($fd,LOCK_EX); //锁定文件(独占共享) fwrite($fd,"我爱PHP中文网 www.php.cn"); //向文件中写入数据 flock($fd,LOCK_UN); //解除文件 fclose($fd); //关闭文件指针 readfile($filename); //输出文件内容 ?>
The output result is:
Instructions:
When writing data to the file, use W or w+ mode to open the file. If LOCK_EX is used at this time, the file will be accessed at the same time. Other users will not be able to obtain the file size and cannot perform operations!
In the next article, we will continue to introduce file pointers for advanced applications of file processing. For details, please read "Advanced Applications of PHP File Processing—File Pointers"!
The above is the detailed content of Advanced application of PHP file processing - remote file access and locked files. For more information, please follow other related articles on the PHP Chinese website!