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.
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:
<code>file_put_contents(string $filename, mixed $data, int $flags = 0, resource $context = ?): int|false</code>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.
<code>$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";
}</code>Example 2 demonstrates writing the same string to a remote URL, assuming the URL has write permissions.
<code>$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";
}</code>The function is useful for logging, file caching, and remote API calls due to its simplicity and flexibility.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.