Uploading And Downloading Files In PHP And MySQLi
Mục lục bài viết
Uploading And Downloading Files In PHP And MySQLi
Last Updated : Jan 1, 2023
IN – PHP MySQLi
In this tutorial we will show you the solution of uploading and downloading files in PHP and MySQLi, we can upload any files on database then we can download those files by retrieve from database and for uploading files on database table has no limit we mentioned.
In database we can do store, edit, update or delete these operations and mainly database used for collects and store all user information.
When we need some information from database we can retrieve using php because it is a server side language.
Step By Step Guide On Uploading And Downloading Files In PHP And MySQLi :-
Here we need to collect server details and make request to server by ‘mysqli_connect()’.
For collect user inputs we need to create html elements of input tags with three types one is ‘text’ for getting image title and ‘file’ type for upload files, another one is for ‘submit’.
When submit button clicks by user it loads uploading program, in that we generated random number before file name for avoid file replacing with same name on database.
Then we need to execute insertion query with ‘uploading file, file title’ details and those details successfully inserted with database.
Another input tag for ‘downloading’ all files from our table ‘fileup’, it’s done when user clicks on ‘Generate Download’ button.
<!DOCTYPE html> <html> <head> <title>File Upload And Download</title> </head> <body> <form method="post" enctype="multipart/form-data"> <label>Title</label> <input type="text" name="title"> <label>File Upload</label> <input type="File" name="file"> <input type="submit" name="submit"> <input type="submit" name="download" value="Generate Download"> </form> <?php $localhost = "localhost"; #localhost $dbusername = "root"; #username of phpmyadmin $dbpassword = ""; #password of phpmyadmin $dbname = "dbase"; #database name #connection string $conn = mysqli_connect($localhost,$dbusername,$dbpassword,$dbname); if (isset($_POST["submit"])) { #retrieve file title $title = $_POST["title"]; #file name with a random number so that similar dont get replaced $pname = rand(1000,10000)."-".$_FILES["file"]["name"]; #temporary file name to store file $tname = $_FILES["file"]["tmp_name"]; #upload directory path $uploads_dir = 'img'; #TO move the uploaded file to specific location move_uploaded_file($tname, $uploads_dir.'/'.$pname); #sql query to insert into database $sql = "INSERT into fileup(title,image) VALUES('$title','$pname')"; if(mysqli_query($conn,$sql)){ echo "File Sucessfully uploaded"; } else{ echo "Error"; }} if (isset($_POST["download"])){ $sql = "SELECT * FROM fileup"; $q=mysqli_query($conn,$sql); echo "<table>"; while($row=mysqli_fetch_array($q)){ echo "<tr>"; echo "<td>"; echo $row['title']; echo "</td>"; echo "<td>"; ?><a href="img/<?php echo $row['image'];?>">Download File</a> <?php echo "</td>"; echo "</tr>"; } echo "<table>"; }?> </body> </html>
- A php script can be placed anywhere in the document. A php script starts with <?php and end with ?> tags.
- The default file extension for php files is “.php” and php each statements end with ‘;’ semicolon. Between start and end tag we need to define our program in php.
- First we need to create database with name ‘dbase’ and table name ‘fileup’ with three columns namely ‘id,title,image’. That ‘id’ column type must be ‘primary and auto_increment’ and title type is ‘varchar’, image type is ‘varbinary’.
- We need to collect server details so we used variables ‘$localhost,$dbusername,$dbpassword,$dbname’ for collecting our server details.
- In variable ‘$localhost’ we stored server name and its server name will available on server page top left end. Most of time it’s name will ‘localhost’.
- Variable ‘$dbusername’ used for store ‘user name’ its most of time default value also ‘root’, ‘$dbpassword’ variable for store ‘user password’ and ‘$dbname’ variable for store ‘database name’.
- Database name will definitely vary because we can give any name for our database when we are creating. If you use above code then create database on xampp server with name ‘dbase’.
- Then using ‘mysqli_connect()’ method with parameter of server details we request server for granting permission.
- When request grant means its finding database name on xampp server and when it finds its connection will success. If the database name not exit or any server details not correct then it throws error on browser webpage.
- So we have give correct details of server and database then we can achieve result easily. First if() condition for checking whether the submit button clicked or not.
- We are storing user inputs, title of image to variable ‘$title’. Then we generating random number for appends to file name front because it avoids replacing and we need to give directory name to variable ‘$uploads_dir’. This directory must present in same location of this file location and those file and directory must be in server location.
- We created earlier temporary location, it’s for move our files to that location and we exexcuting insert query for insertion of user inputs ‘title, file’ to our table ‘fileup’ in database ‘dbase’ on server.
- Next if() condition for checks our insertion whether executed successfully or not. When it success it throws ‘file successfully uploaded’ message on webpage otherwise error message will thrown on webpage.
- After uploading image on database when user clicks on ‘Generate Download’ button, it starts retrieving those files and generating downloading link. First we need to create select query for selecting all datas from table and stored to variable ‘$sql’.
- For executing the select query we need to use ‘mysqli_query()’ function with connection string ‘$conn’ then result stored to variable ‘$q’. Here we embedded html for create table and we using while loop for fetch all stored ‘file title and file’ on table ‘fileup’ by ‘mysqli_fetch_array()’ function.
- In loop fetching datas row by row from database table those are stored to variable ‘$row’ then each row column values of ($row[‘title’] is refers ‘file title’, $row[“image”] is refers ‘uploaded files’) printed on webpage line by line.
- For generate file link we used <a> anchor tag and <a> tag attribute ‘href’ refers path of file. In href “img/” refers file stored folder on server location then printed file name within path by ‘$row[‘image’]’.
- So finally we generated those files path stored on databse. Within a while loop we printed those fetched datas on html table.
- When clicks on ‘Download’ link it’s open respective file with download option, so we can download all files easily.
- Then result will printed on our webpage using ‘echo()’ with ‘connection succeed’ string. It also a statement for print any values in php.
Conclusion :-
In conclusion we are able to know how to upload any images on mysql database using php.
When work with php we need to create and process php files at server location and then we need to start the server before execute the program.
When user gives inputs and clicks submit button it will loads successfully uploaded on our database table in server with success message display on webpage for user verification, otherwise it throws error message on webpage of browser.
Same as for downloading when user clicks on ‘Generate Download’ button fetched all files from database table printed with download link on webpage with html table format.
Within those link which file we need for download click on that particular link then it will open that file with download option or downloaded immediately that is depends on file type, So we can download easily.
I hope this tutorial on uploading and downloading files in PHP and MySQLi helps you and the steps and method mentioned above are easy to follow and implement.