Current Location: Home> Latest Articles> A Comprehensive Guide to PHP's tempnam() Function: Usage and Examples

A Comprehensive Guide to PHP's tempnam() Function: Usage and Examples

M66 2025-07-12

Overview

In PHP, the tempnam() function is used to create a temporary file with a unique file name. This function is ideal for scenarios where temporary files are required, such as caching files or temporary data storage.

Function Syntax

The syntax for the tempnam() function is as follows:

tempnam(dir, prefix)

Function Parameters

  • dir: Specifies the directory where the temporary file will be created.
  • prefix: The prefix to be used for the temporary file's name.

Return Value

The tempnam() function returns the generated temporary file name on success. If an error occurs, it returns FALSE.

Code Example

<?php

echo tempnam("C:\test\new","TMP");

?>

Output

C:\test\new\TMP1.tmp

Conclusion

By using the tempnam() function, PHP can create a temporary file with a unique file name. This function is particularly useful for managing temporary data files and helps avoid file name conflicts.