PHP file Upload full code with database advance script examples Demo

PHP file Upload script with Database

Every Blog and website require file upload functionality for the different purpose.I created a PHP file upload script demo for the beginner using procedural programming using PHP.It’s free to use, anyone can use it for their websites.Today almost 80% sites are powered by PHP this is the reason  PHP file upload script exist on my site.

PHP file upload script requirements:

  1. Uploads directory
  2. HTML form
  3. MySql database
  4. PHP upload script
  5. PHP view script

Getting started: Step1- Uploads directory

Create a  uploads directory where your all PHP file are stored.This directory is used by the upload.php script to store uploaded files/images.All the uploaded files are stored into tmp directory for any session of file uploading.Then letter these file moved to uploads directory by upload.php script.

Step 2:HTML form

Html form is used for getting a file from client side and send it to the upload handler [upload.php].For a file upload form must have the method set to Post and enctpye set to multipart/form-data and action set to Handler script in my case it is upload.phpFor file upload at least one input element required with type=”file”. Below I have given an example of HTML form for file upload in index.html.

Index.html



<!DOCTYPE html>
<html>
<head>
	<title>PHP file upload full code and script.PHP file upload examples.DEMO </title>
	<meta charset="utf-8">
	<meta name="description" content="PHP file upload full code and script.PHP file upload examples and codes ready to download and use."/>
</head>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
 choose file :<input type="file" name="file" value="Choose file">
 <input type="submit" name="upload" value="upload file">
</form>

</body>
</html>

Step 3: MySql Database

For PHP file upload script you do need to use MySQL database but I am using it to store image’s path, name, and size inside database so that I can easily create a  Dynamic gallery from it. I use a database with name test and table with name gallery. I have exported my empty gallery table so that you can easily create a table by just running below given SQL code into your MySql console or import it to your database.

gallery.sql

-- phpMyAdmin SQL Dump
-- version 4.6.6deb1+deb.cihar.com~trusty.2
-- https://www.phpmyadmin.net/
--
-- Host: localhost
-- Generation Time: May 21, 2017 at 05:30 PM
-- Server version: 5.5.55-0ubuntu0.14.04.1
-- PHP Version: 7.1.5-1+deb.sury.org~trusty+1

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `test`
--

-- --------------------------------------------------------

--
-- Table structure for table `gallery`
--

CREATE TABLE `gallery` (
  `id` int(10) NOT NULL,
  `path` varchar(250) NOT NULL,
  `size` varchar(250) NOT NULL,
  `name` varchar(250) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `gallery`
--
ALTER TABLE `gallery`
  ADD UNIQUE KEY `id` (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `gallery`
--
ALTER TABLE `gallery`
  MODIFY `id` int(10) NOT NULL AUTO_INCREMENT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Step 4: PHP upload script

Upload.php  handles the files uploaded by the user. First, it checks the is an original image or false image created by just changing the extension.Then look into uploads directory to find that file exist or not?identical files are not allowed by default. Large files are not allowed.If all condition found true, then the file is moved to uploads folder and a database record is created into gallery table associated with that file.

Upload.php

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$checkfile = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["file"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $checkfile = 1;
    } else {
        echo "File is not an image.
";
        $checkfile = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.
";
    echo "<img src='$target_file' height='50'width='50'>
";
    echo "<b>File Location:</b> $target_file 
";
    echo "<a href='view.php?view=gallery'><b>Show all uploaded images</b></a>
";
    $checkfile = 0;
}
// Check file size
if ($_FILES["file"]["size"] > 500000) {
    echo "Sorry, your file is too large.
";
    $checkfile = 0;

}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.
";
    $checkfile = 0;
}
// Check if $checkfile is set to 0 by an error
if ($checkfile == 0) {
    echo "Sorry, your file was not uploaded.
";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
        echo "The file <b>". basename( $_FILES["file"]["name"]). " has been uploaded.</b>
";
        $size=$_FILES["file"]["size"];
        $name=$_FILES["file"]["name"];
        try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "INSERT INTO gallery (path, size, name)
    VALUES ('$target_file', '$size', '$name')";
    // use exec() because no results are returned
    $conn->exec($sql);
    echo "New record created to existing database associated to images successfully
";
    echo "<a href='view.php?view=gallery'><b>Show all uploaded images</b></a>
";
    }
    catch(PDOException $e)
    {
    echo $sql . "
" . $e->getMessage();
    }

   $conn = null;
        echo "<img src='$target_file' height='50'width='50'>
";
        echo "<b>File Location:</b> $target_file 
";
    } else {
        echo "Sorry, there was an error uploading your file.
";
    }
}
?>

Step5: View.php

View.php I just used for checking that file is uploaded and stored on uploads folder and associated record into MySQL database is working. It can also be used to create a dynamic gallery.

view.php

<?php if($_REQUEST['view']=="gallery") { $servername = "localhost"; $username = "root"; $password = ""; $dbname = "test"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT id, path, size, name  FROM gallery";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
   
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $img=$row['path'];
        echo "<img src='$img' height='100' width='100'>";
    }
    
} else {
    echo "0 results";
}
$conn->close();
}
?>

This is all done! I have used PDO and MySqli extensions for experimental purpose only you can use whatever you want to use edit replace and go.
any feedback is appreciated leave a comment or submit a message at Contact Us page.

 

3 Replies to “PHP file Upload full code with database advance script examples Demo”

Leave a Reply

Your email address will not be published. Required fields are marked *