The download process is the most important process for a PHP website. In the download process, first of all, we upload the image to a folder and MYSQL database then fetch and download it by a download button.
In this tutorial, you will learn how to upload, display and download image using PHP and MYSQL database. We will create a download button for each images. We will be able to download images by clicking the download button and save on your local computer.
Upload image and download in PHP and MYSQL
First of all, we will upload the image to the server folder. We will create a database table to insert the image name with an extension. The folder will be used to save all images. When the user will click the upload button, the image will move to the folder, and the image name with extension will be inserted into the database table.
After completing the upload process, we will fetch the image from the database and display it in the HTML table using PHP and MYSQL database.
Here, we will create download PHP scripts to download from the folder. We will restrict direct download from the folder using htaccess file. As you know that we never allow the users to download the image directly because we want that user to download the image from our website page. This is the most important logic .that we restrict the user to access the direct folder of images.
We will create a download button and process to download images using PHP programming.
Let’s create a database table –
Create a database table for uploading image
First of all, create a database table using the query below –
CREATE TABLE `items` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`image` varchar(255) DEFAULT NULL,
`title` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
)
The table name is “items”.
Image – The image column will be used to store the image name.
Title – The title column is an extra field. You can use it for page titles or image titles.
Create a PHP connection file –
The connection file is used to connect the database in PHP.
config.php
<?php
$dbHost = 'localhost';
$dbName = 'dbname';
$dbUsername = 'root';
$dbPassword = '';
$db= mysqli_connect($dbHost, $dbUsername, $dbPassword, $dbName);
?>
Kindly provide the correct host details.
We already discussed in the PHP image upload tutorial that we upload images in a folder.
Now, we will need to create the folder.
Create a folder "uploads"
Now create a folder – uploads ("uploads" is a folder name . You have to create it . )
Kindly create an uploads folder in the same path from where you will execute PHP scripts after that you can create a folder anywhere inside any folder but you have to set the correct path.
Upload the image, and display with the download button using PHP
According to the CRUD application, we have to fetch the database from the database and display it in a table. Here we will follow the same. We will fetch the image name and title from the database and will display them in an HTML table with the download button. The download button will be used to download the image from the server. We will create code for image upload and display it in the same file.
Let’s 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>Uplaod image and download 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"] > 500000) {
$error[] = 'Sorry, your image is too large. Upload less than 500 KB in size.';
}
if(!isset($error))
{
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>
<td><a href="download.php?id='.$row['id'].'"><button class="btn-primary download_btn">Download</button></a>
</td>
</tr>';
} ?>
</table>
</div>
</body>
</html>
We already discussed the image upload process in a tutorial. When a user selects an image from the local computer and clicks on the upload button the image moves to the folder and the image name with extension is inserted into the database table. All images display in the HTML table with a download button with an id using PHP while loop. We will create a download.php page and will use row id to download the image from the server.
Download the image from the server in PHP?
The download process will be executed by row id. We will fetch the image by id and download it with the code below.
First of all, create an htaccess file in the same uploads folder.
uploads/·htaccess
·htaccess
Deny all
This htaccess file will restrict all the users to download the image directly from the folder.
Now, create a download.php file and use the code below .
download.php
<?php require_once("config.php");
$id = $_GET['id'];
$stmt=mysqli_query($db,"SELECT image from items WHERE id=$id");
$count=mysqli_num_rows($stmt);
if($count==1) {
$row=mysqli_fetch_array($stmt);
$image=$row['image'];
$file='uploads/'.$image;
if (headers_sent()) {
echo 'HTTP header already sent';
} else {
ob_end_clean();
header("Content-Type: application/image");
header("Content-Disposition: attachment; filename="".basename($file).""");
readfile($file);
exit;
}
echo "<script>window.close();</script>";
}
else
{
echo 'File not found ';
}
?>
In the code above –
1. We fetched the image name with row id.
2. You have to give the correct path to the folder.
3. We allowed the image to download using this download.php file.
Create CSS stylesheet file -
You can use CSS to design.
Create a style.css file.
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;
}
Now, open index.php in your browser and upload any image. After the image is uploaded, you can check the image in the folder and check the image name in the database. The image will be displayed after uploaded with the download button. Click on the download button and save the image to your local computer.
In this way, you can upload, display and download image using PHP and MYSQL database.
Recommended Posts:-