How to write an image upload and validation class
Updated: 21-Dec-2023 / Tags: PHP-OOP / Views: 1039 - Author: George
Introduction
As programmers 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 and validation 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 in PHP to upload and validate an image.
Lets start.
The config file
Before we jump right in and write our imageUpload class, we are going to define some constants in a config.php file, that will hold our database credentials
<?php
// Fill in your server's name.
define('SERVER', 'localhost');
// Fill in your database username.
define('USERNAME', 'mysql-username');
// Fill in your database password if any.
define('PASSWORD', 'mysql-password');
// Fill in your database.
define('DATABASE', 'your-database-name');
The imageUpload class
Let's create a file named image-upload-class.php, and write the imageUpload class.
We will require the config.php file so we have access to our database log-in details.
Then i am going to create the properties that i am going to use throughout the class. All the properties except the $error, and $success property are set to private. There is no need to be public.
require "config.php";
class ImageUpload{
// Class properties ============================
// image name.
private $image_name;
// image type.
private $image_type;
// image size.
private $image_size;
// the image's temporary location.
private $image_temp;
// The folder in which we will store the uploaded images.
private $uploads_folder = "./uploads/";
// 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'];
// I need a property to store any validation error.
public $error;
/*
The success property will display the success
message if everything goes well.
*/
public $success;
The class __construct
Next i am going to write the class methods, and i am gonna start with the constructor. The constructor is going to initialize all my properties and execute all the methods in the class.
The class constructor takes as an argument the $_FILES superglobal variable where all the image details are stored. Ex. $upload = new imageUpload($_FILES).
// Class methods =======================
public function __construct($image){
// Setting the uploaded image name to the
// $image_name property.
$this->image_name = $files['image']['name'];
// Setting the uploaded image size to the
// $image_size property.
$this->image_size = $files['image']['size'];
// Setting the temporary location to the
// $image_temp property.
$this->image_temp = $files['image']['tmp_name'];
// Setting the uploaded image type to the
// $image_type property.
$this->image_type = $files['image']['type'];
/*
The isEmpty method will check if there
is a file selected.
*/
$this->isEmpty();
/*
If there is a file selected we are going to
run the isImage method.
The isImage method will check if the selected
file is indeed an image.
*/
if($this->error == null){
$this->isImage();
}
/*
Next we are going to check the file's
file type. Only .jpg, .png, and .gif files
are allowed.
*/
if($this->error == null){
$this->checkFileType();
}
/*
Next we are going to rename the image name.
*/
if($this->error == null){
$this->imageRename();
}
/*
The sizeValidation method will check the
image's file size. Max allowed file size is up
to 2MB.
*/
if($this->error == null){
$this->sizeValidation();
}
/*
The moveFile() method will store the uploaded
image in the 'uploads/' folder.
*/
if($this->error == null){
$this->moveFile();
}
/*
The recordImage() method will insert the
image name in the database.
*/
if($this->error == null){
$this->recordImage();
}
/*
If everything goes well we display the
success message.
*/
if($this->error == null){
$this->success = "Image uploaded successfully";
}
}
The isEmpty method
private function isEmpty(){
if(empty($this->image_name)){
return $this->error = "Please select an image file";
}
}
The isEmpty method will return an error if we press the submit button without selecting a file.
The isImage method
private function isImage(){
if(getimagesize($this->image_temp) == false){
return $this->error = "Please select a valid image file";
}
}
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.
So by using the getimagesize php built-in function we will be sure that the uploaded file is indeed an image.
The checkFileType method
private function checkFileType(){
if(!in_array($this->image_type, $this->allowed_image_types) ){
return $this->error =
"Only [.jpg, .png, and gif] images are allowed";
}
}
The method checks the incoming file-type against our allowed_image_types array. If the file-type is not included in the array, we assign an error message to the $error property.
The imageRename method
The method renames the image name with a 10 character long random string.
private function imageRename(){
// The string from which we will take 10 random characters from.
$str = "0123456789abcefghijklmnopqrstuvwxyz";
// Setting the length of the new image name.
$length = 10;
// We random reorder the characters in the $str variable.
$shuffled_str = str_shuffle($str);
// We take the first 10 characters from the randomized string.
$new_name = substr($shuffled_str, 0, $length);
// We are getting the image's extension.
$extension = pathinfo($this->image_name, PATHINFO_EXTENSION);
// We adding the extension in the new name and assigning it
// to the $image_name property.
$this->image_name = $new_name.".".$extension;
/*
If the new name already exists in the folder
(highly unlikely) the imageRename function
will create a new one.
*/
if(file_exists($this->uploads_folder.$this->image_name)){
$this->imageRename();
}
}
The sizeValidation method
private function sizeValidation(){
if($this->image_size > $this->upload_max_size){
return $this->error = "File is bigger than 2MB";
}
}
The function checks the image's file size. We don't allow files bigger than 2MB to be uploaded.
The moveFile method
private function moveFile(){
if(!move_uploaded_file($this->image_temp, $this->uploads_folder.$this->image_name)){
return $this->error =
"File not stored, please try again";
}
}
The method moves 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.
The recordImage method
With our last method we are going to insert the image name in the database.
private function recordImage(){
// Using the constants from the config file to connect
// to the database.
$mysqli = new mysqli(SERVER, USERNAME, PASSWORD, DATABASE);
// We assume that we have a database table
// named 'images' that has an 'image_name' column
// to insert the image's name.
$mysqli->query(
"INSERT INTO images(image_name)VALUES('$this->image_name')"
);
// Checking if the insert query was successful.
if($mysqli->affected_rows != 1){
// If nothing is recorded..
if(file_exists($this->uploads_folder.$this->image_name)){
// ... we remove the uploaded image file from
// the uploads/ folder...
unlink($this->uploads_folder.$this->image_name);
}
// ... and show an error.
return $this->error =
"There was a database error, please try again";
}
}
The HTML code
First create a file named index.php.
At the top of the file we have the php code, and beneath the html
form element.
<?php
// We require the image upload class.
require("image-upload-class.php");
// We check if the submit button is clicked ...
if(isset($_POST['upload-image'])){
// ... if so, we create a new imageUpload object and pass
// in as an argument the superglobal $_FILES array.
$image_upload = new ImageUpload($_FILES);
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="image">
<input type="submit" name="upload-image" value="upload-image">
<p class="error"><?php echo @$image_upload->error; ?></p>
<p class="success"><?php echo @$image_upload->success; ?></p>
</form>
Summary
We wrote a class which handles all the validation and upload process of an image file.
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 source code and use it in any way you like.
Times downloaded: 178