Explain file_put_contents in php.
Syntax:
file_put_contents(string $filename, mixed $data, int $flags = 0, ?resource $context = null): int|false
- $filename: The path of the file to which the data will be written.
- $data: The data to write to the file (it can be a string or an array).
- $flags: Optional parameter that can modify the behavior. For example:
FILE_APPEND– Appends the data to the file (if the file already exists).LOCK_EX– Acquires an exclusive lock on the file while writing.
- $context: Optional. A valid context resource created with
stream_context_create(). This allows you to modify the behavior of the file write (e.g., changing file stream settings).
Return Value:
- Returns the number of bytes written to the file on success.
- Returns
falseon failure.
Example 1: Basic Usage (Write to a file)
$file = "example.txt";
$data = "Hello, this is some text!";
$result = file_put_contents($file, $data);
if ($result !== false) {
echo "Data written successfully!";
} else {
echo "Failed to write data.";
}
This will write the string "Hello, this is some text!" to the example.txt file. If the file doesn't exist, it will be created.
Example 2: Append Data to a File
If you want to append data to a file (instead of overwriting it), you can use the FILE_APPEND flag.
$file = "example.txt";
$data = "\nAppended text!";
$result = file_put_contents($file, $data, FILE_APPEND);
if ($result !== false) {
echo "Data appended successfully!";
} else {
echo "Failed to append data.";
}
This will append "Appended text!" to the existing content in example.txt.
Example 3: Write an Array to a File
You can also write an array of data to a file by converting it into a string format, such as JSON or a serialized format.
$file = "data.json";
$data = ["name" => "John", "age" => 30, "city" => "New York"];
$result = file_put_contents($file, json_encode($data));
if ($result !== false) {
echo "JSON data written successfully!";
} else {
echo "Failed to write JSON data.";
}
This will write the array as a JSON string to data.json.
Example 4: Locking the File While Writing
To ensure that no other process can write to the file at the same time, you can use the LOCK_EX flag.
$file = "example.txt";
$data = "This will be locked while writing.";
$result = file_put_contents($file, $data, LOCK_EX);
if ($result !== false) {
echo "Data written with lock!";
} else {
echo "Failed to write data with lock.";
}
This ensures that the file is locked during the write process, preventing other PHP scripts from accessing it until the operation is completed.
Example 5: Handle Errors
You can handle errors by checking the result of file_put_contents().
$file = "/path/to/nonexistent/folder/example.txt"; // Invalid path
$data = "This will fail";
$result = file_put_contents($file, $data);
if ($result === false) {
echo "Failed to write data. Error occurred.";
} else {
echo "Data written successfully!";
}
In this case, since the file path is invalid (or the folder doesn't exist), it will fail and return false.
Summary:
file_put_contentsis a convenient function to write data to a file.- You can choose whether to overwrite or append data.
- Use flags like
FILE_APPENDandLOCK_EXto modify the behavior.
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
