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) 得到一个资源类型 ?>
- 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>"; } ?>
- 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);//解锁 ?>
When 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);
Unlock:
- 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!

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.


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

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool