File Upload In PHP
Using Core PHP To Work Better With Files
Hello there, welcome to this article where I try to teach how to enable file upload in PHP, using no frameworks or packages, or any special libraries, just PHP.
In this article, I will teach how to build an online gallery where images can be uploaded and viewed easily.
So here’s a summary of what you’ll learn.
- How to write your HTML code to allow file uploads and set the maximum file size too, if you ever need to.
- How to use the $_FILES superglobal to access files and important information about them.
- What type of files can be uploaded.
- How to store files on the server and on the database.
Sounds fun, doesn't it? Let’s dive in. 🚀🚀
What Do You Need To Know To Continue
Knowledge of these things would really help
- HTML and CSS.
- Basic PHP: Functions, Includes, Arrays (you can learn about arrays here).
- Some MySQL: To reach out to the database.
If you’ve checked all these listed above, you’re good to go.
File Upload
Most web applications in the current day go beyond dealing with just text and numbers, there’s always this need to have files, maybe images (profile pictures or cover images) or audio files (voice notes or songs) or maybe even videos. As a web developer, being able to build such applications only puts you on par with other developers, if not better.
Writing The HTML Code
The first step in building the web application is to have a client-facing code, from where the file will be uploaded.
Now to actually understand what’s happening in the code above.
The “enctype” attribute
The HTML form has an attribute that specifies how the data being sent should be encoded. Possible values are:
- application/x-www-form-urlencoded: This is the form’s default encoding. All characters are encoded before being sent (spaces are converted to “+” symbols, and special characters are converted to ASCII HEX values).
- multipart/form-data: This is the method we’ll be using. No characters are encoded. This value is required when you are trying to send files in the form.
- text/plain: Spaces are converted to “+” symbols, but no special characters are encoded.
Having seen this, we can create our form as thus, since we intend to upload files (image files here):
Now, we can add proceed to add other form input fields.
MAX_FILE_SIZE
There are times you want to limit the files to a particular size, very often though, there’s a form attribute for that. MAX_FILE_SIZE lets you set an expected maximum size for the incoming files. To do this, we create a hidden input field with the name MAX_FILE_SIZE and value as our expected maximum file size in bytes.
To set a maximum file size of 32kb, the code would be written as:
The number 32768 was gotten by converting 32kb to bytes.
1kb is equal to 1024bytes
Having completed work on most of the client-side code for the file upload, let’s take a look at how the application will work on the server-side.
$_FILES
Files sent through HTML forms can be gotten through the $_FILES superglobal. The $_FILES superglobal, like the $_POST superglobal, is inbuilt and is an array. It not only stores the name of the uploaded file or files but it also stores more important details about these files, like the file type, size.
Using the $_FILES variable, you can access an uploaded file the same way you would access an input field, using the name.
So to get an image file with the name picture.
Getting specific details about the file means going a step further into the array.
Upload Types
The $_FILES superglobal allows for the upload of files of different types. Knowing these can help you tailor your application to accept or reject a specific type.
The most common types are:
- image\gif
- image\jpeg
- plain\text
- plain\html
Handling The Submitted Form
Remember that our form action pointed to upload.php, let’s get to work on handling the form data already.
The first thing to do to the form, like every other form is to confirm that it was actually submitted. This is usually done by checking the $_POST superglobal for the presence of one of the submitted fields, in most cases the submit button (as it is always on forms). We also use the submit button here.
Having confirmed that the form was submitted, we can go on to get the form fields (the image display name and the actual image) and store them in our variables.
We could have some more validation just to be a bit safer. So we check if the $name is not empty before proceeding.
Now we can feel a bit safer, we’ve confirmed that the form was submitted and that the name isn’t empty. We can move to store the image now.
Storing The Image
This involves two steps:
- The image name has to be stored in the database (for reference later on), and
- The image has to be stored also, in our folder on the server (not on the temporary folder the server puts it).
Storing the name in the database can be said to be easy as we already learned how to access the file name using the $_FILES superglobal. All we have to do is to write our SQL query to insert the image and the name in the database.
It is assumed you’ve connected to your SQL database just before this.
The image name is stored with the user inputted display name in the database.
We could proceed to make the image name unique so we don’t delete the wrong image whenever we need to(if we ever need to).
Here we’re making the image name very dynamic by concatenating the result of the time() function to it. Knowing that the time() function returns the current time in the number of seconds since the Unix Epoch (January 1, 1970, 00:00:00 GMT). We’re very sure no two image names will ever be the same.
Now we’ve got the name and stored it in our database, what happens to the image? The server temporarily stores them in an auto-generated folder, tmp_name, but we need to store it in our own folder, where we want it so we may use it.
The server automatically stores the file in a temporary folder, usually like this /tmp/php/php1h4j1o. And we do not always have access to this folder depending on what type of server we use. So it’s very safe to move the image to our own folder, where we always have access to it.
move_uploaded_file()
The image (or whatever file is uploaded) is usually stored in a temporary folder on the server (which we might not always have access to). So we have to move it into our own directory, so we may use it later in our application.
move_uploaded_file() helps with the movement. It takes in two parameters, the file name (as it is on the temporary directory) and the destination (our target folder).
To use this function, the destination folder must already exist (or an error is thrown). So we can create an images folder in our root directory, where the images will be stored.
Notice how the $target variable was formed, we set the images folder first, then saved the image the way it was saved in the database (time + real name) so we may always access it with ease.
We should run our SQL query to complete the image storage.
And it’s that easy to upload files in PHP, with no framework or package or additional library, just PHP.
To complete the application, we make a page where all uploaded images can be seen. And that’s it. 😇
Summary
At this point, you must have learned a lot about file upload using PHP and can now go on to building more advanced web applications with ease. All of the codes for the application can be found here.