PHP file basic operation examples sharing
This article mainly shares with you basic operation examples of PHP files. I hope it can help you. First, let's share with you the basic operations of reading and writing PHP files.
Basic operations of reading and writing
Write file function: file_put_contents()
-
FILE_USE_INCLUDE_PATH : The built-in path for a copy of filename will be checked
LOCK_EX : The file will be locked
FILE_APPEND : Will be moved to the end of the file. Otherwise, the contents of the file will be cleared
-
Syntax:
int file_put_contents(file,data,mode,context)
Parameters Description file Required. Specifies the file to which data is to be written. If the file does not exist, a new file is created. data Optional. Specifies the data to be written to the file. Can be a string, one-dimensional array, or data stream. mode Optional. How to open/write files. Possible values: FILE_USE_INCLUDE_PATH, FILE_APPEND, LOCK_EX context Optional. Specifies the environment for a file handle. context is a set of options that can modify the behavior of the stream. If null is used, it is ignored. Return value: This function will return the number of bytes of data written to the file.
mode parameter description
The function is the same as calling fopen(), fwrite() and fclose() in sequence.
Read file function: file_get_contents()
-
Syntax:
string file_put_contents (path,include_path,context,start,max_length)
##Parameter Description path Required. Specifies the file to be read. Can be an external url include_path optional. If you also want to search for files in include_path, you can set this parameter to "1". context Optional. Specifies the environment for a file handle. start Optional. Specifies the position in the file to begin reading. This parameter is new in PHP 5.1. max_length Optional. Specifies the number of bytes to read. This parameter is new in PHP 5.1. Return value: the read string.
Other commonly used file functions
Unlink() Delete file
- ##Rename( ) File move (rename)
- Filesize() File size
- File_exists() Whether the file exists
- Filemtime() The last modification time of the file!
Most file reading and writing are completed using the functions: File_put_contents, file_get_contents.
In a few cases, in special cases, the above two functions are not easy to use.
Typically, the file is too large! It can only be operated part by part!
The basic units are bytes:- #fopen() function opens a file or URL. If the opening fails, this function returns FALSE.
Open file handle, data path between PHP program and file!
Open mode: Specify what operations need to be performed after opening the file! The following modes can be selected:
Requires two parameters: file address and open mode! - #r: read, read mode.
- w: write, write operation, clear write.
- a: append, write operation, append writing.
- x: New writing can only create new files for operation! It is a write operation, similar to w
- + extended mode: extended operations can complete read and write operations.
<?php $handle = fopen('./data.txt','r'); var_dump($handle); // resoure(3) of type (stream) 得到一个资源类型 ?>
Copy after login - File handle reading functions fread(),fgetc(),fgets(),feof();
- One byte data = fgetc(handle); //garbled characters in the case of multi-byte characters
Whenever a byte is read, move the file pointer forward by one byte! In handle operations, it depends on the file pointer!
- String = fgets(handle, length)
If a newline character is read first when reading, it will also terminate. Also called the line reading function! Typical logic, each line records a set of information, this function is the most commonly used!
- feof() determines whether the end of the file is reached
Read all the information in the file Example:
<?php $handle = fopen('./langref.txt','r'); while (! feof($handle)) { $line = fgets($handle,1024); echo $line . "</br>"; } ?>
Copy after login - String = fread(handle, Length)
Read content based on length, which is different from fgets and is not limited by newlines
The only restriction is: the maximum length cannot exceed 8192! - File handle write function fwrite($handle, content)
- Close handle fclose($handle)
- Pointer operation function
- fseek(handle, position), positioning setting pointer, the position starts from 0 and increases!
- ftell(handle), get the pointer position!
By default, PHP's file operation function is not in a blocking state. Free operating state. Therefore, it is easy to cause errors when operating files concurrently. When one script operation needs to block other script operations, file locks need to be used.
Lock operation process:
Lock type:
Add the lock first, check whether the lock is added successfully, and use it again if successful!- Read lock: s-lock (share-lock) shared lock, the expected additional lock before the read operation. As a result, concurrent reads are allowed and additional write operations are blocked.
- Write lock: x-lock (exclusive-lock) exclusive lock, exclusive lock, try to add the lock type before writing operation. As a result, other scripts cannot read or write.
- Intention lock: All scripts that operate resources follow a convention to use file locks (convention).
Type:
- LOCK_SH Read lock
- LOCK_EX Write lock ##LOCK_UN Unlock
<?php //*********脚本1,想要读取文件信息*********** //尝试加读锁 $lock_result= flock($handle, LOCK_SH); //判断锁定结果 if(!$lock_result){ die('锁定失败,不能操作文件'); } //文件操作 $str = fgets($handle, 1024); var_dump($str); sleep(5); echo '<br>'; $str = fgets($handle, 1024); var_dump($str); flock($handle, LOCK_UN);//解锁 ?> <?php //*********脚本2,想要往文件里写入信息*********** //尝试加写锁 $lock_result= flock($handle, LOCK_EX); //判断锁定结果 if(!$lock_result){ die('锁定失败,不能操作文件'); } //文件操作 $result = fwrite($handle, '123456'); flock($handle, LOCK_UN);//解锁 ?>
Copy after loginWhen colleagues execute, the above script 2 needs to wait (in the blocked state) for script 1 to complete before it is executed. ,
Emphasize that you must judge whether the lock is added successfullyYou can use LOCK_NB to not block when the lock fails:
$lock_result = flock($handle, LOCK_EX | LOCK_NB);
Copy after loginUnlock:
- Flock($handle, LOCK_UN) to force unlock,
- Fclose() to automatically unlock!
- Related recommendations:
The above is the detailed content of PHP file basic operation examples sharing. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

To work on file upload we are going to use the form helper. Here, is an example for file upload.

Validator can be created by adding the following two lines in the controller.

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an
