Image Handling using PHP

Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  

A website or webpage without images is dull and will only come alive when images are added to it. While in this tutorial, we will discuss Image Handling using PHP, we discussed Image Handling using HTML in the previous tutorial.

What is PHP?

PHP according to Wikipedia.org “is a server-side scripting language designed for web development but also used as a general-purpose programming language”

As the definition states, PHP is used to program a website directly on the server.

HTML, PHP and Images

HTML programming, on the other hand, works directly on the browser side while PHP deals with servers. If we are using HTML to load images, the images are rendered on the users’ browsers directly. But with PHP, the images are maneuvered at the servers-end before being rendered to the browser for users to view.

Handling Images with PHP

Handling images with PHP is not a Herculean task. But it only requires two things to implement which are:

1) MySQL Credentials (comprising Database and Table) where the image attributes (name, date created, etc.) will be saved, and

2) the PHP code which will store and fetch images from the database.

But before creating the database, you will need to create a folder to store your image, for instance, images. In my case, my directory listing to the images’ folder looked like this:‘..memorila/images/’

Read Also: Handling Image with HTML

1) Creating MySQL Credentials

First of all, you will need to create a MySQL database on your live or local server. For this example, we will create a memotest database. [If you don’t know how to create a database, drop a comment at the comment section so that I will make a post about it.]

Afterwards, you will then need to create a MySQL table. Creating a MySQL table could be done directly on the MySQL Server or dynamically using a PHP Code. The two methods are explained below:

>> To create the MySQL table directly, follow the steps below:

a. Go to MySQL console.
b. Next, create database memotest.
c. Now you need to create a table for storing image info. For this, type the following on the SQL tab. Afterwards, click on GO.

CREATE TABLE IF NOT EXISTS images(
image_id INT(11) NOT NULL PRIMARY key AUTO_INCREMENT,
image_caption VARCHAR(255) NOT NULL,
image_username VARCHAR(255) NOT NULL,
image_date DATE not null);

d. Now the table has been created and ready to use.

>> To create the MySQL table using a PHP code, do as follow:

Create a PHP file and name it create_images_table.php and type the codes that follow. But before the php file, make sure you have created your database (for example, memotest) and create a user with all privileges. [Don’t understand this point? Ask at comment side]

<?php
$link = mysql_connect(“localhost”, “barkalife”, “2jDeBsdBKUsB7K4F”)
or die (“Could not connect”.mysql_error());
mysql_select_db(“memotest”,$link) or die(mysql_error());

$sql = “CREATE TABLE IF NOT EXISTS images (
image_id INT (11) NOT NULL PRIMARY key AUTO_INCREMENT,
image_caption VARCHAR (255) NOT NULL,
image_username VARCHAR (255) NOT NULL,
image_date DATE not null)”;

$results = mysql_query($sql) or die(mysql_error());
echo “Table for storing images create successfully”;

?>

Comment

The mysql_connect function connects you with the server, while the mysql_select_db select the database you created. All other functions create the attributes of the table and if everything is okay, display a success message.

 

2) Now, we need to create the interface that will upload the image to our servers. And if this action is successful, we could then go ahead to manipulate the image as we wish (for instance, displaying it afterwards).

Here is how we do it:

First: Create a simple form to upload the image

This is how you create a form to upload an image to server space. Type in the following codes:

<html>
<head>
<title>Upload your picture</title>
</head>
<body>
<form name=”form1″ action=”check_image.php” enctype=”multipart/form-data” method=”post”>
Image Caption: <input type=”text” name=”image_caption” id=”image_caption”><br>
Username: <input type=”text” name=”image_username” id=”image_username”><br>
Upload Image:<input type=”file” name=”image_filename” id=”image_filename”><br>
<input type=”submit” name=”submit” value=”Upload”>
</form>
</body>
</html>

 

Save the file as upload_image.php.

When this file is rendered, you will get something like the following:

Upload Image
Upload Image

If the Upload button is clicked, the form action will launch the check_image.php file. Hence, we need to create the check_image.php file which will after ascertaining that an image has been attached, send it to the server.

If you got something similar to what is obtained above, you are good to go! Now, let’s move to the next stage!!

Second: Creating check_image.php file

Now, we are going to dig deeper. Type the following php codes and save the file as check_image.php:

<html>
<head>
</head>
<body>

<?php
$link = mysql_connect(“localhost”, “barkalife”, “2jDeBsdBKUsB7K4F”) or die(“Could not connect now!”);
mysql_select_db(“memotest”) or die(“Database not found”);
$image_caption = $_POST[‘image_caption’];
$image_username = $_POST[‘image_username’];
$image_tmpname = $_FILES[‘image_filename’][‘name’];
$today = date(“Y-m-d”);

$imgdir = “../memorila/images/”;
$imgname = $imgdir.$image_tmpname;
if(move_uploaded_file($_FILES[‘image_filename’][‘tmp_name’],$imgname))
{
list($width,$height,$type,$attr)=getimagesize($imgname);
switch($type)
{
case 1:
$ext = “.gif”; break;
case 2:
$ext = “.jpg”; break;
case 3:
$ext = “.png”; break;
default:
echo “Not acceptable format of image”;

}
$insert = “insert into images (image_caption, image_username, image_date)
values (‘$image_caption’, ‘$image_username’, ‘$today’)”;
$insertresults = mysql_query($insert) or die(mysql_error());

$last_pic_id = mysql_insert_id();

echo “Here is your picture: <br>”;
echo “<img src=”.$imgname.” align= ‘left’>”;
}

?>

</body>
</html>

When I did this, I got the following as my final output:

Image uploaded
Image uploaded

Explanation

>> The mysql_select_db selects the database from the server that mysql_connect connected to using the database credentials (server, username, password).
>>$image_caption, $image_username, $image_tmpname and $today are variable names that store information entered into the upload_image.php form.You will need to filter these information entered through the website to guard against SQL injections [That is a subject for another post].
>>You use $imgdir to define the path to the folder you created where images will be uploaded to.
>>$ext affixes the proper image extension to the filename of the image.
>>mysql_query() calls and execute the $insert query that stores the image’s caption, username and date into the SQL database
>>Finally, you display the image with the echo statements.

Finally…

This is not all you need to know about Image Handling using PHP because this is just the tip of the iceberg. But as we all know, “the journey of a thousand miles starts with a single step”. And here, you have made the first effort. Wishing you all the best in the wonderful journey of image handling using PHP!

If you didn’t get something similar or you encountered a problem while trying the examples or you need more explanations, or want to guide us more, please leave a comment in the space provided below. I will take it up from there!

Lastly….and not the least…..

If you loved this post, feel free to share it to your contacts. By doing so, you have helped in spreading information and that will serve as a motivation for us to do more!

See you in our next post! Love you:)

Similar post>> Handling Image with HTML

  •  
  •  
  •  
  •  
  •  
  •  
  •  

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.