PHP, MySQL (PDO) Upload Image to Server – #12

Hi all,

So I’ve been programming in PHP for a few years now against opinions of my colleagues and co workers, I think its a great language and thanks to PHP 7 (FINALLY) it is actually quicker than you would think. So for this reason I dont intend on stopping working with it. So as we all know, the internet is full of information that isn’t always right, or it is simply outdated. Something that I found incredibly tedious to search for was image uploading to a server, store the url of the image and then display it on the page from an SQL server. Today I’m going to show you how to create this system of uploading and displaying an image from scratch. All you will need is your ide of choice – Notepad++ is my personal fav for this ok – and easy php or equivalent local developer environment. Source code will be below, and a download for the packaged contents. NOTE that there is no validation for this, check out w3 schools for simple validation.

So lets get started. We will be creating an upload script, fetch script, sql script for the database to store the image and a simple html page that will post the image to the upload script. A config file will also be created for usability and disabling errors… list goes on. You should ALWAYS use a config file so the transition between local and live development is even more seamless.

So to start lets get the database set up.

SQL

CREATE TABLE IF NOT EXISTS `photos` (
`imageID` int(6) NOT NULL AUTO_INCREMENT COMMENT 'ID of the image',
`imagePath` varchar(50) NOT NULL COMMENT 'The image name being stored',
`photographerID` int(6) NOT NULL COMMENT 'Blog Post ID if post image is in',
`photoTags` varchar(50) NOT NULL COMMENT 'Tags associated with the photo',
PRIMARY KEY (`imageID`)
);

As we are NOT doing this with blobs so the file size isnt static (i have the source code for this if you want it tweet me) therefore the file will be stored in a directory in our server, so simply a string such as uploads/my-image.png

Next we will create our Upload html page

upload.html

<form action="store_image.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>

Here we past everything / our image posted to store_image.php (or upload, i recommend renaming these files so you understand what is being passed around)

store_image.php

<?php
include_once("config/config.php");

$folder = "uploads/";
$upload_image = $folder . basename($_FILES["fileToUpload"]["name"]);
if(isset($_POST["submit"])) {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $upload_image)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
//store it in the dba_close
$insert_query="INSERT INTO photos (imagePath, photographerID, photoTags) VALUES('$upload_image', 0, 'tag1')";

$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $con->prepare($insert_query);
$stmt->execute();

//Navigate to display the image
header( 'Location: fetch_image.php' );

} else {
echo "Sorry, there was an error uploading your file.";
}
}

?>

If you set up the data base with the script above you are going to store the image into the server, if this is successful then you are going to store the image url in the database with a unique id to be retrieved when you want.

fetch_image.php


<?php

include_once("config/config.php");

$con= new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
$sthandler = $con->prepare("SELECT * FROM photos");

$sthandler->execute();
while ($row = $sthandler->fetch(PDO::FETCH_ASSOC)){

$image_name=$row["imagePath"];
echo "<img src=".$image_name." width=100 height=100/>"?>
}
?>

Here we simple echo out the directory of all the images stored in our table. Remember the tags in the echo statement so it parses as html and not simply text!

And last but not least, a config file. Note the storage location of this file. Its under a directory config/config.php allowing us to have a few different configs that we can rename depending on the enviroment we are using. Mine is below, but remember you will need to adjust this to suite your set up.

config.php
<?php
error_reporting(E_ALL);
define( “DB_DSN”, “mysql:host=localhost;dbname=db_pshare” );
define( “DB_USERNAME”, “root” );
define( “DB_PASSWORD”, “” );
?>

Thats it, simple right? So tweet me for questions as I dont moderate this blog and mainly use it for myself. Let me know if you need any help. Its pretty simple without any unnecessary code to confuse you until you get it set up.

Have a good one!

– Corrie