The file_put_contents() function in PHP is an inbuilt function which is used to write a string to a file. The file_put_contents() function checks for the file in which the user wants to write and if the file doesn’t exist, it creates a new file.
The path of the file on which the user wants to write and the data that has to be written are sent as parameters to the function and it returns the number of bytes that were written on the file on success and FALSE on failure.
file_put_contents($file, $data, $mode, $context)
Parameters: The file_put_contents() function in PHP accepts two mandatory parameters and two optional parameters.
- $file: It specifies the file on which you want to write.
- $data: It specifies the data that has to be written on the file. It can be a string, an array or a data stream.
- $context: It is an optional parameter which is used to specify a custom context or the behavior of the stream.
- $mode: It is an optional parameter which is used to specify how the data has to be written on the file such as FILE_USE_INCLUDE_PATH, FILE_APPEND, LOCK_EX.
Return Value: It returns the number of bytes that were written on the file on success and FALSE on failure.
Errors And Exception:
- The file_put_contents() function returns Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE.
- This function fails to write contents if the directory provided is invalid.
Input : file_put_contents("gfg.txt", "A computer science portal for geeks!"); Output : 36 Input : $file_pointer = 'gfg.txt'; $open = file_get_contents($file_pointer); $open .= "A computer science portal for geeks!"; file_put_contents($file_pointer, $open); Output : 36
Below programs illustrate the file_put_contents() function.
- How to get the function name inside a function in PHP ?
- PHP | end() Function
- p5.js | pan() Function
- PHP | Ds\Set first() Function
- PHP | Ds\Set last() Function
- PHP | Ds\Set add() Function
- CSS min() Function
- CSS max() Function
- PHP | Ds\Set contains() Function
- p5.js | hex() function
- CSS | rgb() Function
- CSS env() Function
- D3.js | d3.min() function
- p5.js | nfp() Function
- p5.js | nfs() Function
- p5.js | str() function
- D3.js | d3.map.set() Function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.