Blog de programación, errores, soluciones

Chose Language:
comments
Author: Admin/Publisher |finished | checked

Uploading files in PHP

In this section, we’ll cover the topic of uploading a file to your server via PHP, and what considerations you should keep in mind to achieve it.

Contents:

  1. Introduction
  2. Creating a form with enctype="multipart/form-data"
  3. Understanding the structure of the $_FILES variable
  4. Using the move_uploaded_file() function to save the uploaded file

Intro

If there’s something we’ll inevitably cover, it’s file uploads to our server or another source where we can use them. In this section, we’ll see how to accomplish this with PHP.

To start, let’s create a small form for uploading a file. Below is an example built with PureCSS for styling simplicity.

Form with enctype=”multipart/form-data”

formulario
<html>
  <head>
    <title>Upload file with php</title>
    <link rel="stylesheet" href="cdnjs.cloudflare.com/ajax/libs/pure/1.0.1/pure-min.css" type="text/css">
    <link rel="stylesheet" href="https://unpkg.com/purecss@1.0.1/build/forms-min.css" type="text/css">
  </head>
  <body>
    <h1>upload files with php</h1>
    <h2>This is a fileupload example</h2>
    <form class="pure-form pure-form-aligned" enctype="multipart/form-data" action="upload.php" method="post">
        <fieldset>
            <div class="pure-control-group">
                <label for="name">Filename</label>
                <input id="name" name="name" type="text" placeholder="ex: casa" required>
            </div>

            <div class="pure-control-group">
                <label for="file">File: </label>
                <input id="file" name="uploaded_file" type="file" placeholder="file" required>
            </div>


            <div class="pure-controls">
                <button type="submit" class="pure-button pure-button-primary">Submit</button>
            </div>
        </fieldset>
    </form>
  </body>
</html>

Keep in mind that the form included enctype="multipart/form-data". Without this attribute, $_FILES will not work and will return an empty array.

Content of $_FILE variable

The global variable $_FILES contains all the information about a file that is uploaded to the server. In the following explanations, the placeholder ‘x’ is used for simplicity, but it can be any name. In your case, you would use ‘file’ because of the form structure.

  • $_FILES['x']['name']: The original file name on the client machine.
  • $_FILES['x']['type']: The MIME type of the file (if provided by the browser).
  • $_FILES['x']['size']: The size of the file in bytes.
  • $_FILES['x']['tmp_name']: The temporary name given to the file on the server.
  • $_FILES['x']['error']: Contains an error code associated with the upload.

Here are the error codes:

  • UPLOAD_ERR_OK = 0: No error occurred; the upload was successful.
  • UPLOAD_ERR_INI_SIZE = 1: The uploaded file exceeds the upload_max_filesize directive in php.ini.
  • UPLOAD_ERR_FORM_SIZE = 2: The file exceeds the MAX_FILE_SIZE directive in the HTML form.
  • UPLOAD_ERR_PARTIAL = 3: The file was only partially uploaded.
  • UPLOAD_ERR_NO_FILE = 4: No file was uploaded.
  • UPLOAD_ERR_NO_TMP_DIR = 6: Missing a temporary folder (introduced in PHP 5.0.3).
  • UPLOAD_ERR_CANT_WRITE = 7: Failed to write the file to disk (introduced in PHP 5.1.0).
  • UPLOAD_ERR_EXTENSION = 8: A PHP extension stopped the file upload (introduced in PHP 5.2.0).

Next, we will need to check the file size and any errors before proceeding with the upload.

checkerrors function que ira en upload.php
private function checkerrors($error)
    {
        switch ($error) {
            case UPLOAD_ERR_OK:
                return array(true,"file was upload succesfully");
                break;
            case UPLOAD_ERR_INI_SIZE:
                return array(false,"an error occurs: size error");
                break;
            case UPLOAD_ERR_FORM_SIZE:
                return array(false,"an error occurs: do not size specified form values");
                break;
            case UPLOAD_ERR_PARTIAL:
                return array(false,"an error occurs: file is partialy uplaoded ");
                break;
            case UPLOAD_ERR_NO_FILE:
                return array(false,"an error occurs: file does not uploaded");
                break;
            case UPLOAD_ERR_NO_TMP_DIR:
                return array(false,"an error occurs: no tmp file directory ");
                break;
            case UPLOAD_ERR_CANT_WRITE:
                return array(false,"an error occurs: cant write check file permissons ");
                break;
            case UPLOAD_ERR_EXTENSION:
                return array(false,"an error occurs: PHP extension denied it");
                break;
        }
    }

If no error is returned by $error, the file will be temporarily uploaded to our server.

Using the move_uploaded_file function to save our file.

Syntax
move_uploaded_file ( string $filename , string $destination ) : bool

Where $filename is the name of the file to move (in our case, it’s $_FILES["uploaded_file"]['tmp_name']), which will be moved to the folder /var/www/html/upload_con_php/x/. Keep in mind that the $destination will also include the name of the file, so it would look like /var/www/html/upload_con_php/x/file.extension.

This is how my upload.php file would look.

update.php
<?php
error_reporting(E_ALL);
      ini_set("display_errors", 1);
      /*
      echo $_FILES["uploaded_file"]['name']."</br>";
      echo $_FILES["uploaded_file"]['type']."</br>";
      echo $_FILES["uploaded_file"]['size']."</br>" ;
      echo $_FILES["uploaded_file"]['tmp_name']."</br>";
      */
      $error = checkerrors($_FILES["uploaded_file"]['error']);
      //echo var_dump($_FILES);
      if($error[0]){
        $is_uploaded = move_uploaded_file($_FILES["uploaded_file"]['tmp_name'],"/var/www/html/upload_con_php/x/".basename($_FILES["uploaded_file"]['name']));
        if($is_uploaded):
            echo "el archivo fue subido con exito";
        else:
            echo "el archivo no a podido ser subido ";
        endif;
      }else{
          echo $error[1];
      }

      function checkerrors($error)
      {
          switch ($error) {
              case UPLOAD_ERR_OK:
                  return array(true,"file was upload succesfully");
                  break;
              case UPLOAD_ERR_INI_SIZE:
                  return array(false,"an error occurs: size error");
                  break;
              case UPLOAD_ERR_FORM_SIZE:
                  return array(false,"an error occurs: do not size specified form values");
                  break;
              case UPLOAD_ERR_PARTIAL:
                  return array(false,"an error occurs: file is partialy uplaoded ");
                  break;
              case UPLOAD_ERR_NO_FILE:
                  return array(false,"an error occurs: file does not uploaded");
                  break;
              case UPLOAD_ERR_NO_TMP_DIR:
                  return array(false,"an error occurs: no tmp file directory ");
                  break;
              case UPLOAD_ERR_CANT_WRITE:
                  return array(false,"an error occurs: cant write check file permissons ");
                  break;
              case UPLOAD_ERR_EXTENSION:
                  return array(false,"an error occurs: PHP extension denied it");
                  break;
          }
      }
?>

Finally, keep in mind that we use the basename function, which will return only the last component of the path we pass to it.

You can check what does basename in PHP basename function post

Take in consideration that move_uploaded_file function is not the only function that can save the file, you can save the file with other bunch of functions, but these one is the one that most feet with what we are doing, we have a temporary file and then move to where we want.

We will see an others functions to create file with PHP, in creating files with PHP

If you want to download the example to your computer, you can download it through GitHub at the following link. 👇

Descargar repo en github
Category: en-php
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category

Comments