Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

file_put_contents()

Example

Write data to a file.

<?php
echo file_put_contents(“test.txt”,“Hello World. Testing!”);
?>

The result of the code above will be:

21

Definition and Usage

The file_put_contents() function writes data to a file and operates as follows:

If FILE_USE_INCLUDE_PATH is set, it searches for the file in the include path.

  • It creates the file if it does not exist.
  • It opens the file.
  • If LOCK_EX is set, it locks the file.
  • If FILE_APPEND is set, it appends data to the end of the file; otherwise, it clears the file content.
  • It writes the data to the file.
  • It closes the file and releases any locks.

Note: Use FILE_APPEND to prevent deleting existing content in the file.

Syntax

file_put_contents(filenamedatamodecontext)

Parameter Values

 

Parameter

Description

filename

Mandatory. Specifies the path to the file to write to. If the file does not exist, it will be created.

data

Mandatory. The data to write to the file, which can be a string, array, or data stream.

mode

Optional. Specifies how to open or write to the file. Possible values include:

  • FILE_USE_INCLUDE_PATH – Search for the filename in the include directory.
  • FILE_APPEND – Append data to the file if it already exists, instead of overwriting it.
  • LOCK_EX – Apply an exclusive lock to the file while writing.

context

Optional. Specifies the context for the file handle, which is a set of options that can alter the behavior of the stream.

Technical Details

Return Value:

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

PHP Version:

5.0+

Binary Safe:

Yes

PHP Changelog:

In PHP 5.1, support was added for LOCK_EX and the ability to pass a stream resource to the data parameter.