Moving Uploaded Files to a Safe Location

      '/tmp/' . basename($_FILES['File']['name'])

When a user uploads a file to a PHP script using the <input type="file" /> HTML element, PHP stores the file in a temporary location (set in the php.ini directive upload_tmp_dir) and deletes it upon completion of script execution. Therefore, you have to access the uploaded file within the script. To do so, PHP contains the function move_uploaded_file(), which moves a file from one location to another. The great thing about move_uploaded_file() is that the function first does a sanity check, whether the filename you provide really is an uploaded file or if a malicious user just tried to trick you into moving /etc/passwd or C:\boot.ini somewhere else.

Moving an Uploaded File to a New Location

  if (isset($_POST['Submit']) &&  isset($_FILES
   ['File'])) {
    $move = move_uploaded_file(
      '/tmp/' . basename($_FILES['File']['name'])
    echo '<h1>';
    echo ($move) ? 'Moved' : 'Did not move';
    echo ' the file!</h1>';
  } else {
  <form action="<?php echo htmlspecialchars
    ($_SERVER['PHP_SELF']); ?>"
    method="post" enctype="multipart/form-data">
    <input type="file" name="File" />
    <input type="submit" name="Submit" value="Submit
       form" />

Suppose the path /tmp exists and is writable by the web server and the PHP process. Then, the preceding code moves the uploaded file to this directory, using its original filename (and you do not care whether the filename already exists).

What Does PEAR Offer?

The following PEAR packages offer functionality helpful for processing form data of any kind:

  • HTML_QuickForm is a very convenient package to create forms using an OOP (object-oriented programming) syntax and includes very mighty validation and processing features

  • HTTP_Upload helps to manage file uploads and offers advanced features such as providing valid extensions for uploads