Приглашаем посетить
Отели (hotels.otpusk-info.ru)

Moving Uploaded Files to a Safe Location

Previous
Table of Contents
Next

Moving Uploaded Files to a Safe Location

move_uploaded_file(
      $_FILES['File']['tmp_name'],
      '/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 (upload-move.php; excerpt)
<?php
  if (isset($_POST['Submit']) &&  isset($_FILES
   ['File'])) {
    $move = move_uploaded_file(
      $_FILES['File']['tmp_name'],
      '/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" />
  </form>
<?php
  }
?>

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



Previous
Table of Contents
Next