Cara menggunakan php file_put_contents temporary

Very often you will find you want to work with a file as if it were a "scratchpad" - a holding area where you can write out temporary data for later use. To make this as easy as possible, PHP has a function called tmpfile() which takes no parameters, but will create a temporary file on the system, fopen() it for you, and send back the file handle as its return value.

That file is then yours to read from and write to all you wish, and is deleted as soon as you fclose() the file handle or the script ends. Here is an example of tmpfile() in use:


As you can see, tmpfile() is a drop-in replacement for fopen()ing a known file, so it is easy to make use of.

If you want to know where these temp files are being saved, use the sys_get_temp_dir() function - it's new in PHP 5.2.1, but returns a string containing the directory used for creating temporary files.

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

The first argument is mandatory, and it is used to define the filename where the data will be written.

The second argument is mandatory and used to define the data written in the file.

The third argument is optional, which is used to define opening the file or writing the data. Any of the following values can be used in this argument.

FILE_USE_INCLUDE_PATH:
It is used the search the file in the include directory.

FILE_APPEND:
If the file exists, it is used to add the data at the end of the file.

LOCK_EX:
It is used to set the exclusive lock on the file when writing.

The fourth argument is optional and used to define the stream’s behavior or the context for handling the file.

The function returns the number of characters written into the file and returns False if no data is written into the file

file_put_contents() Function Examples

Different uses of the file_put_contents() function have been shown in the next part of this tutorial by using multiple examples. You have set the necessary read and write permissions to the folder where the file will be located before practicing the examples of this tutorial; otherwise, the permission denied error would occur. Run the following command to set all permission for the folder, ‘/var/www/html/php’.

$ sudo chmod -R 777 /var/www/html/php

Example-1: Write/Overwrite the Content into a File

Create a PHP file with the following script that will write a text in a text file located inside the folder, ‘/var/www/html/php’. If the temp.txt file exists before, then the file_put_contents() will overwrite the file’s content. If the temp.txt file does not exist, then the file_put_contents() function will create the file automatically before writing. Next, the file_get_contents() function is used in the script to check whether the text has been written properly in the file or not.

<?php

//Set the filename

$filename = "temp.txt";

//Set the string value

$str = "Adding content to the file.";

//Write content to the file

file_put_contents('/var/www/html/php/'.$filename, $str) or print_r(error_get_last());

//Check the file exists or not

if(file_exists($filename))

{

echo "The content of the file:<br/>";

//Print the content of the file

echo file_get_contents($filename);

}

?>

Output:

The following output would be appeared after executing the above script if the text was written properly in the file.

Cara menggunakan php file_put_contents temporary

Example-2: Append Data into an Existing Filename

Create a PHP file with the following script that will append a text with the new line in an existing text file located inside the folder, ‘/var/www/html/php’. The FILE_APPEND and LOCK_EX options are used in the third argument of the file_put_contents() function for appending the text to the temp.txt file. Next, the file_get_contents() function is used in the script to check whether the text has been written properly in the file or not.

<?php

//Set the filename

$filename = "temp.txt";

//Check the file exists or not

if(file_exists($filename))

{

echo "The content of the file before append:<br/>";

//Print the content of the file

echo file_get_contents($filename);

//Set the string value

$str = "Appending new content to the file.\n";

//Write content to the file

file_put_contents('/var/www/html/php/'.$filename, $str, FILE_APPEND | LOCK_EX) or print_r(error_get_last());

echo "<br/>The content of the file after append:<br/>";

//Print the content of the file

echo file_get_contents($filename);

}

?>

Output:

The following output would be appeared after executing the above script if the text was appended properly in the file.

Cara menggunakan php file_put_contents temporary

Example-3: Write/Overwrite the File Content Using FILE_USE_INCLUDE_PATH

You have to enable the include_path directive in the php.ini file for using the FILE_USE_INCLUDE_PATH option, the third argument of the file_put_contents() function. Open the php.ini file and remove the semicolon (;) from the front of the following line.

include_path = ".:/usr/share/php"

Run the following command from the terminal to restart the apache server after changing the php.ini file.

$ sudo service apache2 restart

Create a PHP file with the following script that will write/overwrite the text with the newline in an existing text file named myfile.txt that is located in the location defined in include_path directive. Next, the file_get_contents() function has been used in the script to check the text has been written properly in the file or not.

<?php

//Set the filename

$filename = "myfile.txt";

//Set the string value

$str = "Writing data into a file using file_put_contents().\n";

//Write content to the file

file_put_contents($filename, $str, FILE_USE_INCLUDE_PATH) or die("Unable to open the file.");

echo "The content of the file:<br/>";

//Print the content of the file

echo file_get_contents($filename, true);

?>

Output:

The following output would be appeared after executing the above script if the text was written properly in the file.

Cara menggunakan php file_put_contents temporary

Example-4: Write to a File by Creating a Directory

Create a PHP file with the following script that will write/overwrite the text with the new line in a text file named testing.txt located inside the directory named ‘temporary’ by using a user-defined function named WriteIntoFile(). This function will create the directory if the directory does not exist in the current location before writing into the file. Next, the file_get_contents() function is used in the script to check whether the text has been written properly in the file or not.

<?php

//Define to function to write into file by creating directory if not exists

function WriteIntoFile($dir, $file, $data){

//Create the directory if not exist

if(!is_dir($dir))

mkdir($dir);

//Write data into the file

file_put_contents("$dir/$file", $data);

}

//Initialize the necessary variables

$directory = 'temporary';

$filename = 'testing.txt';

$str = 'Testing file content.';

//Call the function to write into the file

WriteIntoFile($directory, $filename, $str);

//Check the file exists or not

if(file_exists("$directory/$filename"))

{

echo "The content of the file:<br/>";

//Print the content of the file

echo file_get_contents("$directory/$filename");

}

?>

Output:

The following output would be appeared after executing the above script if the text was written properly in the file.

Cara menggunakan php file_put_contents temporary

Conclusion

Different ways of writing content to a file by using the file_put_contents() function have been shown in the examples of this tutorial to help the PHP users to apply this function properly in their script.