Articles

The month of PHP functions : temporary

  • Ecrit par Julien Pauli
  • lundi 16 avril 2007
Image pour le titre du contenu

Ce document est aussi disponible en français fr 


 tmpfile()  and  its sister function  tempnam() provide tools to create temporary files, without thinking about it name. tmpfile() will create a temporary file in your system (not in the /tmp/directory), and will give you a file resource for it. This file will be destroyed at the end of the script, or when the file is closed. This way, tmpfile() is useful to use disk as cache when convertir a file to some other format.

 

Example 1 - Sending text via FTP and a file : 

tempnam() is more useful when one has to keep the temporary file a little longer than the script. Instead of using  file_put_contents() then give a temporary file name,  tempnam() will generate such a name.

<?php
    $file = tmpfile();
    fwrite($file,$_POST['mon_champ_texte']);
    fseek($file,0);
    ftp_fput($ftpConnexion,"my_dir/myFtpFile.ext",$file,FTP_ASCII);
    fclose($file); // d&eacute;truit le fichier temporaire
?>

Example 2 - File upload  and moving to a temporary folder :

<?php
function upload_to_tempfile($uploadedFileName)    {
        if (is_uploaded_file($uploadedFileName))    {
            $tempFile = tempnam('my_upload_dir','upload_temp_'); 
// only 'upl' will be used as file name
            move_uploaded_file($uploadedFileName, $tempFile);
            return is_file($tempFile);
        }
    }
?>

Example 3 - Sending and processing a file in a relative folder :

<?php
$tmpfile = tempnam(realpath("../tmp/"), "tmp") ;
$fp = fopen($tmpfile, "w");
fwrite($fp, 'des donn&eacute;es');
fclose($fp);
?>

Example 4 - Reading temporary folder of the system :

<?php
// Equivalent to $_ENV['TMP'];
echo dirname(tempnam(''''));
?>

Keep in mind

  • tmpfile() will create a temporary file in the system. This file is automatically destroyed at the end of the script, unless the script is killed.
  • tempname() returns a full path with the temporary file, which is handy when used with other functions such as  fopen().
  • tempname()  accepts only absolute path. Use realpath() when nécessary. If the specified folder doesn't exists, the default temporary folder will be used, without a warning.
  • tempname() will only use the three first characters of the filename in the second argument.
< Précédent   Suivant >

Commentaires

Vous pouvez ajouter votre commentaire!


Vous devez vous connecter pour commenter