Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

PHP’s filesystem API can read and write files, inspect metadata, manage directories, handle uploads, and work with streams. For reliable code, choose an API for the operation, resolve paths deliberately, check return values, and restrict the PHP process and user input to the resources the application is meant to manage.

How do I read and write files in PHP?

Use file_get_contents() and file_put_contents() for straightforward whole-file operations. Use fopen() with fread() or fwrite() when you need explicit stream handling, such as processing data incrementally. The PHP manual’s filesystem function index covers these and related operations.

<?php
$path = __DIR__ . '/data/message.txt';

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

$written = file_put_contents($path, "Updated contentn");
if ($written === false) {
    throw new RuntimeException('Could not write the file.');
}

These calls can fail: a path may not exist, the PHP process may lack permission, or a wrapper may be unavailable or disallowed. Check the documented return value for the operation rather than assuming success. For example, fopen() returns a stream resource on success or false on failure. Use strict comparisons when checking results, because values such as zero can be meaningful for some operations.

Choose whole-file calls or explicit streams

  • Whole-file convenience calls: file_get_contents() reads a resource into a string, while file_put_contents() writes a string. They are concise for suitable whole-file tasks.
  • Explicit stream handling: fopen() opens a stream; fread() and fwrite() let code control the read or write sequence. Check the open result before using the stream and close it when finished.

The manual documents these operations but does not establish a universal performance ranking between them. Choose based on the operation and resource, and verify the behavior required by your application.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Which PHP function should I use for common filesystem tasks?

The filesystem API includes more than reading and writing. Select the function that matches the task, then handle its return value and failure conditions as documented.

Task Functions
Open and transfer data fopen(), fread(), fwrite(), file_get_contents(), file_put_contents()
Copy or rename copy(), rename()
Create, inspect, or remove directories mkdir(), glob(), rmdir()
Check file type, status, or metadata is_file(), is_dir(), is_readable(), is_writable(), filesize(), filemtime(), filetype(), fileperms()
Manage permissions, locks, temporary files, or deletion chmod(), flock(), tempnam(), tmpfile(), unlink()
Resolve a path or handle an uploaded file realpath(), is_uploaded_file(), move_uploaded_file()

A status check such as is_writable() can help explain why an operation may fail, but it does not replace checking the operation itself: permissions or filesystem state can change between a check and a later write.

How does PHP resolve relative file paths?

PHP’s default local filesystem wrapper is file://. An absolute path identifies a location directly. A relative path is resolved against PHP’s current working directory, not necessarily the directory containing the script. In CLI use, the working directory ordinarily starts as the directory from which the command was invoked. Some functions and options may also search include_path. See the PHP manual’s file:// wrapper documentation.

When code needs a path anchored to the current script, construct it explicitly rather than relying on the caller’s working directory:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
$path = __DIR__ . '/data/message.txt';

That makes the intended base directory clear, but it does not itself authorize access or guarantee the file exists. The path must still be accessible to the PHP process. The fopen() documentation describes path handling and notes that configured restrictions such as open_basedir can further limit access.

How do PHP streams and wrappers work?

A stream is PHP’s common model for reading or writing a sequence of data. A wrapper supplies the behavior for a particular resource scheme. PHP includes built-in wrappers and supports registered custom wrappers; the functions and wrappers available depend on the operation. The Streams documentation explains the model, and Supported Protocols and Wrappers lists wrapper behavior.

This matters because a function that accepts a filename may accept more than a local disk path. For example, fopen() can receive a value in scheme://... form. If that scheme identifies a network URL wrapper, whether PHP can use it depends in part on configuration. Do not treat an arbitrary filename from a user as safe merely because an API is described as a file function.

Check URL-wrapper configuration on the deployed runtime

The PHP manual documents allow_url_fopen with a default of 1; it enables URL-aware wrappers for functions such as fopen(). It documents allow_url_include with a default of 0, requiring allow_url_fopen, and records that allow_url_include has been deprecated since PHP 7.4.0. These are manual-documented defaults, not proof of a particular server’s settings. Check the deployed PHP configuration. See Filesystem Runtime Configuration.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How can I prevent path traversal in PHP?

Path traversal occurs when a value supplied by a user is used to reach a file outside the area the application intended to expose. Filtering a filename is not a substitute for authorization: first decide which directory the authenticated user may manage and which operations are permitted there. The PHP manual’s Filesystem Security guidance illustrates the risk of joining a home-directory path with a submitted filename and cautions that basename() alone is not a complete defense for every design.

  • Define the boundary: Choose the application directory a user may access. Do not let a submitted path select an unrestricted filesystem location.
  • Allow only intended names and operations: Validate against the formats and actions the application actually needs. An explicit allow-list is often easier to reason about than trying to enumerate every dangerous path.
  • Enforce least privilege: Run PHP with only the filesystem permissions it needs. Filesystem permissions and PHP configuration—including open_basedir, when used—are additional boundaries, not replacements for application authorization.
  • Check the result: Handle failures from reads, writes, directory operations, and path resolution instead of assuming that validation guarantees access.

Exact deployment controls depend on the operating system and hosting model. Avoid treating a single string function as a universal path-traversal fix.

How should PHP handle uploaded files?

An uploaded file is a separate trust boundary: do not treat its original name or contents as inherently safe. PHP’s filesystem reference includes is_uploaded_file() and move_uploaded_file() for the upload flow. Validate the application’s authorization and accepted file policy, then use the documented upload functions rather than treating an arbitrary client-supplied path as a trusted local file. Consult the filesystem function index for those APIs.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.