w3resource

PHP Exercises : Get the directory path used for temporary file


28. Get Temporary File Directory

Write a PHP script to get the directory path used for temporary files.

Sample Solution:

PHP Code:

<?php
// Generate a temporary file with a unique filename
// The tempnam() function creates a temporary file with a unique name in the system's temporary directory
$temp_file = tempnam(sys_get_temp_dir(), 'Tux');
// Output the path of the created temporary file
echo $temp_file."\n";
?>

Explanation:

  • Generate a Temporary File:
    • The tempnam() function is used to create a temporary file. It takes two arguments:
      • sys_get_temp_dir(): This function returns the path of the system's temporary directory.
      • 'Tux': This string is used as a prefix for the unique filename.
  • Store Temporary File Path:
    • The path of the created temporary file is stored in the variable $temp_file.
  • Output Temporary File Path:
    • The echo statement outputs the path of the created temporary file, followed by a newline (\n).

Output:

/tmp/TuxN0kaAE 

Flowchart:

Flowchart: Get the directory path used for temporary file

For more Practice: Solve these Related Problems:

  • Write a PHP script to retrieve and display the system’s temporary file directory along with its free space.
  • Write a PHP script to verify that the temporary directory is writable and output a status message accordingly.
  • Write a PHP script to list all files in the temporary directory that match a specific file extension.
  • Write a PHP script to validate and then update the temporary directory path based on server configuration changes.


Go to:


PREV : Print PHP Credits.
NEXT : List Module Functions.

PHP Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.