Images play important role in a website. If you don’t know how to upload images in PHP then you are missing something attractive part of your website.
In this tutorial, you will learn how to upload image and display in PHP with the MYSQL database.
Let’s discuss the process of uploading images on the server using PHP programming.
How to upload the image in PHP?
The image uploading process completes by an HTML form. We create a form with an input type file. The Image is also a file. We upload image formats only using HTML form and PHP.
Image formats are –
JPG, PNG, JPEG, JPEG, GIF, etc. We restrict users to upload only these formats otherwise display an error like “Sorry, only JPG, JPEG, PNG & GIF files are allowed” We create a folder to save all images inside that folder using PHP scripts. First of all, we create MYSQL database table-like items. In the items table, we create two columns. The first column is for image names with extensions like – myimage1.png or myimage2.jpg etc and the second column is for only the title. The title may be page title or any image title. The image moves to the folder and the image name with extension is inserted into the database.
How to upload and display the image in PHP and MYSQL?
After the image is uploaded, we fetch rows using PHP while loop and use HTML image attributes to display the image in PHP. When the user selects an image to upload and enters the title, he clicks the upload button. Image moves to the folder and the image name with extension is inserted into the database.
All the images are displayed on the HTML page in the HTML table using PHP and MYSQL database.
Let’s create a database table –
Create a database table to insert image name with extension –
First of all, create a table in your database.
CREATE TABLE `items` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`image` varchar(255) DEFAULT NULL,
`title` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
)
In the database table above, we created an items table. The image column will be used to insert the image name with an extension in the table. The title column is an extra field for the image title or page title.
Create a connection file –
This connection file will be used to connect the HTML page to the database using PHP.
Create a file config.php
config.php
<?php
$dbHost = 'localhost';
$dbName = 'dbname';
$dbUsername = 'root';
$dbPassword = '';
$db= mysqli_connect($dbHost, $dbUsername, $dbPassword, $dbName);
?>
Kindly set the correct connection details.
Create an uploads folder to move all images in the same folder –
All images move to the folder on the server. We can store the image in the database but the best thing is to upload and move the image file to the folder.
Now create a folder – uploads (uploads is a folder name . You have to create it . )
Create this folder in the same path where you will create the PHP file. You can set a path after that.
Create PHP scripts to upload the image.
Now, we will create an index.php file. The index.php file will contain an HTML form to upload the image, an HTML table to display the images after uploaded and PHP scripts to move the image in the folder and insert an image into the database.
Lets’ create an index.php file.
index.php
<?php require_once("config.php");?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Image Upload in PHP and MYSQL database </title>
</head>
<body>
<?php
if(isset($_POST['form_submit']))
{
$title=$_POST['title'];
$folder = "uploads/";
$image_file=$_FILES['image']['name'];
$file = $_FILES['image']['tmp_name'];
$path = $folder . $image_file;
$target_file=$folder.basename($image_file);
$imageFileType=pathinfo($target_file,PATHINFO_EXTENSION);
//Allow only JPG, JPEG, PNG & GIF etc formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
$error[] = 'Sorry, only JPG, JPEG, PNG & GIF files are allowed';
}
//Set image upload size
if ($_FILES["image"]["size"] > 1048576) {
$error[] = 'Sorry, your image is too large. Upload less than 1 MB in size.';
}
if(!isset($error))
{
//move image to the folder
move_uploaded_file($file,$target_file);
$result=mysqli_query($db,"INSERT INTO items(image,title) VALUES('$image_file','$title')");
if($result)
{
$image_success=1;
}
else
{
echo 'Something went wrong';
}
}
}
if(isset($error)){
foreach ($error as $error) {
echo '<div class="message">'.$error.'</div><br>';
}
}
?>
<div class="container">
<?php if(isset($image_success))
{
echo '<div class="success">Image Uploaded successfully</div>';
} ?>
<form action="" method="POST" enctype="multipart/form-data">
<label>Image </label>
<input type="file" name="image" class="form-control" required >
<label>Title</label>
<input type="text" name="title" class="form-control">
<br><br>
<button name="form_submit" class="btn-primary"> Upload</button>
</form>
</div>
<div class="container_display">
<table cellpadding="10">
<tr>
<th> Image</th>
<th>Title</th>
</tr>
<?php $res=mysqli_query($db,"SELECT* from items ORDER by id DESC");
while($row=mysqli_fetch_array($res))
{
echo '<tr>
<td><img src="uploads/'.$row['image'].'" height="200"></td>
<td>'.$row['title'].'</td>
</tr>';
} ?>
</table>
</div>
</body>
</html>
In the code above –
1. The connection file is included at top of the file using require_once() PHP function
2. We created a form to upload the image.
In this form, we created an input type file because the browse button appears when you write an input type file and also a text field for the normal title.
3. Must write enctype="multipart/form-data" in the form because without the enctype attribute, you cannot upload the image. The type holds the image process.
4. You can restrict the user to upload image sizes less than 1 MB .
if ($_FILES["image"]["size"] > 1048576) {
$error[] = 'Sorry, your image is too large. Upload less than 1 MB in size.';
}
1MB == 1048576 bytes
You can increase the size according to your need.
How to restrict the user to upload only desired image formats JPG, JPEG, PNG & GIF?
The programmer can restrict the user to upload desired formats only.
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
$error[] = 'Sorry, only JPG, JPEG, PNG & GIF files are allowed';
}
You can set more formats according to your needs but these are the image formats
How to move the image file into a folder in PHP?
We use move_uploaded_file() PHP function to move image in the folder.
move_uploaded_file($file,$target_file);
Designing form and HTML table (CSS Stylesheet )
Create a style.css file to design the form and table.
style.css
body{
background-color: #f1f1f1;
}
.form-control {
width: 100%;
height: 25px;
padding: 6px 12px;
font-size: 14px;
color: #555;
background-color: #fff;
border: 1px solid #ccc;
border-radius: 4px;
}
.btn-primary {
padding: 6px 12px;
font-size: 14px;
font-weight: 400;
cursor: pointer;
border: 1px solid transparent;
border-radius: 4px;
background-color: #337ab7;
color: #fff;
}
.download_btn{
background: #479920 !important;
}
.container
{
margin-left: 30%;
width: 450px ;
background-color: #fff;
padding: 10px;
padding-right: 40px;
border: 1px solid #ccc;
border-radius: 4px;
}
.container_display
{
margin-left: 10%;
width: 900px ;
background-color: #fff;
padding: 10px;
padding-right: 40px;
border: 1px solid #ccc;
border-radius: 4px;
}
label {
font-size: 16px;
}
.success
{
margin: 5px auto;
border-radius: 5px;
border: 3px solid #fff;
background: #33CC00;
color: #fff;
font-size: 20px;
padding: 10px;
box-shadow: 10px 5px 5px grey;
}
After using CSS, it will look like this.
In this way, you can upload the image and display it on an HTML page using PHP and MYSQL database.
If you want to upload and display an image on a PHP website then follow this complete tutorial.
Recommended Posts:-