PHP file_put_contents() Function

The file_put_contents() writes a string to a file.

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

This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file. If filename does not exist, the file is created. Otherwise, the existing file is overwritten, unless the FILE_APPEND flag is set.

This function follows these rules when accessing a file:

  • If FILE_USE_INCLUDE_PATH is set, check the include path for a copy of *filename*
  • Create the file if it does not exist
  • Open the file
  • Lock the file if LOCK_EX is set
  • If FILE_APPEND is set, move to the end of the file. Otherwise, clear the file content
  • Write the data into the file
  • Close the file and release any locks
  • This function returns the number of character written into the file on success, or FALSE on failure.

    Example -

    ParameterDescription
    fileRequired. Specifies the file to write to. If the file does not exist, this function will create one
    dataRequired. The data to write to the file. Can be a string, an array or a data stream
    modeOptional. Specifies how to open/write to the file. Possible values:
    FILE_USE_INCLUDE_PATH
    FILE_APPEND
    LOCK_EX
    contextOptional. Specifies the context of the file handle. Context is a set of options that can modify the behavior of a stream.

    Note -

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