Table of Contents
Functions of PHP Write File
1. fopen()
2. fwrite()
3. file_put_contents()
4. Overwriting
Examples to Implement of PHP Write File
Example #2
Conclusion
Recommended Article

PHP Write File

Aug 29, 2024 pm 01:02 PM
php

There are various in-built functions in PHP which are used to perform various actions upon a file. They maybe to create, open, read, write and other operations on the file.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Functions of PHP Write File

Below are the major functions available by default in the PHP below:

1. fopen()

First, in order to write to a file, we must know how to create that file. This is done with the help of the open() function. The name might be misleading as to open a file, but in PHP, the same function is used for creating and opening the file, just like vi functions in Linux. This function, as soon as it is executed, checks for the file if it exists and then only creates it. The example below demonstrates the same:

Code:

<?php
// Creating a file for test
$myfile = fopen("test.txt", "w")
?>
Copy after login

Output:

PHP Write File

2. fwrite()

After creating a file, we have to write the required contents into it, and hence we use this function for the same. This function will stop only when it reaches the end of the file (EOF) or the length we specify according to the order which comes first.

Syntax:

fwrite(file, string, length)
Copy after login
  • where the file is the mandatory field which describes the file we should write to
  • the string is another required parameter which tells the string to write to the opened file
  • length is an optional parameter and gives us the maximum number of bytes to be written

Code:

<?php
// Your code here!
$f = fopen("testfile.txt", "w");
$text = "Random data here\n";
fwrite($f, $text);
?>
Copy after login

Output:

PHP Write File

Here testfile.txt is the file created, and the string value assigned to $text will be written to that file.

3. file_put_contents()

This is another function which can be used to write contents to a file in PHP. There are a certain number of rules in the same order mentioned to be followed when accessing a file:

  • There is a property called FILE_USE_INCLUDE_PATH, and it checks the path if it includes a copy of the filename when it is set.
  • Creates a file after checking whether it exists or not
  • Next, it opens the file
  • If the property LOCK_EX is set, then it locks the file
  • When the property FILE_APPEND is set, it moves to the end of the file else clears the contents of the file.
  • Now it writes the required data to the file.
  • Closes the file and release if any locks are present
Note: The property FILE_APPEND should be used in order to save data from getting fully erased as it appends data to the end of the file.

Syntax:

file_put_contents(filename, text, mode, context)
Copy after login
  • where filename is the mandatory parameter and tells us the entire path of the file where we have to write to, this function hence checks and creates a file.
  • text is another mandatory field which is the data we have to write to our file. It can be in the form of a simple string, an array of strings or a data stream.
  • mode is the optional field which gives us various ways to operate on the file. Its possible values are:
    • FILE_USE_INCLUDE_PATH: This searches for specified filename in the include directory path.
    • FILE_APPEND: It appends the data to the file instead of overwriting the same.
    • LOCK_EX: This puts an explicit lock on the file when being written.
  • context is the optional parameter which gives the context of the file. It is basically a bunch of options which can alter the stream’s behavior.

Return Values: This function returns the total number of bytes which are written to the file in case of a SUCCESS and returns value FALSE if failed.

Below is the example:

Code:

<?php
echo file_put_contents("filetest.txt","Testing for file write");
?>
Copy after login

Output:

PHP Write File

Here the file we are creating is given as the first parameter, and the next parameter is the text written into that file.

4. Overwriting

We can overwrite to the above file in which data has been already written. Whatever data is already present in the file is cleaned off, and it will start as a brand new empty file. In the below examples, we will open an existing file and try writing new data on it.

Below is the example:

Code:

<?php
$f = fopen("testfile.txt", "w");
$text = "Random data here\n";
$filetext = "Over writing the data\n";
fwrite($f, $filetext);
$filetext = "File Dummy Data\n";
fwrite($f, $filetext);
fclose($f);
?>
Copy after login

Output:

PHP Write File

Here we are overwriting data in testfile.txt, so whatever is mentioned in the $filetext string value, the same will be written to the file. And when we use the same write command again by changing data given to the $filetext, then the old data is cleaned up and occupied by the latest text value that is provided.

At the end of the file, we always should close it by using the close() function which we have opened using the fwrite() function. As shown in the above example, we also use the \n, which represents the newline equivalent to pressing the enter button on our keyboard.

Now let us take an example and see how to include more data in our file.

Examples to Implement of PHP Write File

Below are the examples of PHP Write File:

Example #1

First, we add 2 lines of data using the below code:

Code:

<?php
$testf = "TestFile.txt";
$filehandle = fopen($testf, 'w');
$fdata = "Julian Caesar\n";
fwrite($filehandle, $fdata);
$fdata = "Harry James\n";
fwrite($filehandle, $fdata);
print "Data writing completed";
fclose($filehandle);
?>
Copy after login

Output:

PHP Write File

This creates a file TestFile.txt having 2 lines of data as mentioned.

Example #2

We will append another 2 names in the same file as shown below:

Code:

<?php
$testf = "TestFile.txt";
$filehandle = fopen($testf, 'a');
$fdata = "Lilly Potter\n";
fwrite($filehandle, $fdata);
$fdata = "Edward Cullen\n";
fwrite($filehandle, $fdata);
print "Data has been appended";
fclose($filehandle);
?>
Copy after login

Output:

PHP Write File

This example appends the given names to the same file as in the first example.

Conclusion

As shown above, there are various methods and steps that need to be followed when we want to write to a file in PHP. fwrite() is one of the main functions to do this and is used majorly for writing data to a file. They can do basic writing of data to our file but should be used in combination with other mandatory functions like open() and close(), without which it is not possible to perform operations on the file if it does not exist.

Recommended Article

This is a guide to the PHP Write File. Here we discuss the Introduction and its Functions of PHP Write File along with examples and Code Implementation. You can also go through our other suggested articles to learn more-

  1. Overview of Abstract Class in Python
  2. What is Abstract Class in PHP?
  3. Socket Programming in PHP with Methods
  4. PHP chop() | How to Work?

The above is the detailed content of PHP Write File. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 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.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 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.

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.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 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.

See all articles