PHP Files Creating a Temporary File - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Files Creating a Temporary File - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Tuesday, July 9, 2019

PHP Files Creating a Temporary File

PHP Files


Creating a Temporary File

Problem

You need a file to temporarily hold some data.

Solution

If the file needs to last only the duration of the running script, use tmpfile():

       $temp_fh = tmpfile();
       // write some data to the temp file
       fputs($temp_fh,"The current time is ".strftime('%c'));
       // the file goes away when the script ends
       exit(1);

If the file needs to last longer, generate a filename with tempnam(), and then use fopen():

       $tempfilename = tempnam('/tmp', 'data-');
       $temp_fh = fopen($tempfilename, 'w') or die($php_errormsg);
       fputs($temp_fh, "The current time is ".strftime('%c'));
       fclose($temp_fh)                                         or die($php_errormsg);

Discussion

The tmpfile() function creates a file with a unique name and returns a filehandle. The file is removed when fclose() is called on that filehandle, or the script ends.

Alternatively, tempnam() generates a filename. It takes two arguments: the first is a directory, and the second is a prefix for the filename. If the directory doesn’t exist or isn’t writable, tempnam() uses the system temporary directory—the TMPDIR environment variable in Unix or the TMP environment variable in Windows. This example shows what tempnam() generates:

       $tempfilename = tempnam('/tmp','data-');
       print "Temporary data will be stored in $tempfilename";

This prints:

       Temporary data will be stored in /tmp/data-GawVoL

Because of the way PHP generates temporary filenames, a file with the filename that tempnam() returns is actually created but left empty, even if your script never explicitly opens the file. This ensures another program won’t create a file with the same name between the time that you call tempnam() and the time you call fopen() with the file name.

No comments:

Post a Comment

Post Top Ad