0
0
PhpHow-ToBeginner · 3 min read

How to Write a File in PHP: Simple Guide with Examples

To write a file in PHP, use the file_put_contents() function which writes data to a file in one step. Alternatively, use fopen() to open a file, fwrite() to write data, and fclose() to close the file.
📐

Syntax

file_put_contents() writes a string to a file in one step. It takes the filename and the data as arguments.

fopen() opens a file and returns a file handle. You specify the filename and mode (like 'w' for write).

fwrite() writes data to the opened file handle.

fclose() closes the file handle to save changes.

php
<?php
// Using file_put_contents
file_put_contents('filename.txt', 'Hello World');

// Using fopen, fwrite, fclose
$file = fopen('filename.txt', 'w');
fwrite($file, 'Hello World');
fclose($file);
?>
💻

Example

This example shows how to write the text "Hello, PHP!" into a file named example.txt using file_put_contents(). It creates the file if it does not exist or overwrites it if it does.

php
<?php
$text = "Hello, PHP!";
file_put_contents('example.txt', $text);
echo "File written successfully.";
?>
Output
File written successfully.
⚠️

Common Pitfalls

  • Not having write permission on the folder or file causes errors.
  • Using fopen() with wrong mode (like 'r' for reading only) will not allow writing.
  • For large files, using file_put_contents() may be inefficient.
  • Not closing the file with fclose() can cause data loss.
php
<?php
// Wrong: fopen with read mode
$file = fopen('file.txt', 'r');
fwrite($file, 'data'); // This will fail
fclose($file);

// Right: fopen with write mode
$file = fopen('file.txt', 'w');
fwrite($file, 'data');
fclose($file);
?>
📊

Quick Reference

FunctionPurposeExample Usage
file_put_contentsWrite data to a file in one stepfile_put_contents('file.txt', 'Hello');
fopenOpen a file with a mode ('w' for write)$file = fopen('file.txt', 'w');
fwriteWrite data to an open file handlefwrite($file, 'Hello');
fcloseClose an open file handlefclose($file);

Key Takeaways

Use file_put_contents() for quick and simple file writing in PHP.
For more control, use fopen(), fwrite(), and fclose() together.
Always check file permissions to avoid write errors.
Close files after writing to ensure data is saved.
Use the correct mode ('w' for write) when opening files.