How to create a temporary file in PHP?

By IncludeHelp Last updated : January 10, 2024

A temporary file is a file that has a unique name and is deleted automatically when it is closed.

Problem statement

Write a PHP program to create a temporary file.

Creating a temporary file

To create a temporary file having a unique name in read-write-binary (w+b) mode, use the tmpfile() method. This method does not accept the file name (i.e., you don't need to provide a file name) and returns a file handle if the file is created; false, otherwise.

Syntax

The syntax of the tmpfile() method is:

tmpfile();

Example

$file = tmpfile();

PHP program to create a temporary file

In this program, we create a temporary file, write some content, read and print the content, and close it.

<?php
// Creating a temporary file
$file = tmpfile();

// Writing content
fwrite($file, "Hello, world!");

// Seeking file pointer to start position
fseek($file, 0);

// Reading content
$content = fread($file, 1024);

// Printing the content
echo("File's content is: ".$content);

// Closing the file 
// which will remove the file also
fclose($file);
?>

Output

The output of the above program is:

File's content is: Hello, world!

To understand the above program, you should have the basic knowledge of the following PHP topics:

Writing content to a temporary file

To write content in a temporary file, use the fwrite() function by passing the file handle and content to write as the parameters.

fwrite($file, "Hello, world!");

Writing content to a temporary file

To read content from a temporary file, first set the file pointer at the start of the file using the fseek() function and then use the fread() function by passing the file handle and maximum size to read as the parameters.

fseek($file, 0);
$content = fread($file, 1024);

Closing (deleting) temporary file

Use the fclose() function to close and delete the temporary file.

fclose($file);

More PHP File Handling Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.