Writing an ImageUpload class in php

Updated: 12-Jan-2022 | Tags: PHP-OOP | Views: 794


Hello guys.
In this post we are going to upload an image and store the image's name in the database.

In our applications, we are going to use image upload actions very often. So the best thing to do, is to have a class which will handle all the upload process. We can transfer the class from one project to another and everything will work just fine. Plus we can add functions to expand the class anytime with ease.

So in this tutorial we are going to use the object oriented programming - OOP style, and write an imageUpload class to upload an image.
Lets start.

The ImageUpload class

First create a php file and name it image-upload-class.php. Inside the file we are going to open php tags and write the class declaration.

	class ImageUpload{


The class properties

Next i am going to create the properties that i am going to use throughout the class. All the properties except the error property are set to private. There is no need to be public.

In the first four we are storing the uploaded file's details such, the name, the type, the size, and the path to the temporary stored location.

class ImageUpload{
	// Class properties ============================
	private $image_name; // image name.
	private $image_type; // image type.
	private $image_size; // image size.
	private $image_temp; // the images temporary location.
	private $uploads_folder = "./uploads/"; // the uploads folder

	// setting the max upload file size to 2MB.
	private $upload_max_size = 2*1024*1024;
	// creating an array of allowed image types.
	private $allowed_image_types = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
	public $error; // I need a property to store any validation error.

	// Class methods =======================
  • In line 8 we setting the path to the folder where our uploaded images will be stored.
  • In line 11 the max allowed file size.
  • In line 13 we have an array with the image types that we allow to be uploaded.
  • And in line 14 we have the error property. This property has a public scope because i need to call the property from the html file.

The class __construct

Next i am going to write the classe's methods, and i am gonna start with the consructor.
In the constructor i am going to initialize all my properties.
The class constructor takes as an argument the $_FILES superglobal variable where all the images details are stored.

	// Class methods =======================
	public function __construct($image){
		$this->image_name = $image['image']['name'];
		$this->image_size = $image['image']['size'];
		$this->image_temp = $image['image']['tmp_name'];
		$this->image_type = $image['image']['type'];

		// These are all the methods we need in our class.
		$this->isImage(); // Checking if the uploaded file is actually an image.
		$this->imageNameValidation(); // Sanitizing the images name.
		$this->sizeValidation(); // Validating the file size.
		$this->checkFile(); // Checking if the file exists in uploads folder.

		// If there is no error.
		if($this->error == null){
			// moving the file from the temporary location to the uploads folder.
		// if there is no errors
		if($this->error == null){
			// Recording the images name in the database.

The class methods

The first method that we are going to write is the isImage(). With this method we are checking if the uploaded file is actually an image file. This is a good practice so we don't get in trouble if someone uploads a malicious file and change the file's extension to an image's mime/type such as .jpg, .gif etc.

private function isImage(){
	$finfo = finfo_open(FILEINFO_MIME_TYPE);
	$mime = finfo_file($finfo, $this->image_temp);
	if(!in_array($mime, $this->allowed_image_types) ){
		return $this->error = "This is not a valid image type";
  • In line 42 to 44 we creating a new instance of the finfo object, and pass in the FILEINFO_MIME_TYPE flag. This will allow us to check the uploaded file's mime/type.
    We pass in the finfo_file() function the (resource, and the location where the uploaded file is temporary stored). This method will return us the file's mime/type.
  • In line 45-47 we are checking the returned mime/type against our $allowed_image_types array.
    If the uploaded file's mime type is not included in the array we returning an error.

Next we sanitize the images name so we are sure that it is safe to store it in the database.

private function imageNameValidation(){
		return $this->image_name = filter_var($this->image_name, FILTER_SANITIZE_STRING);

With the next function we checking the file size. We don't allow files bigger than 2MB to be uploaded.

private function sizeValidation(){
		if($this->image_size > $this->upload_max_size){
			return $this->error = "File is bigger than 2MB";

Next we are checking if our image already exists in the folder. If file exists we return an error.

private function checkFile(){
			return $this->error = "File already exists in folder";

Next we are moving the file from the temp location to our "./uploads" folder. Also we are checking if the file was transferred successfully. If not, we returning an error message.

private function moveFile(){
		if(!move_uploaded_file($this->image_temp, $this->uploads_folder.$this->image_name)){
			return $this->error = "There was an error, please try again";

With our last method we are going to insert the image name in the database.

private function recordImage(){
		$mysqli = new mysqli('host', 'username', 'password', 'database');
		$mysqli->query("INSERT INTO images(image_name)VALUES('$this->image_name')");
		if($mysqli->affected_rows != 1){
			return $this->error = "There was an error, please try again";
  • In line 68 we are connecting to the mysql server and the database.
    You have to fill in your connection details.
  • In line 69 we are executing the insert query.
    I have here to say, that in my database i have an images table, and inside i have an image_name column.
    So here i am inserting the uploaded image_name in the image_name column.
  • In line 70 we are checking the affected_rows property. The expected value is 1. So if the affected rows is not one, i delete the file we just uploaded in the uploads folder in line 70 to 73.
  • And in line 74 we returning our error message.
    You see that we are not exactly saying to the user what the error is really about. We can not tell the users specific things about system errors, you never know how someone can use those informations to hurt our website.

The HTML code

First create a file named index.php.
At the top of the file before the !doctype declaration we have to place a few lines of php code.

		if($_FILES['image']['error'] == 0){
			$image_upload = new ImageUpload($_FILES);
<!DOCTYPE html>

<form action="" method="post" enctype="multipart/form-data">
	<h2><i class="far fa-file-image"></i> Choose an image to upload</h2>
	<input type="file" name="image" >
		Accepted image file types are <span>( .jpg .png .gif )</span>,
		and the file must be smaller than <span>2MB</span>.

	<input type="submit" name="upload-image" value="upload-image">
	<p class="error"><?php echo @$image_upload->error; ?></p>

Code breakdown

  • In line number 2 we are including with the require() function our imageUpload class, so we can have access.
  • In line 3 we are checking if the submit button in line 20 is pressed.
  • In line 4 we are checking if there was a file selected and uploaded without errors.
  • And in line 5 when there are no errors we creating a new object from our imageUpload class. And pass in the $_FILES superglobal variable. Now our class will handle the file.
  • From line 12 to 22 we have our html form. Now the important stuff here are the form's attributes. action=""... is empty, that means the form will be submitted to the same page. That's why we placed our php code in the top of the page.
  • method="post"... we are sending the data trough an HTTP POST REQUEST. That's why we checking in line 2 for a $_POST request.
  • enctype="multipart/form-data"... the enctype must be set to multipart/form-data else the upload process will not work. Always use multipart/form-data as an enctype value when uploading files.
  • In line 14 we have the choose file button. The name="image" attribute is used in our class to access the file's properties, (name, size, type, etc)
  • In line 20 we have our submit button, again here we use the name="upload-image" attribute to check the $_POST request in line 3.
  • And in line 21 we displaying any error that the class will return, with the public property $error. That's why we set the scope of this property to public.


We wrote a class which handles all the validation and upload process of an image file.
We saw how to get the files mime type with the finfo_file() function, so we are sure the uploaded file is an image.

We validated the images name so we can stored it safely in the database.
Also we validated the file's size, and throw an error if the file was bigger than 2MB.
And we moved the file from the temp location to our ./uploads folder.

I hope you liked the tutorial.
Thanks for reading.

Source code

You can download the php and html file and use it in any way you want.

Times downloaded: 135

View on Youtube

Buy me a coffee

If you like to say thanks, you can buy me a coffee.

Buy me a coffee with paypal

Comment section

You can leave a comment, it will help me a lot.

Or you can just say hi. 😉

Tutorial Categories