← Back to Chapters

PHP file_put_contents() & file_get_contents()

? PHP file_put_contents() & file_get_contents()

? Quick Overview

The file_put_contents() and file_get_contents() functions in PHP provide an easy and efficient way to write data to files and read entire file contents into a string. They are commonly used for configuration files, logs, and lightweight storage.

? Key Concepts

  • file_put_contents() writes data to a file
  • file_get_contents() reads full file data at once
  • Files are created automatically if missing
  • Ideal for small and quick I/O tasks

? Syntax & Theory

  • file_put_contents(filename, data, flags) writes data and optionally appends content
  • file_get_contents(filename) returns file content as a string

? Code Example

? View Code Example
// Write data to a file and read it back
<?php
$file="example.txt";
$content="Hello, this is a test file.";

if(file_put_contents($file,$content)){
echo "File written successfully<br>";
}

if(file_exists($file)){
echo file_get_contents($file);
}
?>

? Live Output / Explanation

The script creates a text file, writes a string into it, and then reads the same content back from the file and displays it on the screen.

? Interactive Concept Flow

? File ➜ ✍️ Write Data ➜ ? Saved ➜ ? Read Data ➜ ?️ Display

? Use Cases

  • Saving user preferences
  • Writing log files
  • Storing temporary application data
  • Reading configuration files

✅ Tips & Best Practices

  • Use FILE_APPEND flag to avoid overwriting files
  • Check file permissions before writing
  • Avoid using for very large files

? Try It Yourself

  • Append data using FILE_APPEND
  • Read multiple files using a loop
  • Compare performance with fopen() and fread()