PHP file_put_contents() Function

Definition

The file_put_contents() writes a string to a file.

Syntax

PHP file_put_contents() Function has the following syntax.

file_put_contents(file,data,mode,context)

Parameter

ParameterIs RequiredDescription
fileRequired.File to write. For non-existing file, this function will create one
dataRequired.Data to write. Can be a string, an array or a data stream
modeOptional.How to open/write to the file.
contextOptional.Context of the file handle.

Possible values for mode:

  • FILE_USE_INCLUDE_PATH
  • FILE_APPEND
  • LOCK_EX

Return

This function returns the number of bytes that were written to the file, or FALSE on failure.

Note

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE.

Use the === operator for testing the return value of this function.

Example

file_put_contents() and fwrite() complement functions file_get_contents() and fread(), respectively.


<?PHP//from  w w  w  .  j  a  va 2s. com
      echo file_put_contents("test.txt","Hello World. Testing!");


      $myarray[] = "This is line one";
      $myarray[] = "This is line two";
      $myarray[] = "java2s.com";
      $mystring = implode("\n", $myarray);
      $filename = "test.txt";
      $numbytes = file_put_contents($filename, $mystring);
      print "$numbytes bytes written\n";
?>

The third parameter to file_put_contents() can be set to FILE_APPEND, If you do not use FILE_APPEND, the existing text will be replaced.

Use FILE_APPEND to avoid deleting the existing content of the file.

The code above generates the following result.





















Home »
  PHP Tutorial »
    Function reference »




PHP Array Functions
PHP Calendar Functions
PHP Class Functions
PHP Data Type Functions
PHP Date Functions
PHP File Functions
PHP Image Functions
PHP Math Functions
PHP MySQLi Functions
PHP SimpleXML Functions
PHP String Functions
PHP XML Functions
PHP Zip Functions