Home  >  Article  >  Backend Development  >  How to use php file_put_contents function?

How to use php file_put_contents function?

青灯夜游
青灯夜游Original
2019-05-25 10:42:043731browse

file_put_contents() is a built-in function in PHP used to write strings to files. The path to the file the user wants to write and the data that must be written are passed to the function as parameters, and the number of bytes written to the file is returned on success, or FALSE on failure.

How to use php file_put_contents function?

php How to use the file_put_contents() function?

php file_put_contents() function is used to write a string into a file. This function checks the file the user wants to write to, and if the file does not exist, creates a new file and then writes the string.

Basic syntax:

file_put_contents(file,data,mode,context)

Parameters: The PHP file_put_contents() function accepts two required parameters and two optional parameters.

● File: required. Specify the file to which data is to be written. If the file does not exist, a new file is created.

● data: optional. Specifies the data to be written to the file. Can be a string, array, or data stream.

● Mode: optional. Specify how to open/write the file. Possible values: FILE_USE_INCLUDE_PATH, FILE_APPEND, LOCK_EX.

● context: optional. Specifies the environment for a file handle, customizing the behavior of the context or stream. context is a set of options that can modify the behavior of the stream. If null is used, it is ignored.

Return value: When the writing is successful, the number of bytes written to the file is returned. If it fails, FALSE is returned.

Errors and Exceptions:

● The file_put_contents() function returns the Boolean value FALSE, but may also return a non-Boolean value that evaluates to FALSE.

● If the provided directory is invalid, this function cannot write the content.

Let’s take a look at how to use the php file_put_contents() function through an example.

Example:

<?php
echo file_put_contents("./test.txt","Hello php. I&#39;m study in php.cn!");
?>

Output:

31

The above is the detailed content of How to use php file_put_contents function?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn