Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP file_put_contents() Function

PHP file_put_contents() Function


PHP Filesystem Reference Manual Complete PHP Filesystem Reference Manual


Definition and Usage

The file_put_contents() function writes a string to a file.

When accessing a file, this function follows these rules:

  1. If FILE_USE_INCLUDE_PATH is set, check the filename built-in path of the copy
  2. If the file does not exist, create a file
  3. Opening a File
  4. If LOCK_EX is set, lock the file
  5. If FILE_APPEND is set, move to the end of the file. Otherwise, the file contents are cleared
  6. Write the data to the file
  7. Close the file and unlock all files

Returns the number of characters written to the file on success, or FALSE on failure.

Syntax

int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] )

Parameters Description
filename Required. Specifies the file to write data to. If the file does not exist, a new file is created.
data Required. Specifies the data to write to the file. Can be a string, an array, or a stream.
flags Optional. Specifies how to open/write the file. Possible values:
  • FILE_USE_INCLUDE_PATH
  • FILE_APPEND
  • LOCK_EX
  • | | context | Optional. Specifies the context of the file handle. A context is a set of options that can modify the behavior of a stream. |

    Tips and Notes

    **Note:** Use FILE_APPEND to avoid deleting the existing contents of the file.


    Example

    Example

    The output of the above example is:

    6
    
    

    Next, we append content to the file sites.txt:

    Example

    After successful execution, open sites.txt; its content is:

    Runoob
    
    Google
    
    

    PHP Filesystem Reference Manual Complete PHP Filesystem Reference Manual