PHP file_put_contents Function Overview & Tutorial
In PHP programming, file_put_contents is an inbuilt PHP function used when you want to write a string to a file on the server or your local computer (i.e. if you’re executing the PHP web application on a local web server).
How Does PHP file_put_contents Work
First, the file_put_contents() function checks for the availability of the file you want to write to. In the event the said file doesn’t exits, the file_put_contents function creates a new one.
The function accepts the directory path of the file you want to write to as well as the data string that you want to write to the said file as input parameters.
Now, if the data were written to the file successfully, the file_put_contents() function returns the number of bytes written. On the other hand, if the attempt to write to the file was unsuccessful, the function returns a Boolean FALSE value.
The function syntax is pretty simple and straightforward as can be observed below:
file_put_contents($file, $data, $mode, $context)
Now, let’s take a look at the parameters need to use this function.
The PHP file_put_contents function can accept a total of four input parameters when called. Out of these four parameters, two required parameter whereas the other two are optional.
Let’s take a look at the parameters:
- $file: This is a required parameter. With this parameter you specify the file you want to write to.
- $data: This is a required parameter. It allows you to specify the data you want to write as either a string, an array or a data stream.
- $context: This is an optional parameter. You use it to indicate a custom context or how you want the data stream to behave.
- $mode: This is another optional parameter that you can use to tell the program how you want the data written to the $file.
As we’ve already mentioned above, if the write attempt is successful then the number of bytes of the written data is returned. However, if it was unsuccessful a Boolean FALSE is returned.
Errors and Exceptions
The function returns a Boolean FALSE when it fails to run successfully. In addition, the function will fail when an invalid directory to the target file is provided.
Here’s a quick example of how to use the file_put_contents() function in the code below:
file_put_contents("fileput.txt", "file_put_contents is fun to use!");
The result upon execution of the code is:
Ouput : 32
The file_put_contents in php function is a very useful function in PHP for file manipulation and can make life easy for you when working on your PHP project. To learn more about this function, click here to visit its official PHP web page.