Basics of File Uploading

Uploading files empowers web users to contribute content effortlessly

One of the most misunderstood topics in PHP for beginners. How does someone upload a file? What happens when you click upload? Where does it go? Let’s demystify this process and tackle files in PHP. It’s simpler than you think.

Configuration

If you’re using the docker container that was provided with the code samples, there’s one thing that you’ll need to do first and that’s to change permissions. What we’re going to do here is not recommended on your production server, but it does give us a quick and easy way to allow for files to be uploaded.

https://github.com/dinocajic/php-youtube-tutorials

Run your docker command as you normally would to spin up the docker containers.

docker run -i -t -p "80:80" -v ${PWD}/app:/app -v ${PWD}/mysql:/var/lib/mysql mattrayner/lamp:latest

Open Docker Dashboard and click on the docker container that you just spun up.

Click on the CLI button to open up the terminal.

Navigate to the var/www folder: cd var/www

Execute the chmod function: chmod -R 777 html

You’ll now be able to upload files to that directory.

The HTML Form

Time to create our form. This is the form that the user will interact with. You’ve seen the file-chooser-button appear that allows for the user to select a file and then click on the Upload button to process the upload.

<form action="./upload.php" method="post" enctype="multipart/form-data">
  <div>
    Select file to upload:
  </div>

  <div>
    <input type="file" name="file_name" id="file_name">
  </div>

  <div>
    <input type="submit" name="submit" value="Upload">
  </div>
</form>

There are a couple of things to dissect in the form itself.

  • There is a new type of input type and that’s file. Who could have guessed that. This is what gives us the button that when clicked allows us to browse for files on our computer.

  • The method is still set to post and we’re going to create an upload.php file to process our file upload.
  • The other addition is the enctype=”multipart/form-data”. This tells PHP that we’re going to be uploading files. If you omit the enctype the file upload will not work.

Pretty straightforward so far. Let’s create our upload.php file next that’s going to allow for the file to be uploaded.

Processing File Upload

If you remember from our previous article, we mentioned the $_FILES predefined variable. Let’s see what it contains when we click submit by dumping its content in our uploads.php file.

var_dump($_FILES);
array (size=1)
  'file_name' => 
    array (size=5)
      'name' => string '75-Get-vs-Post.jpg' (length=18)
      'type' => string 'image/jpeg' (length=10)
      'tmp_name' => string '/tmp/phpFMpvdR' (length=14)
      'error' => int 0
      'size' => int 133821

After clicking submit, we see that $_FILES is just an array of data. It used our input name="file_name" to create a key called file_name. That key gets an array of data: name, type, tmp_name, error, size. So if you echo $_FILES['file_name']['name'] you’ll get 75-Get-vs-Post.jpg.

  • The name gives you the original name of the file that you just uploaded.
  • The type gives you the file type. In this case, I uploaded an image so it knew that this was an image and stored its type.
  • The tmp_name is where people get lost. Where does my file go? Well, in this case, it goes into the /tmp directory. It also gets a random temporary name of phpFMpvdR. This is important since we’re going to have to move this file into an accessible directory later on.
  • error will return a boolean value: 0 if there are no errors and 1 if there’s an error.
  • size gives you the size of the image. This is the size in bytes.

We have all the data that we need now to upload a file. We can honestly do this with one line of code, but for readability we’ll split it into 3 lines of code.

<?php

$target_file = $_FILES["file_name"]["name"];
$temp_file   = $_FILES["file_name"]["tmp_name"];

move_uploaded_file($temp_file, $target_file);

We have a temporary file location. We need to move that to our current directory and we want it to have the exact same name as our original file name. We use the move_uploaded_file function to move the files from the temp location to our current directory. Go to your directory and you’ll see it there.

What if we wanted to move it to a subdirectory like uploads/. We just need to create the directory and append it to our target_file name.

<?php

$target_file = "uploads/" . $_FILES["file_name"]["name"];
$temp_file   = $_FILES["file_name"]["tmp_name"];

move_uploaded_file($temp_file, $target_file);

And success. Our files now get uploaded to our uploads subdirectory.

var/
   www/
      html/
         76-file-uploads/
            index.html
            upload.php
            uploads/
                some-image.jpg

Summary

That’s it when it comes to uploading files. Everything else is just error handling and validation. For example, what happens when the file size is just too large? How do you restrict users to only upload PDF’s? We’ll take a look at more advanced form processing next. You should never leave your file processing this exposed.

Predefined Variables

ACCESS SERVER INSIGHTS WITH PHP’S BUILT-IN PREDEFINED VARIABLES

PHP – P76: PREDEFINED VARIABLES

PHP automatically has access to form submission variables since they’re added to the $_POST variable. Let’s dive into the most common variables like $_SERVER, $_GET, and $_POST.

Basics of File Uploading

Uploading files empowers web users to contribute content effortlessly

PHP – P77: basics of file uploading

One of the most misunderstood topics in PHP for beginners. How does someone upload a file? What happens when you click upload? Where does it go? Let’s demystify this process and tackle files in PHP. It’s simpler than you think.

check file type

FILE TYPE VALIDATION IN PHP SAFEGUARDS AGAINST MALICIOUS UPLOADS

PHP – P78: CHECK FILE TYPE

Never trust the user. Even though you specified that the user should upload an image, will they follow your instructions? Majority of the users will but there are some that wont for various reasons.

Leave a Reply