PHP Functions Reference

PHP file_get_contents() and file_put_contents() Functions

Read and write files in PHP while handling failures, permissions, paths, and safe storage locations.

PHP file_get_contents() and file_put_contents()

PHP provides simple functions for reading and writing file contents. They are convenient for small files, configuration data, and basic cache files.

Read a File

$content = file_get_contents($path);

if ($content === false) {
    throw new RuntimeException("Could not read the file.");
}

Use a trusted, controlled path. Do not allow an untrusted request parameter to become an arbitrary filesystem path.

Write a File

$result = file_put_contents(
    $path,
    $content,
    LOCK_EX
);

if ($result === false) {
    throw new RuntimeException("Could not write the file.");
}

LOCK_EX requests an exclusive lock while writing. It does not replace a complete strategy for atomic file replacement or concurrent application behavior.

Security and Reliability

Store private files outside the public web root, set restrictive permissions, validate file paths, and handle disk-full or permission errors. Avoid using these functions to load arbitrarily large files into memory.

Summary

These functions make simple file operations easy, but applications must control paths, permissions, file sizes, and error handling.

Share this page Help other developers discover this resource.