


Introduction to commonly used file operation reading and writing functions in PHP_PHP Tutorial
This article introduces the following commonly used file operation functions file_get_contents reads the entire file content fopen creates and opens files fclose closes the file fgets reads a line of file content file_exists checks whether a file or directory exists file_put_contents writes to file fwrite writes files
Use PHP built-in function file_exists to check whether a file or directory exists. The file_exists function returns TRUE if the file or directory exists, or FALSE if it does not exist.
The following is a simple example code to check whether the file exists:
代码如下 | 复制代码 |
$filename = "C:blablaphphello.txt"; if (file_exists($filename)) {echo "The file $filename exists."; }else { echo "The file $filename does not exist." ;}?> |
If the file exists, the displayed result of executing the PHP file is:
The file C:blablaphphello.txt exists.
If the file does not exist, the displayed result of executing the PHP file is:
The file C:blablaphphello.txt does not exist.
You can also use the file_exists function to test whether a directory exists. The sample code is as follows:
The code is as follows | Copy code | ||||
{echo "yes";}
|
The entire file content can be read using the PHP built-in function file_get_contents.
file_get_contents(filepath)
代码如下 | 复制代码 |
$f = file_get_contents("C:blablaphphello.txt"); echo $f;?> |
C:blablaphphello.txt
The following php code uses the file_get_contents function to read the file and output the file contents:
The code is as follows | Copy code |
$f = file_get_contents("C:blablaphphello.txt"); echo $f;?>
|
Note: Since the file path contains backslashes, and in PHP strings, the backslashes need to be escaped and represented by two backslashes. (If you forget the escape of some special characters in PHP, please read the PHP string mentioned above.)
代码如下 | 复制代码 |
$f = fopen("c:datainfo.txt", "r"); ?> |
The code is as follows | Copy code |
$f = fopen("c:datainfo.txt", "r"); ?> |
Among them, c:datainfo.txt is the file path, and r indicates that the mode of opening the file is read only mode.
The fopen function has the following modes for opening files:
Mode Description
r Read only, the file pointer is at the beginning of the file.
r+ for reading and writing, the file pointer is at the beginning of the file.
w is write only, the file pointer is at the beginning of the file, and the file length is truncated to 0.
Create the file if it does not exist.
w+ reads and writes, the file pointer is at the beginning of the file, and the file length is truncated to 0.
Create the file if it does not exist.
a is write only, the file pointer is at the end of the file.
Create the file if it does not exist.
a+ for reading and writing, the file pointer is at the end of the file.
Create the file if it does not exist.
x is write only, the file pointer is at the beginning of the file.
If the file already exists, the fopen () function returns FALSE and generates an E_WARNING level error.
Create the file if it does not exist.
x+ for reading and writing, the file pointer is at the beginning of the file.
If the file already exists, the fopen () function returns FALSE and generates an E_WARNING level error.
Create the file if it does not exist.
If the file is successfully opened, the return value of the fopen function is a file pointer resource. If an error occurs, FALSE is returned.
Create file
Selecting an appropriate value for the fopen function parameter mode, you can create a file with fopen, for example:
The code is as follows | Copy code | ||||
$f = fopen("c:data103.txt", "a"); $f = fopen("c:data104.txt", "a+");
$f = fopen("c:data105.txt", "x");
|
The syntax for fgets to read a line of file content is:
fgets(filepointer)
Below we give an example of how to read a file line by line.
代码如下 | 复制代码 |
$f= fopen("C:blablaphpsites.txt","r"); while (!feof($f)){ $line = fgets($f); echo "site: ",$line," "; } fclose($f);?> |
The code is as follows | Copy code |
$f= fopen("C:blablaphpsites.txt","r");
while (!feof($f)){
$line = fgets($f);
echo "site: ",$line," "; } fclose($f);?> |
Execute the PHP file and the displayed result returned is:
site: woyouxian.comsite: blabla.cnsite: google.com
The first line of this PHP code opens a file and the last line closes a file. The while loop statement means that when the file does not end, read one line and execute it in a loop until the file pointer reaches the end of the article.
The feof function is a built-in function of PHP, used to test whether the file pointer has reached the end of the file. Returns TRUE if yes, FALSE if not. The English meaning of eof is end of file, which is easy to remember.
Under normal circumstances, the return value of the fgets function is a string. If an error occurs, FALSE is returned.
Describes how to use the PHP built-in function fclose to close a file.
The fclose function syntax is as follows:
fclose(filepointer)
The fclose function returns TRUE if successful and FALSE if failed.
Here is a PHP code example of the fclose function:
The code is as follows | Copy code | ||||
fclose($f); ?>
|
In this chapter, we describe how to use fopen, fwrite, and fclose to implement a series of operations of opening files, writing files, and saving and closing files. Focus on the fwrite function.
PHP built-in function fwrite is used to write files.
fwrite(handle,string)
代码如下 | 复制代码 |
$f= fopen("C:blablaphpwrite.txt","w"); fwrite($f,"It is awesome.");fclose($f);echo "done"; ?> |
The following PHP code example demonstrates how to create a new file, write its contents, then save and close the file:
The code is as follows | Copy code |
$f= fopen("C:blablaphpwrite.txt","w");
fwrite($f,"It is awesome.");fclose($f);echo "done";
|
After executing the PHP file, a file with the path C:blablaphpwrite.txt will be created. The content of the file is It is awesome.
If you want to append content to the existing file, you only need to modify the parameter mode value of fopen, as follows:
$f= fopen("C:blablaphpwrite.txt","a");
For details about the parameter mode value of the fopen function, see fopen.
The fwrite function returns the number of bytes written to the file. If an error occurs, it returns FALSE.
PHP built-in function file_put_contents is used to write files.
代码如下 | 复制代码 |
$content = "one for all"; file_put_contents($path,$content); if (file_exists($path)) {echo "ok";}else {echo "ng";} ?> |
The code is as follows | Copy code |
$content = "one for all"; file_put_contents($path,$content); if (file_exists($path)) {echo "ok";}else {echo "ng";} ?> |
This PHP code example will create a file with the path C:blablafilesysone.txt and the content of the file is one for all.
If you want to append content to an existing file, you can also use the file_put_contents function, just add one parameter.
file_put_contents(filepath,data,flags)
When the value of flags is FILE_APPEND, it means appending content to the existing file.
For example, if we want to append content to the C:blablafilesysone.txt file in the above example, we can write like this:
The code is as follows
|
Copy code
|
||||
$path="C:blablafilesysone.txt"; $content = "all for one"; file_put_contents($path,$content,FILE_APPEND); |
if (file_exists($path))
http://www.bkjia.com/PHPjc/629216.html

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.


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

Zend Studio 13.0.1
Powerful PHP integrated development environment

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

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

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

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.