Tutorialspoint.dev

PHP | file_put_contents() Function

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.

Syntax:

file_put_contents($file, $data, $mode, $context)

Parameters: The file_put_contents() function in PHP accepts two mandatory parameters and two optional parameters.

  1. $file: It specifies the file on which you want to write.
  2. $data: It specifies the data that has to be written on the file. It can be a string, an array or a data stream.
  3. $context: It is an optional parameter which is used to specify a custom context or the behavior of the stream.
  4. $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:

  1. The file_put_contents() function returns Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE.
  2. This function fails to write contents if the directory provided is invalid.

Examples:

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.

Program 1:

<?php
  
// writing content on gfg.txt
echo file_put_contents("gfg.txt", "A computer 
                  science portal for geeks!");
?>

Output:

36

Program 2:

<?php
  
$file_pointer = 'gfg.txt';
  
// Open the file to get existing content
$open = file_get_contents($file_pointer);
  
// Append a new person to the file
$open .= "A computer science portal for geeks!";
  
// Write the contents back to the file
file_put_contents($file_pointer, $open);
  
?>

Output:

36

Reference:
http://php.net/manual/en/function.file-put-contents.php



This article is attributed to GeeksforGeeks.org

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter