How to File Upload and View with PHP and MySQL | Coding Cage

How to File Upload and View with PHP and MySQL

By
We already have a Simple File Uploading tutorial in this blog and now This tutorial demonstrates how you can upload a files using PHP and Store uploaded file into the MySQL Database . With PHP it's easy to upload any files that you want to the server, you can upload MP3 , Image , Videos , PDF etc... files, this will also help you that how can you fetch uploaded files from MySQL Database and view them on Browser, so let's take a look.
File Upload and View with PHP and MySQL
 

File Uploading into the Database

First of all here i'll show you that how you can upload files using simple html form that sends file to the database through PHP script.

Read also : Insert, Upload, Update, Delete an Image in PHP MySQL using PDO
Read also : Simple File Uploading Script using PHP
Read also : Ajax Image Upload using jQuery and PHP

In this tutorial i am going to store file name, file type, and file size.
import the following sql code in your phpmyadmin. Database crediantials.

CREATE DATABASE `dbtuts` ;
CREATE TABLE `dbtuts`.`tbl_uploads` (
`id` INT( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`file` VARCHAR( 100 ) NOT NULL ,
`type` VARCHAR( 10 ) NOT NULL ,
`size` INT NOT NULL
) ENGINE = MYISAM ;

Database configuration.

$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "dbtuts";
mysql_connect($dbhost,$dbuser,$dbpass) or die('cannot connect to the server'); 
mysql_select_db($dbname) or die('database selection problem');

The HTML Form.

index.php

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>File Upload and view With PHP and MySql</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit" name="btn-upload">upload</button>
</form>
</body>
</html>

above html form sends the data to the following PHP script and joining this html and php script you can easily upload files to the database .
upload.php

<?php
if(isset($_POST['btn-upload']))
{    
     
 $file = rand(1000,100000)."-".$_FILES['file']['name'];
    $file_loc = $_FILES['file']['tmp_name'];
 $file_size = $_FILES['file']['size'];
 $file_type = $_FILES['file']['type'];
 $folder="uploads/";
 
 move_uploaded_file($file_loc,$folder.$file);
 $sql="INSERT INTO tbl_uploads(file,type,size) VALUES('$file','$file_type','$file_size')";
 mysql_query($sql); 
}
?>

Display files from MySql.

Now we are going to fetch uploaded files from MySql Database, data selecting from mysql database i hope you know that...
view.php

<table width="80%" border="1">
    <tr>
    <td>File Name</td>
    <td>File Type</td>
    <td>File Size(KB)</td>
    <td>View</td>
    </tr>
    <?php
 $sql="SELECT * FROM tbl_uploads";
 $result_set=mysql_query($sql);
 while($row=mysql_fetch_array($result_set))
 {
  ?>
        <tr>
        <td><?php echo $row['file'] ?></td>
        <td><?php echo $row['type'] ?></td>
        <td><?php echo $row['size'] ?></td>
        <td><a href="uploads/<?php echo $row['file'] ?>" target="_blank">view file</a></td>
        </tr>
        <?php
 }
 ?>
</table>

that's it
Complete script.
dbconfig.php

?<php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "dbtuts";
mysql_connect($dbhost,$dbuser,$dbpass) or die('cannot connect to the server'); 
mysql_select_db($dbname) or die('database selection problem');
?>

index.php
First file with Html form which select the file from client to be upload.

<?php
include_once 'dbconfig.php';
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>File Uploading With PHP and MySql</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="header">
<label>File Uploading With PHP and MySql</label>
</div>
<div id="body">
 <form action="upload.php" method="post" enctype="multipart/form-data">
 <input type="file" name="file" />
 <button type="submit" name="btn-upload">upload</button>
 </form>
    <br /><br />
    <?php
 if(isset($_GET['success']))
 {
  ?>
        <label>File Uploaded Successfully...  <a href="view.php">click here to view file.</a></label>
        <?php
 }
 else if(isset($_GET['fail']))
 {
  ?>
        <label>Problem While File Uploading !</label>
        <?php
 }
 else
 {
  ?>
        <label>Try to upload any files(PDF, DOC, EXE, VIDEO, MP3, ZIP,etc...)</label>
        <?php
 }
 ?>
</div>
<div id="footer">
<label>By <a href="http://cleartuts.blogspot.com">cleartuts.blogspot.com</a></label>
</div>
</body>
</html>

upload.php this is the main PHP Script of this tutorial which uploads the file to the server.

<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-upload']))
{    
     
 $file = rand(1000,100000)."-".$_FILES['file']['name'];
    $file_loc = $_FILES['file']['tmp_name'];
 $file_size = $_FILES['file']['size'];
 $file_type = $_FILES['file']['type'];
 $folder="uploads/";
 
 // new file size in KB
 $new_size = $file_size/1024;  
 // new file size in KB
 
 // make file name in lower case
 $new_file_name = strtolower($file);
 // make file name in lower case
 
 $final_file=str_replace(' ','-',$new_file_name);
 
 if(move_uploaded_file($file_loc,$folder.$final_file))
 {
  $sql="INSERT INTO tbl_uploads(file,type,size) VALUES('$final_file','$file_type','$new_size')";
  mysql_query($sql);
  ?>
  <script>
  alert('successfully uploaded');
        window.location.href='index.php?success';
        </script>
  <?php
 }
 else
 {
  ?>
  <script>
  alert('error while uploading file');
        window.location.href='index.php?fail';
        </script>
  <?php
 }
}
?>

view.php
this file shows the uploaded file from the database.

<?php
include_once 'dbconfig.php';
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>File Uploading With PHP and MySql</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="header">
<label>File Uploading With PHP and MySql</label>
</div>
<div id="body">
 <table width="80%" border="1">
    <tr>
    <th colspan="4">your uploads...<label><a href="index.php">upload new files...</a></label></th>
    </tr>
    <tr>
    <td>File Name</td>
    <td>File Type</td>
    <td>File Size(KB)</td>
    <td>View</td>
    </tr>
    <?php
 $sql="SELECT * FROM tbl_uploads";
 $result_set=mysql_query($sql);
 while($row=mysql_fetch_array($result_set))
 {
  ?>
        <tr>
        <td><?php echo $row['file'] ?></td>
        <td><?php echo $row['type'] ?></td>
        <td><?php echo $row['size'] ?></td>
        <td><a href="uploads/<?php echo $row['file'] ?>" target="_blank">view file</a></td>
        </tr>
        <?php
 }
 ?>
    </table>
    
</div>
</body>
</html>

style.css
and last but not the least stylesheet that makes beautify all the pages.

@charset "utf-8";
/* CSS Document */

*
{
 padding:0;
 margin:0;
}
body
{
 background:#fff;
 font-family:Georgia, "Times New Roman", Times, serif;
 text-align:center;
}
#header
{
 background:#00a2d1;
 width:100%;
 height:50px;
 color:#fff;
 font-size:36px;
 font-family:Verdana, Geneva, sans-serif;
}
#body
{
 margin-top:100px;
}
#body table
{
 margin:0 auto;
 position:relative;
 bottom:50px;
}
table td,th
{
 padding:20px;
 border: solid #9fa8b0 1px;
 border-collapse:collapse;
}
#footer
{
 text-align:center;
 position:absolute;
 left:0;
 right:0;
 margin:0 auto;
 bottom:50px;
}

That's it guys, please don't forget to share this tutorial.




236 comments:

  1. very nice script with design...
    thank you..

    ReplyDelete
  2. hello, nice script, how do we increase the upload limit

    ReplyDelete
    Replies
    1. hi olawole
      thanx for visiting....
      search for 'upload_max_filesize' in 'php.in' file and change it's value as you'r need, by default it's 2M

      refer this : http://cleartuts.blogspot.in/2014/12/simple-file-uploading-with-php.html

      Delete
    2. nice dude

      Delete
  3. thanx man...

    ReplyDelete
  4. Hi,

    Thanks for this!

    How could I make it so it doesn't error if there was no file uploaded? I have added this to an existing form and sometimes the file will intentionally be blank.

    Thanks

    ReplyDelete
  5. thanks Man you good job and helpfull Me

    ReplyDelete
  6. thanks man you solve my problem thanks again ad again

    ReplyDelete
  7. thanks, nice script.. how do i add upload description and date

    ReplyDelete
    Replies
    1. create new two fields in your table for description and date, and make change in INSERT Query
      as below :

      $sql="INSERT INTO tbl_uploads(file,type,size,description,date)
      VALUES('$final_file','$file_type','$new_size','$desc','$date')";

      Delete
  8. Replies
    1. Did you mean Resize ?
      I'll post it soon...

      Delete
  9. finally a really helpfull tutorial ! well done

    ReplyDelete
  10. Nice post.. For more information about file uploading and file handling visi this link..

    http://www.webtutorials55.blogspot.com

    ReplyDelete
  11. It's a good post.But can you tell me how to upload and insert in MySQL database if there are 3 files(image file,text file,and word file) ?

    ReplyDelete
  12. It's a good post.But can you tell me how to upload and insert into MySQL database at a time , if there are 3 files(image file,text file,word file) ?

    ReplyDelete
    Replies
    1. Hi Sushree :)

      You want to upload multiple files at a time, I have to post a complete tutorial on it soon, till then try googling about multiple file uploading ..

      Delete
  13. You may try this as well may it too will help you

    http://weinformer.blogspot.in/2015/07/file-upload-and-view-with-php-and-mysql.html

    ReplyDelete
  14. Can you post some tutorial to prevent sql injection with php oop and PDO

    ReplyDelete
  15. How I could upload data categorywise? i.e. if I have 3 categories and want to upload different files in different categories...

    ReplyDelete
    Replies
    1. Hi Sunny :)

      create select box to choose category and load category from table into the select box and set category id as a value in option element of select box then alter upload table and add category id as a new field for uploading file category and then make some change in insert query

      Delete
  16. Say I already had a mysql row without an upload, how would I amend my data with the upload?

    ReplyDelete

  17. hey bro i m getting this error how to slove this.


    Warning: move_uploaded_file(uploads/37261-Waseem 01.jpg): failed to open stream: No such file or directory in C:\xampp\htdocs\clearupload\upload.php on line 11

    Warning: move_uploaded_file(): Unable to move 'C:\xampp\tmp\php14AD.tmp' to 'uploads/37261-Waseem 01.jpg' in C:\xampp\htdocs\clearupload\upload.php on line 11

    ReplyDelete
    Replies
    1. Warning Says No such file or directory so check if directory/folder is there or not

      Delete
  18. you have just given the link view to view the file .. what i f user upload his image and it will shown to him on the same page not going to other or something like this..
    all is want user upload pic and this is should be displayed to his index page where he has uploaded the image

    ReplyDelete
    Replies
    1. Print Image name from MySQL Database into "<img>" element something like this
      <img src="folder_name/<?php echo $row['file']; ?>" />

      Delete
  19. Pradeep your tutorial is indeed very nice, you not only upload file but also store in the DB which is very good, but i notice that when you move_uploaded_file you do not use file extension move_uploaded_file($file_loc,$folder.$final_file) and this is working fine for you but when i move_uploaded_file without extension so file is uploaded without extension so file is not able to view, can you please tell me what is that? i also wrote tutorial about it but i keep extension also please check here https://htmlcssphptutorial.wordpress.com/2015/07/31/upload-file-using-php-and-save-in-folder/

    ReplyDelete
    Replies
    1. yes I missed that part in this tutorial, well i just want to show users that how to upload files in mysql
      and your tutorial is also very nice ...

      Delete
  20. Sir i have gone through your codes its really amazing and helpful.So now i want to upload multiple images at once to database and upload folder and also multiple delete at once to delete them using OOP. So i want help from you....

    ReplyDelete
  21. Thanks for this tutorial. I would like to add two more components to this. 1. how to prevent duplicate file uploads, and 2. how to include the date when the file was uploaded, and have it displayed on the view.php page.

    ReplyDelete
    Replies
    1. to prevent duplicate file upload you can use following function

      if (file_exists($_FILES["file"]["name"]))
      {
      echo "Sorry, file already exists.";
      }

      to add date :

      Alter "tbl_uploads" table and add new field as "uploaded_date" with "CURRENT_TIMESTAMP"
      or select database then run following sql code inside phpMyAdmin
      ALTER TABLE `tbl_uploads` ADD `uploaded_date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ;

      or you can use

      date(Y."/".m."/".d); function ,

      just add this date function in sql insert query current date will be added..

      Delete
  22. I'm getting errors when uploading files when I want to use the date when files are uploaded. What am I missing? Here's my code -

    $file_date = $_FILES['file']['date'];
    $folder="uploads/";

    // new file size in KB
    $new_size = $file_size/1024;
    // new file size in KB

    // make file name in lower case
    $new_file_name = strtolower($file);
    // make file name in lower case

    $final_file=str_replace(' ','-',$new_file_name);

    if(move_uploaded_file($file_loc,$folder.$final_file))
    {
    $sql="INSERT INTO tbl_uploads(file,type,size,date) VALUES('$final_file','$file_type','$new_size','$file_date')";

    ReplyDelete
    Replies
    1. $file_date = $_FILES['file']['date']; this is not file type

      use this : $file_date = date(Y."/".m."/".d);

      Delete
    2. How do I change this so I have the day,month, and then the year?

      Delete
    3. use this : $file_date = date(d."/".m."/".Y);

      Delete
  23. Hi Pradeep, Thanks for the awesome tutorial and scripts! it worked first time i tried it.

    Just a quick question, how can I filter the upload files that are coming in? ex. only images and pdf can be uploaded.

    Thanks!

    ReplyDelete
    Replies
    1. to upload only images and pdf files, you have to check file extensions to be uploaded, use certain file types like jpg, png, pdf ...

      use : $_FILES['field_name']['type'] to check file extension and make condition to upload ...

      Delete
  24. great script Pradeep, but how to verify uploaded files are not malicious. I want users to upload .pdf files and diplay them as thumbnails for other users to open or download. thanks

    ReplyDelete
  25. Great script Pradeep, but how can you verify that the uploaded files are not malicious (virus etc). I want users to upload.pdf files and have them displayed as thumbnails for users to open and/or download.

    ReplyDelete
    Replies
    1. as you want to upload only pdf files, for that check files extension before uploading file ...

      Delete
  26. Hi Pradeep, For some reason the file is not being inserted into the table. I have checked the mysql console and the database and table is there but the table is empty.

    ReplyDelete
    Replies
    1. check mysql insert query, and try to print (echo) sql insert query like "echo $sql;"

      Delete
    2. Thanks Pradeep, looking forward to the download script ;)

      Delete
    3. HI Bruce

      I will post a file downloading tutorial soon :)

      Delete
  27. Hi,

    Thanks for the script, it is great. I'm just having one problem: When I upload a file, I just get a blank screen, no redirects or errors, and the file is not moved into the /uploads/ folder or entered into the database.

    I only modified the database connect code with

    //database credentials
    define('DBHOST','x');
    define('DBUSER','x');
    define('DBPASS','x');
    define('DBNAME','x'');

    $db = new PDO("mysql:host=".DBHOST.";port=3306;dbname=".DBNAME, DBUSER, DBPASS);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    Thanks so much!

    ReplyDelete
    Replies
    1. Hi...

      as you modified only database connection code then you need to use "$db" variable with prepare and execute to work this script using PDO

      ex :

      $stmt = $db->prepare(query);
      $stmt->execute();

      hope this helps... :)

      Delete
  28. thanks for the tutorial pradeep, this is what i searching for.
    but can you tell me where the location of a script that displays pdf, doc, etc ??

    ReplyDelete
    Replies
    1. Hi Aulia...

      there is only one folder i have created here as "uploads" which stores all the types of file, and i have given only link of uploaded file... pdf can be displays on browser by clicking on the uploaded file link on view.php...

      Delete
  29. Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\projects\upload.php on line 48

    ----------------------------------------------------------------
    44 mysql_connect($dbhost,$dbuser,$dbpass) or die('cannot connect to the server');
    45 mysql_select_db($dbname) or die('database selection problem');
    46 $sql="SELECT * FROM uploads";
    47 $result_set=mysql_query($sql);
    48 while($row=mysql_fetch_array($result_set))



    please help me out

    ReplyDelete
    Replies
    1. this error might be on "view.php"

      $sql="SELECT * FROM uploads";
      $result_set=mysql_query($sql);
      while($row=mysql_fetch_array($result_set))

      this code is on view.php and make sure that you have changed table name yours is uploads and in this script i have used tbl_uploads...

      Delete
    2. hi i have configured the script to my existing theme ..how to upload it from my website

      Delete
    3. hello jayesh,
      uploading is same for localhost or online website , you can upload easily just put this script in your website with necessary configurations and you are done .

      Delete
  30. Hi Pradeep,
    Your code is working perfectly, however I'm trying to restrict files from uploading if they do not have the defined extensions and file size. I have played about with alert boxes which advise the client that only certain files can be uploaded but when these boxes are closed the script continues to upload and insert the files. I've tried exit() and the die() but just get a blank page result. Is there a way to stop the script and exit back to the index.php and have the client retry?

    ReplyDelete
  31. Why for your db engine are you Myisam engine instead of Innodb?

    ReplyDelete
  32. Pradeep thanks for taking the time to do these tut's. I have another question. When uploading files when I reach a maximum amount of files to be displayed on a web page I would like another webpage to be created how do I go about doing that?

    ReplyDelete
    Replies
    1. you must paginate your data ... here is the link for pagination tutorials

      http://www.codingcage.com/search/label/Pagination

      Delete
  33. Pradeep,
    Getting error: 'video can't be played because the file is corrupt' on .mp3 file view

    ReplyDelete
  34. I have also tried adding

    // Check if file already exists
    if (file_exists($_FILES["file"]["name"]))
    {
    echo "Sorry, file already exists.";
    }

    but seems to have no effect. same file continues to be added. I remove the rand function also. please help. Thanks

    ReplyDelete
    Replies
    1. HI Weito

      try following

      $folder = "uploads/";
      $target_file = $folder . $_FILES["fileToUpload"]["name"];

      if (file_exists($target_file))
      {
      echo "Sorry, file already exists.";
      }

      it works...

      Delete
    2. not working getting erorr file uploaded successfully in popup and in page showing file already exist and showing eror undefined index line no 10

      Delete
    3. hell tauseef, please check your code, there's must be something wrong in your code :)

      Delete
  35. Pradeep

    I've been trying to upload larger files (500mb) Ive made the necessary changes in the php.ini but the upload doesnt seem to be working. When I try to upload the page just stops on the upload.php page. No warnings or failure notice or anything like that... any ideas?

    ReplyDelete
    Replies
    1. hi there...

      again open "php.ini" file and search for the following

      post_max_size = 3M
      upload_max_filesize = 64M
      max_file_uploads = 20

      and change the by default values as your need

      hope it helps...

      Delete
  36. Hi,

    Love this script !

    One thing,, is it posible to add a text field to, so this text store in the database, wil display it with image

    Thanks

    ReplyDelete
    Replies
    1. Hi Fred,

      yes it's possible to store text field, just alter mysql table and add text field and change mysql insert and select query

      Delete
  37. file uploaded successfully but i am not able to view the uploaded file. it shows no object found

    ReplyDelete
    Replies
    1. Hi Nemchand,

      if file uploaded successfully then how you are not able to view the file, check your code if there is something wrong in the script, if you modified this script, otherwise it's working script,

      if there is error in the code then show me the error...

      Delete
    2. the same error for me also!!!!!!

      Delete
    3. file uploaded successfully but i am not able to view the uploaded file. it shows no object found

      Delete
    4. if there is error in the code then show me the error...

      Delete
    5. the code is working awesome i am able to see the file are using xampp which version msql or mysqli

      Delete
  38. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. Hi Rahul,

      it's simple, as i showed uploaded files on "view.php" in the table format, do the same just copy code and paste in "index.php" below uploading form

      hope it helps :)

      Delete
  39. :) thanks pradeep .. it works great ... another thing is that i want to upload multiple files on the same row of the database with only one upload button .. can you please suggest me how to do that? thanks a lot bro ...

    ReplyDelete
    Replies
    1. multiple file uploads , i will post a tutorial about it soon :)

      Delete
  40. Hi, i followed the tutorial through to the end. I increased the upload_max_filesize = 2M to 1024M, when i try to upload a file with a small size, it uploads without any errors. When i try to upload a file that is large(for example a file with the size 18M), it gives this error "Warning: POST Content-Length of 18921011 bytes exceeds the limit of 8388608 bytes in Unknown on line 0" and i cant find anything on it when i Google it. Please help me out. It gives the same kind of error when i try the simple-file-uploading-with-php tutorial too. Thanks.

    ReplyDelete
    Replies
    1. Hi Winfred,

      open "php.ini" file and search following things

      post_max_size = 3M
      upload_max_filesize = 64M
      max_file_uploads = 20

      and change the by default values as your need...

      Delete
  41. Hi,

    Thanks for the tutorial. I downloaded the script and I haven't changed anything. I get this error when I try to upload a JPG. What am I missing?

    Warning: move_uploaded_file(uploads/94829-77190-3d-glass-green-effect.jpg): failed to open stream: Permission denied in /Users/numb/Sites/uppladdning/upload.php on line 22

    Warning: move_uploaded_file(): Unable to move '/private/var/tmp/phpP2FqRW' to 'uploads/94829-77190-3d-glass-green-effect.jpg' in /Users/numb/Sites/uppladdning/upload.php on line 22

    Thanks for the help!

    //Devotte007

    ReplyDelete
  42. Hi,

    Thanks for the tutorial. I downloaded the script and I haven't changed anything. I get this error when I try to upload a JPG. What am I missing?

    Warning: move_uploaded_file(uploads/94829-77190-3d-glass-green-effect.jpg): failed to open stream: Permission denied in /Users/numb/Sites/uppladdning/upload.php on line 22

    Warning: move_uploaded_file(): Unable to move '/private/var/tmp/phpP2FqRW' to 'uploads/94829-77190-3d-glass-green-effect.jpg' in /Users/numb/Sites/uppladdning/upload.php on line 22

    Thanks for the help!

    //Devotte007

    ReplyDelete
    Replies
    1. Hi there,

      "failed to open stream" and "Unable to move", this error clearly shows that there is folder name are mismatched or does not exist, so check folder name in your file.

      Delete
  43. hey i cant view the uploaded files the table is empty :(

    ReplyDelete
    Replies
    1. hi roshan,

      there's must be some error, if you modified this script then check mysql queries and other thing , this is working script ...

      Delete
    2. got it right on the second time thanks :D and can you tell me how to change this in oder to upload files in to several tables like for example there are 3 tables name 2010,2011,2012, user has to select a table and upload the file to that specific tabel?

      Delete
    3. Hi Roshan ,

      if user has to select table to upload files in different tables for that you have to put select box and fill it's options with table name like below

      <select name="tbl_name">
      <option value="tbl_1">table one</option>
      <option value="tbl_2">table two</option>
      <option value="tbl_3">table three</option>
      </select>

      and take a variable for table name from above select list : $tbl = $_POST['tbl_name'];

      after it put the $tbl variable in insert query like this :

      INSERT INTO $tbl(file,type,size) VALUES('$file','$file_type','$file_size')";

      if all uploading tables has same fields then it will work

      hope it helps :)


      Delete
  44. getting this now :3
    Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:\wamp\www\dbconnect.php on line 2

    ReplyDelete
    Replies
    1. yes it's because we have MySQL extension in this tutorial i recommend you to use PDO or MySQLI

      PDO : http://www.codingcage.com/search/label/PDO
      MySQLI : http://www.codingcage.com/search/label/MySQLi

      or if you want to use this script then put the following code in "dbconfig.php" in the first line

      error_reporting( E_ALL & ~E_DEPRECATED & ~E_NOTICE );

      Delete
    2. thanks it was very helpfull. (y)

      Delete
    3. you're welcome roshan

      keep visiting :)

      Delete
    4. my last question xD i upload a video to this database and from the view page how can i redirect to a seperate page by clicking on the video name or a new view button where i can watch it or simply in other words how can i make it open and view in another page? Thanks :)

      Delete
    5. hello roshan,
      it's quite simple, from view.php as i displayed all the uploaded files within anchor tag, like this
      <a href="uploads/<?php echo $row['file'] ?>" target="_blank">view file</a>

      just replace hrefs="" value and with page name with QueryString and in querystring define file id, then using query string fetch the file using $_GET[] function

      <a href="pagename.php?file_id=<?php echo $row['id'] ?>" target="_blank">view file</a>

      Delete
  45. sir, can you explain..

    $final_file=str_replace(' ','-',$new_file_name);

    if(move_uploaded_file($file_tmp,$folder.$final_file))

    ReplyDelete
    Replies
    1. hello himanshu,

      here str_replace() function replace all the unwanted spaces with - (hyphen) and move_uploaded_file() function moves the file to the specified folder.

      Delete
  46. nice script.... but when i tried to upload image it says error while uploading file... please help me out

    ReplyDelete
    Replies
    1. hello adeyeye, please check if you have made some changes in this script.

      Delete
  47. This is awesome!!!
    I was wondering if there's a way to give the file a title when you upload so that when you view the HTML table it shows the title name instead of the file name? Example "Title of File" instead of filename.pdf

    ReplyDelete
    Replies
    1. hello there, yes you can give title for file and you can also show file title in HTML table, just alter table and add new field as file_title and make some changes in insert query.

      Delete
  48. Hey thanks for this tutorial....it really works but there is a problem with me........file is uploading in a local folder but not in mysql database.....tbl_uploads show empty and in view.php it shows nothing in table..

    ReplyDelete
    Replies
    1. hello rishi,
      please check MySQL Insert Query in "upload.php"

      INSERT INTO tbl_uploads(file,type,size) VALUES('$file','$file_type','$file_size');

      Delete
  49. It was

    if(move_uploaded_file($file_loc,$folder.$final_file))
    {
    $sql="INSERT INTO tbl_uploads(file,type,size) VALUES('$final_file','$file_type','$new_size')";
    mysql_query($sql);
    ?>

    now I've change it to yours as

    if(move_uploaded_file($file_loc,$folder.$final_file))
    {
    $sql="INSERT INTO tbl_uploads(file,type,size) VALUES('$file','$file_type','$file_size');";

    still uploading in local folder uploads but table is empty in mysql....
    please help me out

    ReplyDelete
  50. hey thanks I got it done !!!

    ReplyDelete
  51. how can i show particular image by its id

    ReplyDelete
    Replies
    1. hello brin,

      it's quite simple, from view.php as i displayed all the uploaded files within anchor tag, like this
      <a href="uploads/<?php echo $row['file'] ?>" target="_blank">view file</a>

      just replace hrefs="" value and with page name with QueryString and in querystring define file id, then using query string fetch the file using $_GET[] function

      <a href="pagename.php?file_id=<?php echo $row['id'] ?>" target="_blank">view file</a>

      hope this helps :)

      Delete
  52. Thanks for sharing this great article ..This is very helpful,.
    "blueapplecourses"

    ReplyDelete
  53. Hello, first of all thanks for the script works like a charm, is there any chance that you can share the code for update a file already uploaded? if you can I would be really grateful :)

    ReplyDelete
    Replies
    1. hello prowine, it's easy to update uploaded file, just execute update query for mysql table and within this remove uploaded file using unlink() function and, set new file name in update query. hope you got it :)

      Delete
    2. Just a little bit actually im kinda newbie with myslq and php, but im going to do my research to learn new stuff about this, thanks you have a great day! :)

      Delete
    3. hello prowine, thanks for visiting and dropping comment,
      keep learning and keep visiting :)

      Delete
  54. Hye, when i copy this coding. But,the output is blank?why

    ReplyDelete
    Replies
    1. hi mira, why are you copying the code, i have given the file for download, so download it and try .

      Delete
  55. Hello Pradeep, I want to restrict the file type to pdf. so how can i modify the above code to suit the requirement?

    ReplyDelete
    Replies
    1. Hello there, if you want to restrict pdf files then write code for pdf extension and if the file is pdf display error message

      $_FILES['filepdf']['type'] != "application/pdf"

      Delete
    2. Dear Pradeep, Thanks for your quick reply. since i am new to coding can you give me the code block, and where should i insert in your above code.

      Delete
  56. Hi, how to replace the "view" with download, so it will download instead of view?

    ReplyDelete
    Replies
    1. hello lyserg, here is quick option you can use, just add new attribute as download. in view link

      <a href="uploads/file_name_here" download="file_name_here">Download</a>

      Delete
  57. Ya know, I got really excited when I read the title of the post, and the opening paragraph furthered that excitement. Why? Because I actually need the solution this article CLAIMS it will give (sadly it failed at delivery).

    This article does NOT teach one how to do as the opening line claims, "Store uploaded file into the MySQL Database". Rather it teaches one how to upload a file to the server and store the location of that file in the database - which is vastly different. Using type largeblob, one should be able to store files in the database.... not locally on the server. That's what I am trying to learn about. If you have any articles about storing files directly into the database without local file storage, I really am interested.

    ReplyDelete
  58. I have a problem in sessions .When I use session's in query. The file name ($final_file) is not working.Could you please fix it.

    $sql="INSERT INTO tracks(file,type,size,user_id)
    VALUES('$final_file','$file_type','$new_size','".$_SESSION['id']."')";

    ReplyDelete
    Replies
    1. Hello Taha, please check that how it's not working, check your mysql table with the table fields in your insert query, try to print $sql query, you will get an idea what's happening in your sql query.

      Delete
  59. how do i store the data in database?

    ReplyDelete
  60. how i do it for store the file to phpmyadmin..please help me

    ReplyDelete
    Replies
    1. Hello Norizal, this tutorial is already with MySQL database(PHPMyAdmin) and the file name is storing in database and associated file moved in folder :)

      Delete
    2. I need your help to be able to download files stored in sql database. row location is where the dumped uploaded file is.Thanks..

      Delete
  61. i still get an error in uploading a file in whatever file i upload... please help i copy it correctly but still doesn't run right, thankyou

    ReplyDelete
    Replies
    1. We have the same problem. What should we do sir? What is wrong?

      Delete
    2. Mine is working now. I just forgot to create a folder.

      Delete
  62. Hi,i am getting this error... i have increase the size in php.ini but still??? it happen when upload video or audio of bigger size??? by the way nice tutorial
    Warning: POST Content-Length of 8627491 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

    ReplyDelete
  63. Hi,i am getting this error... i have increase the size in php.ini but still??? it happen when upload video or audio of bigger size??? by the way nice tutorial
    Warning: POST Content-Length of 8627491 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

    ReplyDelete
  64. hi i am getting this error "Warning: POST Content-Length of 48119840 bytes exceeds the limit of 8388608 bytes in Unknown on line 0" i have increase the size from php.ini but still?? any help

    ReplyDelete
  65. shows error like this -- > mysql_fetch_array() expects parameter 1 to be resource,boolean given in C:\xampp\htdocs\check\view.php on line 30

    and no data is inserted in database

    ReplyDelete
    Replies
    1. Hey Ashok, please check your code, there's must be some error while inserting or selecting on index and view page ...

      Delete
  66. i successfully upload the file but i cant see it in the table. why?

    ReplyDelete
  67. i successfully upload the file but why i cant see it in table?

    ReplyDelete
    Replies
    1. hello sona, check your insert query ... try to echo insert query

      Delete
  68. please can you modify this so that at a successful login the users will see a menu with the following
    1.upload document for evaluation 2. check documents submitted for evaluation 3. check doc to evaluate 4. check documents you evaluated
    thanks

    ReplyDelete
  69. hi, I can't download the script on Box, is there a problem or its just me, because I am able to download all your other scripts.

    ReplyDelete
    Replies
    1. Hello Muchaeli, link is updated , download it ...

      Delete
  70. Hi,
    I am getting an error when trying to upload files, error saying 'error while uploading file'.
    Can you help me out with it please ?
    Thanks

    ReplyDelete
  71. Hi,
    I am getting an error when uploading the file, error saying 'error while uploading file'.
    Can you help me out please ?
    Thanks

    ReplyDelete
  72. Hi,
    I am getting an error, error saying ' error while uploading file'.
    do you know why? can you help me please ?
    thanks

    ReplyDelete
    Replies
    1. Hello josef, there's must be some error with your code, please check, you can echo or print your insert query to know whats inserting(uploading) ...

      Delete
  73. HI,
    I am trying to upload mp3 file but it shows error.
    Warning: POST Content-Length of 32995016 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

    ReplyDelete
    Replies
    1. Hi Nadia,

      open "php.ini" file and search following things

      post_max_size = 3M
      upload_max_filesize = 64M
      max_file_uploads = 20

      and change the by default values as your need...

      Delete
  74. Hi sir, I tried doing this but I'm getting an error whenever I upload a file. It doesn't state what the error is, it just says "error while uploading file" Please help sir. Thanks!

    ReplyDelete
    Replies
    1. Hello Ericka, there's must be some error with your code, please check, you can echo or print your insert query to know whats inserting(uploading) ...

      Delete
  75. good work dude, thanks for your code

    ReplyDelete
    Replies
    1. thanks kamal, glad you liked it :)

      Delete
    2. Fine pradeep i want to upload 7-15 files according to user selection min 7 files to max 8 files and store it as above in my sql dp, i dont know how to use array in upload .php? can yu help me?

      Delete
    3. Hi pradeep trying to upload 5 files using five input options and linking into one submit button but i cant able to store their values in dtabase , can yu show any example or source code for this ?
      MY form would be like this:
      student should upload his birth certificate, then marksheets then his photo after that he need to click submit , so that all values should hit the databases.

      Delete
  76. Thank you sir,After few changes i get it.
    I have to upload multiple files in to database.Can you tell where to be use the loop

    ReplyDelete
  77. sir,How can i upload multiple files in this code.Can you help me plzzz

    ReplyDelete
  78. Sir,How can i upload multiple files in this code.Please,help me

    ReplyDelete
  79. Sir can u tell me how to insert multiple files in thiz code.
    Plz,tell me as soon as possible

    ReplyDelete
  80. Hi. everything is working great but my question is how do I insert a row from my userstable inte this table. for example I want to display the username of the user that have entered a file and also have a page where a user can view only the files they have entered. so I want to import the username from my user table into the sqlquery.

    ReplyDelete
  81. Hi. everything is working great but my question is how do I insert a row from my userstable inte this table. for example I want to display the username of the user that have entered a file and also have a page where a user can view only the files they have entered. so I want to import the username from my user table into the sqlquery.

    ReplyDelete
  82. Hi. everything is working great but my question is how do I insert a row from my userstable inte this table. for example I want to display the username of the user that have entered a file and also have a page where a user can view only the files they have entered. so I want to import the username from my user table into the sqlquery.

    ReplyDelete
  83. ERROR
    Deprecated: mysql_query(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:\wamp\www\file-uploading-with-php-and-mysql\view.php on line 27
    ERROR
    Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\wamp\www\file-uploading-with-php-and-mysql\view.php on line 28
    plz help me i can see the table and i really i need this to work

    ReplyDelete
  84. Fatal error: Uncaught Error: Call to undefined function mysql_query() in C:\xampp\htdocs\upload.php:25 Stack trace: #0 {main} thrown in C:\xampp\htdocs\upload.php on line 25

    help please ?

    ReplyDelete
    Replies
    1. I have the same problem, did you happen to find any solution for this? if you did, could you please share your solution with me. Thank you.

      Delete
  85. I like this source code : visit my shopping site that is developed by me. www.byadab.com

    ReplyDelete
  86. the same code is working fine on wamp server but when i uploaded site on server, after selecting image, when i am clicking on upload, blank screen comes up.
    when i debugged it, echo statements are getting displayed before the following line :
    if(move_uploaded_file($file_loc,$folder.$final_file))

    please help

    ReplyDelete
  87. I'm trying to modify upload.php to only allow videos, can you help as I cant do it! :(

    ReplyDelete
  88. I have made small changes and have now managed to check for certain file types, do I need to do anything more

    if($file_type != "video/mp4" && $file_type != "video/avi" && $file_type != "video/mov" && $file_type != "video/3gp" && $file_type != "video/mpeg")
    {
    ?>

    alert('Error: Suspicious file or not a valid video format ');
    window.location.href='index.php?fail';



    alert('successfully uploaded');
    window.location.href='index.php?success';

    ReplyDelete
  89. nicw script..how can i download automatically?

    ReplyDelete
  90. Hello thanks for the code. When i upload pdf files, it gets into the uploads directory but is not viewed in the table in view.php. There are only two image files in the list.

    ReplyDelete
    Replies
    1. hello prashant, sorry for the late reply, did you solved it ? and make sure that records are properly inserted into table or not.

      Delete
  91. It doesnt get stored into the database as well. What's the problem

    ReplyDelete
  92. $file = rand(1000,100000)."-".$_FILES['file']['name'];

    dont know why u had uses rand()...it is creaating error while viewing page

    ReplyDelete
  93. $file = rand(1000,100000)."-".$_FILES['file']['name'];

    ReplyDelete
  94. Fatal error: Uncaught Error: Call to undefined function mysql_query() in C:\xampp\htdocs\upload.php:25

    Help please???

    ReplyDelete
  95. Thank u so much................................

    ReplyDelete
  96. I need to download the data instead of viewing...
    Please help me out..

    ReplyDelete
  97. Thanks for the script. its really very useful

    ReplyDelete
  98. thanks sir its really helpfull

    ReplyDelete
  99. I am not download the file, no erros or exceptions is show

    ReplyDelete
  100. thank you for these best scripts!!

    I have a concern, what if i want to upload a video file and image file on the same page and save in one directory?

    ReplyDelete
  101. really very useful for me sir.....good job
    I have one question , tat is how to upload only the pdf files?Plz send the reply to my mail jenijenisha92@gmail.com

    ReplyDelete
    Replies
    1. hi jenisha, sorry for the late reply, and tupload only pdf files you need to check uploading files extension, and give condition that if file is pdf then proceed to upload otherwise display message that select only pdf files, that's it...

      Delete
  102. can't upload video, what is the problem

    ReplyDelete
  103. hello pradeep ! this is very nice tutorial and blog. Can You please post a tutorial about "how to save a file into database table and how to access that file".
    Thanks in advance

    ReplyDelete
    Replies
    1. hi gaurav, file is actually saving in database and how you want to access your file let me know ?

      Delete

  104. when face this problem, what i can do? help please..
    Warning: move_uploaded_file(uploads/29526-2-year.png): failed to open stream: No such file or directory in C:\xamp\htdocs\file\upload.php on line 22

    ReplyDelete
  105. hey its showing error while uploading files. What to do ?? i didn't change anything in code

    ReplyDelete
  106. I need to download the data instead of viewing...
    Please help me out..

    ReplyDelete
  107. Hi Pradeep how can we edit uploades file and my file stored in to database

    ReplyDelete
  108. multiple field in file uploading oding please help

    ReplyDelete
  109. hello sir,
    we were creating a form filling page using php where we upload the resume and view it. we got the first part where we could upload the file but we are not able to display.we use mysql to store the data/file uploaded.

    ReplyDelete
  110. hello sir,
    we were creating a form filling page using php where we upload the resume and view it. we got the first part where we could upload the file but we are not able to display.we use mysql to store the data/file uploaded.

    ReplyDelete
  111. Thanks for the tutorial.
    I am having one query , if i upload a csv file it uploaded successfully but when i view the csv file it downloads the csv file instead of showing its data.What to do to get rid of this problem ?

    ReplyDelete
  112. Hi Pradeep,
    How can i upload file without refresh page? Using with ajax & jquery

    ReplyDelete
    Replies
    1. hello salman, sorry for the late reply bro, and i will surely post a tutorial about image uploading with jQuery Ajax, keep visiting ...

      Delete
  113. hello salman, ask script edit

    ReplyDelete
  114. hello salman, ask script to edit there is , if there are comments in reply yes salman

    ReplyDelete
  115. hello salman, ask script to edit there is , if there are comments in reply yes salman

    ReplyDelete
  116. it is possible to switch to postgresql will work?

    ReplyDelete