Guides

Uploading files via HTTP using PHP

Uploading a file to the server via HTTP in PHP is extremely simple: a typical example can be found in the code below, which runs on both Linux and Windows.

ATTENTION

  • Linux plans. In order to work properly, upload scripts need the permissions of the upload destination folder to be set with chmod 777. ou can do this configuration using an FTP client.
  • Windows plans. In order to work properly, upload scripts require that the destination folder of the upload has write permissions. This can be configured in the control panel under older and file permissions

upload.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<HTML>
<head>
<title> PHP upload test page </title>
</head>
<body>
<?php
error_reporting(2047);
if (isset($_POST["invio"])) {
  $percorso = "uploadtest/";
  if (is_uploaded_file($_FILES['file1']['tmp_name'])) {
    if (move_uploaded_file($_FILES['file1']['tmp_name'], $percorso.$_FILES['file1']['name'])) {
      echo 'Nome file: <b>'.$_FILES['file1']['name'].'</b><br>';
      echo 'MIME Type: <b>'.$_FILES['file1']['type'].'</b><br>';
      echo 'Dimensione: <b>'.$_FILES['file1']['size'].'</b> byte<br>';
      echo '======================<br>';
      echo 'File caricato correttamente<br><br>';
      echo '<a href="upload.php">carica un altro file</a>';
    } else {
      echo "si è verificato un errore durante l'upload: ".$_FILES["file1"]["error"];
    }
  } else {
    echo "si è verificato un errore durante l'upload: ".$_FILES["file1"]["error"];
  }
} else {
  // HTML ?>
    <form enctype="multipart/form-data" method="post" action="" name="uploadform">
      seleziona il file da caricare sul server: 
      <br>
      <input type="file" name="file1" size="50">
      <br>
      <input type="submit" value="invia" name="invio">
    </form>
  <?php
}
?>
</body>
</html>

Once the form has been posted, the data is uploaded by the PHP user agent into a temporary folder. Using the move_uploaded_file command, you can move the file from the temporary folder to another folder.

In this example, it is assumed that the files are uploaded to an uploadtest folder at the same level as the script. This folder must of course have the correct permissions for the upload to be successful, as indicated above.

The global predefined variable $_FILES is an associative array that contains, for each file type field of a form, the main characteristics of the file itself:

  • $_FILES[ file1']['tmp_name']: contains the name assigned by the PHP user agent to the file uploaded into the temporary folder.
  • $_FILES['file1']['name']: contains the name of the file as it was in the client from which it was taken
  • $_FILES['file1']['type']: contains the MIME type of the file
  • $_FILES['file1']['size']: contains the size of the file in bytes
  • _FILES['file1']['error']: contains the numeric error code that may have occurred during the upload.