Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • PHP Tutorial
  • PHP Exercises
  • PHP Array
  • PHP String
  • PHP Calendar
  • PHP Filesystem
  • PHP Math
  • PHP Programs
  • PHP Array Programs
  • PHP String Programs
  • PHP Interview Questions
  • PHP GMP
  • PHP IntlChar
  • PHP Image Processing
  • PHP DsSet
  • PHP DsMap
  • PHP Formatter
  • Web Technology
Open In App

PHP fwrite( ) Function

Last Updated : 31 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The fwrite() function in PHP is used to write data (string or binary) to an open file. Before using fwrite(), you need to open the file with fopen(). Once the file is open, fwrite() sends your data to that file.

Syntax:

fwrite(resource $handle, string $string, int $length = null): int|false

In this syntax:

The fwrite() function in PHP accepts three parameters.

  • $handle: The file resource obtained from fopen() or similar functions.
  • $string: The string data you want to write to the file.
  • $length (optional): The maximum number of bytes that you want to write.

Return Value:

It returns the number of bytes written on success, or False on failure.

Note: The fwrite() function was initially introduced in core PHP 4 and continues to be fully supported in PHP 5, PHP 7, and PHP 8.

How Does fwrite() Work?

The general process of writing to a file using fwrite() involves these steps:

  • Open the file using fopen() with an appropriate mode (e.g., w for write, a for append).
  • Use fwrite() to write your string data to the file.
  • Close the file with fclose() to free resources and save changes.

Writing to a New File

We open the file example.txt in write mode ("w"). Then, we write a string of text into the file using fwrite(). After writing, we close the file with fclose() to save the changes.

PHP
<?php $file = "example.txt"; // Open file for writing $handle = fopen($file, "w"); if ($handle) {     $text = "Hello, this is a sample text.\nWelcome to fwrite() function.";     $bytesWritten = fwrite($handle, $text);     echo "Wrote $bytesWritten bytes to $file";     fclose($handle); } else {     echo "Failed to open the file."; } ?> 

Output:

Screenshot-2025-05-31-162809
PHP fwrite( ) Function

Appending Data to an Existing File

We open the file example.txt in append mode ("a"), which lets us add data without deleting what’s already there. Then, we write a new line at the end of the file using fwrite(). Finally, we close the file with fclose().

PHP
<?php $file = "example.txt"; $handle = fopen($file, "a"); if ($handle) {     $newLine = "\nAdding a new line to the file.";     fwrite($handle, $newLine);     fclose($handle);     echo "Data appended successfully."; } else {     echo "Unable to open the file."; } ?> 

Output:

file

Writing Binary Data to a File

In this example, we open a file named data.bin in binary write mode. We then create some binary content using PHP’s pack() function to convert numbers into binary format. This binary data is written to the file, and finally, the file is closed.

PHP
<?php // Open the file in binary write mode $fileHandle = fopen("data.bin", "wb"); // Create binary data representing some unsigned short integers $binaryContent = pack("S*", 1234, 5678, 910, 1122); // Write the binary data into the file fwrite($fileHandle, $binaryContent); // Close the file to save changes fclose($fileHandle); echo "Binary data successfully saved."; ?> 

Output:

Screenshot-2025-05-31-164634
PHP fwrite( ) Function

Best Practices for Using the fwrite() Function

  • Always check if the file opens successfully before writing.
  • Use the correct file mode (w, a, wb, etc.) based on your needs.
  • Close the file after writing with fclose() to save changes.
  • Use file locking (flock()) when multiple processes may write simultaneously.
  • Validate and sanitize data before writing to avoid security issues.

Conclusion

The PHP fwrite() function is essential for writing data to files. It works together with fopen() to open files and fclose() to close them. Whether you want to create new files, update existing ones, or write partial data, fwrite() provides an efficient way to do so.With proper error handling and the right file modes, you can safely and effectively manage file writing operations in your PHP applications.


S

Shubrodeep Banerjee
Improve
Article Tags :
  • Misc
  • Web Technologies
  • PHP
  • PHP-file-handling
  • PHP-function
Practice Tags :
  • Misc

Similar Reads

    PHP basename( ) Function
    The basename() function in PHP is an inbuilt function which is used to return the base name of a file if the path of the file is provided as a parameter to the basename() function. Syntax: string basename ( $path , $suffix ) Parameters: The basename() function in PHP accepts two parameters which are
    2 min read
    PHP chgrp( ) Function
    The chgrp() function in PHP is an inbuilt function that is used to change the user group of the specified file. It returns true on success and false on failure. Only the superuser has the right to change the group of a file arbitrarily. Syntax: bool chgrp ( $filename, $group ) Parameters: The chgrp(
    2 min read
    PHP chmod( ) Function
    The chmod() function in PHP is an inbuilt function which is used to change the mode of a specified file to a specific mode given by the user. The chmod() function changes the permissions of the specified file and returns true on success and false on failure. Syntax:  bool chmod ( string $filename, i
    2 min read
    PHP chown( ) Function
    The chown() function in PHP is an inbuilt function which is used to change the owner of the specified file. It returns true on success and false on failure. Only the superuser has the right to change the owner of a file. Syntax: bool chown ( $filename, $user ) Parameters: The chown() function in PHP
    2 min read
    PHP copy( ) Function
    The copy() function in PHP is an inbuilt function which is used to make a copy of a specified file. It makes a copy of the source file to the destination file and if the destination file already exists, it gets overwritten. The copy() function returns true on success and false on failure. Syntax: bo
    2 min read
    PHP dirname( ) Function
    The dirname() function in PHP is an inbuilt function which is used to return the directory name of a given path. The dirname() function is used to parent directory's path i.e levels up from the current directory. The dirname() function returns the path of a parent directory which includes a dot ('.'
    2 min read
    PHP disk_free_space( ) Function
    The disk_free_space() function in PHP is an inbuilt function which is used to return the amount of free space in a specified directory. The disk_free_space() function denotes the free space in bytes. It returns the available space on a filesystem or on a disk partition. The disk_free_space() functio
    2 min read
    PHP disk_total_space( ) Function
    The disk_total_space() function in PHP is an inbuilt function which is used to return the total space of a specified directory. The disk_total_space() function denotes the total space in bytes. It returns the total space on a filesystem or on a disk partition. The disk_total_space() function returns
    2 min read
    PHP fclose() Function
    The fclose() function in PHP closes a file that was previously opened by fopen(). Closing a file releases the resource associated with it and makes sure all the data written to the file is properly saved. Not closing files can lead to resource leaks or incomplete data writing.Syntax:bool fclose(reso
    2 min read
    PHP feof( ) Function
    The feof() function in PHP is an inbuilt function which is used to test for the end-of-file on a file pointer. It checks if the "end-of-file" has been reached or not. The feof() function is used for looping through the content of a file if the size of content is not known beforehand. The feof() func
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences