search
HomeBackend DevelopmentPHP TutorialIntroduction to commonly used file operation reading and writing functions in PHP_PHP Tutorial

Introduction to commonly used file operation reading and writing functions in PHP_PHP Tutorial

Jul 13, 2016 pm 05:13 PM
phpunderintroduceseveralfunctionCommonly usedoperatedocumentarticleuseRead and write

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
 代码如下 复制代码

if (file_exists("C:blablaphp"))
  {echo "yes";}
else
  {echo "no";}

if (file_exists("C:blablaphp"))

{echo "yes";}
else

{echo "no";}

The entire file content can be read using the PHP built-in function file_get_contents.

The file_get_contents function reads the entire file and returns a string. The simplest way to write file_get_contents is as follows:


file_get_contents(filepath)

For example, you have a .txt file with the path:
 代码如下 复制代码


$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.)

The return value of the file_get_contents function is the read file content string. If an error occurs, FALSE is returned.
 代码如下 复制代码
$f = fopen("c:datainfo.txt", "r");
?>
A file can be opened using the PHP built-in function fopen. Open file The simplest syntax of fopen is as follows: fopen(filepath,mode) Here is an example of PHP code to open a file:
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:data101.txt", "w");
$f = fopen("c:data102.txt", "w+");
$f = fopen("c:data103.txt", "a");
$f = fopen("c:data104.txt", "a+");
$f = fopen("c:data105.txt", "x");
$f = fopen("c:data106.txt", "x+");
?>

$f = fopen("c:data101.txt", "w"); $f = fopen("c:data102.txt", "w+");

$f = fopen("c:data103.txt", "a");

$f = fopen("c:data104.txt", "a+");

$f = fopen("c:data105.txt", "x");
$f = fopen("c:data106.txt", "x+");

?>

Use the PHP built-in function fgets to read a line of the file.


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);?>


Suppose we have a sites.txt file with three lines and the following content: woyouxian.comblabla.cngoogle.com The file path of sites.txt is: C:blablaphpsites.txt We use PHP to read the file content line by line. The PHP code is as follows:
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
 代码如下 复制代码

$f = fopen("c:datainfo.txt", "r");
fclose($f);
?>

$f = fopen("c:datainfo.txt", "r");
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.

The common syntax of the fwrite function is:

fwrite(handle,string)
 代码如下 复制代码
$f= fopen("C:blablaphpwrite.txt","w");
fwrite($f,"It is awesome.");fclose($f);echo "done";
?>


Among them, the parameter handle represents the file pointer resource (usually created by the fopen function), and string represents the content to be written.

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 simplest way to write the file_put_contents function can only use two parameters, one is the file path and the other is the content to be written. The syntax is as follows: file_put_contents(filepath,data) If the file does not exist, the file_put_contents function will automatically create the file; if the file already exists, the original file will be overwritten. You can use the file_put_contents function to create and write a new file, or overwrite an original file. Here is an example of PHP code using the file_put_contents function:
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:

if (file_exists($path)) {echo "ok";}else {echo "ng";}
The code is as follows
 代码如下 复制代码
$path ="C:blablafilesysone.txt";
$content = " all for one";
file_put_contents($path,$content,FILE_APPEND);
if (file_exists($path)) 
{echo "ok";}else  {echo "ng";}
?>

Copy code

$path="C:blablafilesysone.txt";
$content = "all for one"; file_put_contents($path,$content,FILE_APPEND);
?>

After executing the PHP file, we looked at the C:blablafilesysone.txt file and found that the file content had increased and became: one for all all for one The file_put_contents function returns the number of bytes written to the file, or FALSE if an error occurs.
http://www.bkjia.com/PHPjc/629216.html
www.bkjia.com
truehttp: //www.bkjia.com/PHPjc/629216.htmlTechArticleThis article introduces the following common file operation functions file_get_contents Read the entire file content fopen Create and open the file fclose Close the file fgets and read one line of the file file_e...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

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: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

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.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

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: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

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 in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

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: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

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: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

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.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

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.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

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

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

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.