tmpfile() in PHP
By: Andi, Stig and Derick
In case you want to create a temporary file, the best way to do it is with the tmpfile() function. This function creates a temporary file with a unique random name in the current directory and opens this file for writing. This temporary file will be closed automatically when you close the file with fclose() or when the script ends:
<?php
$fp = tmpfile();
fwrite($fp, 'temporary data');
fclose(fp);
?>
In case you want to have more control over where the temporary file is created and about its name, you can use the tempnam() function. On the contrary to the tmpfile() function, this file will not be removed automatically:
<?php
$filename = tempnam('/tmp', 'p5pp');
$fp = fopen($filename, 'w');
fwrite($fp, 'temporary data');
fclose(fp);
unlink($filename);
?>
The first parameter to the function specifies the directory where the temporary file is created, and the second parameter is the prefix that will be added to the random file name.
Archived Comments
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
PHP convert string to lower case
PHP code to write to a CSV file for Microsoft Applications
PHP code to write to a CSV file from MySQL query
PHP code to import from CSV file to MySQL
Password must include both numeric and alphabetic characters - Magento
Error: Length parameter must be greater than 0
PHP file upload prompts authentication for anonymous users
PHP file upload with IIS on windows XP/2000 etc
Multiple File Upload in PHP using IFRAME
Resume or Pause File Uploads in PHP
Exception in module wampmanager.exe at 000F15A0 in Windows 8