How To Upload Images To Your Website Using PHP & MySQL

Posted by Godson on April 24, 2019 in PHP
Card Image
Spread the love


Here is a video version of this article.

In this article, I will teach you how to upload images to your web server using PHP. The ability to upload images to your web server is needed in most of the websites today, especially in membership websites where profile pictures of the users are stored.

In this article, I will show you an approach where you will store the actual image in your web server and then store the path of the image in your database (we will use MySQL in this article).

So, let’s get started

Setting Things Up

If you haven’t already set up a local environment for PHP, go ahead and download and install XAMPP (or other equivalents like MAMP, WAMP Server, etc). Download and install a code editor (for example, VS Code, Brackets, Atom, Sublime Text, etc).

Go to the directory where your PHP projects are stored (it is in htdocs folder inside the xampp installation folder in case of XAMPP). Create a new folder and create four files: index.php, style.css, db.php and process.php.

Also create a folder called img to store all the uploaded images.

Open the folder in your code editor. Now, open your browser and go to localhost/fileupload (type your folder name in place of fileupload).

Design The Page

First, design the webpage with a form which contains an input of type file, a submit button and an <img> for displaying the image. I have also created an id variable in PHP so that only one image can be associated with one id. This is how profile pictures work.

Note: Add the attribute enctype=”multipart/form-data” to the form.

In the scr attribute of <img>, I have set it to:

<?php echo $currentProfilePic['profilepic'] ?>

We will be creating that variable later in the article.

Here is a basic design that you could start with.



$id = 5;


<!DOCTYPE html>
	<title>Upload Files</title>
	<link rel="stylesheet" href="style.css">

	<div class="container">
		<span class="userId">Id - <?php echo $id; ?></span> 
		<h1>Please upload your an image</h1>
		<form method="post" action="process.php" enctype="multipart/form-data">
			<input type="file" name="profilePic">	
			<input type="submit" name="submit" value="Upload">
			<input type="hidden" name="id" value="<?php echo $id ?>">

		<div class="profilepicture">
			<img src="<?php echo $currentProfilePic['profilepic'] ?>">




body {
    font-family:"Roboto Thin";

.container {
    margin:48px auto;

h1 {

.userId {
    border-radius: 8px;

form {

form input {
    border:1px solid black;

.profilepicture {
    margin: 24px auto;
    padding: 16px;

.profilepicture img {


The DB Class

Now, open the db.php file and in this file, we will write the code for connecting to the database and also performing different operations on the database.

We will write the connection code in the constructor of the DB class that we will create. We will use PDO for the database connection.

Here is my db.php file


class DB {
	private $con;

	public function __construct() {
		try {
			$this->con = new PDO('mysql:host=localhost;dbname=fileuploadtutorial', "root", "");
			$this->con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		} catch (PDOException $e) {
			die("Connection failed. " . $e->getMessage());

	public function insertPic($id, $pic) {
		$query = "INSERT INTO profilepic (id, profilepic) VALUES (:id, :profilePic)";
		$stmt = $this->con->prepare($query);
		$stmt->execute(['profilePic' => $pic, 'id' => $id]);

	public function changePic($id, $pic) {
		$query = "UPDATE profilepic SET profilepic = :profilePic WHERE id = :id";
		$stmt = $this->con->prepare($query);
		$stmt->execute(['profilePic' => $pic, 'id' => $id]);

	public function getProfilePic($id) {
		$query = "SELECT * FROM profilepic WHERE id = :id";
		$stmt = $this->con->prepare($query);
		$stmt->execute(['id' => $id]);

		$data = $stmt->fetch();

		return $data;

Here we have three methods in our DB class: insertPic($id, $pic), changePic($id, $pic) and getProfilePic($id).

The Upload Functionality

Now, we will start writing the code for the image upload functionality.

Here are the things we are doing in the code below:

  • Require the db.php file
  • Instantiate the DB class
  • Check if submit button has been pressed
  • Store the id and profilePic data from the form into $id and $profilePic variables respectively
  • Extract the tmp_name and filetype to $tempFileName and $fileType variables respectively
  • Create a unique file name for the image and store it in $fileName
  • Store the destination path to store the image in $targetPath variable
  • Move the image file to an img/ folder in the project
  • Check if profile picture exists already
  • If it does, delete the previous image and insert the new image path to the database
  • If it doesn’t, just insert the new image path to the database.
  • Return to the index.php file

Some of the built-in functions in PHP that we are using are

  1. move_uploaded_file(): upload the file to a specific folder in your web server.
  2. unlink(): delete the file from the server.
  3. pathinfo(): get details about the file (here we get the file extension)
  4. uniqid(): create a unique id (which we will be using as the image name)

<?php require_once 'db.php';

$db = new DB();

if(isset($_POST['submit'])) {
	$id = $_POST['id'];
	$profilePic = $_FILES['profilePic'];

	$tempFileName = $_FILES['profilePic']['tmp_name'];
	$fileType = pathinfo($_FILES['profilePic']['name'], PATHINFO_EXTENSION);
	$fileName = uniqid('gt-') . '.' . $fileType;

	$targetPath = "img/" . $fileName;

	$data = checkExistingPic($id, $db);

	if(move_uploaded_file($tempFileName, $targetPath)) {
		if(!$data) {
			$db->insertPic($id, $targetPath);
			header("Location: index.php");
		else {
			$db->changePic($id, $targetPath);
			header("Location: index.php");
	} else {
		echo "Problem with copying image";

function checkExistingPic($id, $db) {
	return $db->getProfilePic($id);


Display The Image

Now, the last thing you need to do is to display the image in the index.php file. So, add the following PHP code at the beginning of the file.

require_once 'db.php';

$db = new DB();
$currentProfilePic = $db->getProfilePic($id);

Now you will be able to see the profile picture that you have uploaded for a particular id. You can try changing the id in the index.php file and upload profile pictures for different ids.


I hope this article will help you deal with image uploads in PHP. You can use the code from this article and come up with your own use cases. If you liked this article please share it around. If you have any doubts you can ask in the comments below.

Spread the love

Share Your Thoughts

Your email address will not be published. All fields are required.