PHP File put contents

The PHP file_put_contents() function is the most suitable option for writing a string to a file or appending the contents of a string at one time.


The file_put_contents() function is used to write a string to the file, successfully returning the number of bytes written to the file, or FALSE if it fails.


int file_put_contents(string filename, string data[, int flags[, resource context]])
Parameter Description:
Parameters Description
filename The file name to write to the data
data The data to be written. Type can be string, array(but not for multi-dimensional array), or stream resources
flags Optional, specifies how to open /write files. Possible values:
  1. FILE_USE_INCLUDE_PATH: Check the built-in path to the filename copy
  2. FILE_APPEND: Write data at the end of the file in append mode
  3. LOCK_EX: lock on file
context Optional, Context is a set of options, it can modify the text attributes


echo file_put_contents("test.txt"," This is something. ");

Run the example, the browser output:


The test.txt file(with the program with the directory) the content was: This is something ..


  • if the file does not exist, create the file, which is equivalent to the fopen() function behavior.
  • if the file exists, the contents of the file are cleared by default. You can set the flags parameter to FILE_APPEND to avoid it(see below).
  • This function is safe for binary objects.

Write content in append form

When the value of the flags parameter is set to FILE_APPEND, new data is written in such a way that the contents of the existing file are appended with the contents:

File_put_contents("test.txt"," This is another something.", FILE_APPEND);

After executing the program, the contents of the test.txt file becomes: This is something.This is another something.

The behavior of file_put_contents() is actually equivalent to calling fopen(), fwrite() and fclose().

Copyright 2014-2017 by All Rights Reserved.