Using PHP file_put_contents() to Write Data to Files and URLs

This article explains the PHP file_put_contents() function, its parameters, and how to use it to write strings or other data to local files or remote URLs, providing syntax details and practical code examples for file creation, data writing, and error handling.

php Courses
php Courses
php Courses
Using PHP file_put_contents() to Write Data to Files and URLs

In PHP development, the built‑in file_put_contents() function can write a string or other data to a specified file or URL.

The function creates a new file if it does not exist and returns the number of bytes written or false on failure.

Basic syntax:

file_put_contents(string $filename, mixed $data, int $flags = 0, resource $context = ?): int|false

Parameters: $filename – target file name or URL; $data – data to write; $flags – optional write mode; $context – optional stream context.

Example 1 shows writing a string to a local file, creating the file if necessary and checking the result.

$data = "Hello, world!";
$file = "test.txt";
$result = file_put_contents($file, $data);
if ($result !== false) {
    echo "Data successfully written to file";
} else {
    echo "Failed to write file";
}

Example 2 demonstrates writing the same string to a remote URL, assuming the URL has write permissions.

$data = "Hello, world!";
$url = "https://example.com/test.php";
$result = file_put_contents($url, $data);
if ($result !== false) {
    echo "Data successfully written to URL";
} else {
    echo "Failed to write URL";
}

The function is useful for logging, file caching, and remote API calls due to its simplicity and flexibility.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPCode Examplefile_put_contentsURL writing
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.