Upload images through a simple form

David Carr

Tutorials PHP & MySQL

This tutorial will show you how to upload an image and give it a name in a simple form, first you'll need a database table to store the title and path to the image, create the following structure in phpmyadmin:

CREATE TABLE `images` (
`itemID` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`itemTitle` VARCHAR( 255 ) NOT NULL ,
`itemPath` VARCHAR( 255 ) NOT NULL
) ENGINE = MYISAM ;

Next connect to your database:

//connect to your database here.
// db properties
define('DBHOST','localhost');
define('DBUSER','database username');
define('DBPASS','password');
define('DBNAME','database name');

// make a connection to mysql here
$conn = mysql_connect (DBHOST, DBUSER, DBPASS);
$conn = mysql_select_db (DBNAME);
if(!$conn){
    die( "Sorry! There seems to be a problem connecting to our database.");
}

Check to see if the form has been submitted if so then run the code.

// if form submitted then process form
if (isset($_POST['sub'])){

Check the lengh if the title, if to small or to long generate an error which we will print out later.

// check fields are not empty
$imgTitle = trim($_POST['imgTitle']);
if (strlen($imgTitle) < 1 || strlen($imgTitle) > 255) {
$error[] = 'Title must be at between 1 and 255 characters.';
}

Set a path to store images in:

// location where initial upload will be moved to
$target = "images/" . $_FILES['uploaded']['name'];

Next move the uploaded image from the tmp directory to your chosen destination only if the image is a .gif,.png or ,jpg.

// find the type of image
switch ($_FILES["uploaded"]["type"]) {
case $_FILES["uploaded"]["type"] == "image/gif":
    move_uploaded_file($_FILES["uploaded"]["tmp_name"],$target);
    break;
case $_FILES["uploaded"]["type"] == "image/jpeg":
       move_uploaded_file($_FILES["uploaded"]["tmp_name"],$target);
    break;
case $_FILES["uploaded"]["type"] == "image/pjpeg":
       move_uploaded_file($_FILES["uploaded"]["tmp_name"],$target);
    break;
case $_FILES["uploaded"]["type"] == "image/png":
    move_uploaded_file($_FILES["uploaded"]["tmp_name"],$target);
    break;
case $_FILES["uploaded"]["type"] == "image/x-png":
    move_uploaded_file($_FILES["uploaded"]["tmp_name"],$target);
    break;

default:
    $error[] = 'Wrong image type selected. Only JPG, PNG or GIF accepted!.';
}

If validation is okay then carry on.

if (!$error) {

Next get the title from the form and remove any tags and make it safe for database entry:

 // post form data
 $imgTitle   = $_POST['imgTitle'];

//strip any tags from input
$imgTitle   = strip_tags($imgTitle);

 // remove any harmful code and stop sql injection
 $imgTitle = mysql_real_escape_string($imgTitle);

Next insert the title and image path into the database, show a sucess message and close the 2 if statements.

    // insert data into images table
    $query = mysql_query("INSERT INTO images (itemTitle, itemPath) VALUES ('$imgTitle', '$target')")or die ('Cannot add image because: '. mysql_error());

    // show a message to confirm results
    echo 'Image Added';

}
}

Display any errors:

if (!empty($error))
{
        $i = 0;
        echo "<p><span class='error'>";
        while ($i < count($error)){
        echo $error[$i].'<br />';
        $i ++;}
        echo "</span></p>";
}

Finally the form itself make sure the form has enctype="multipart/form-data" or no upload will happen.

<form enctype="multipart/form-data" action="" method="post">
<p><label>Title:</label> <input name="imgTitle" type="text" size="40" value="<?php if (isset($error)){ echo $imgTitle; }?>" /></p>
<p><label>Image:</label><input name="uploaded" class="text-input" type="file" maxlength="20" value="" /></p>
<p><input type="submit" name="sub" class="button" value="Add Image"></p>
</form>

Here's the full script:

<?php
//connect to your database here.
// db properties
define('DBHOST','localhost');
define('DBUSER','database username');
define('DBPASS','password');
define('DBNAME','database name');

// make a connection to mysql here
$conn = mysql_connect (DBHOST, DBUSER, DBPASS);
$conn = mysql_select_db (DBNAME);
if(!$conn){
    die( "Sorry! There seems to be a problem connecting to our database.");
}

// if form submitted then process form
if (isset($_POST['sub'])){

// check fields are not empty
$imgTitle = trim($_POST['imgTitle']);
if (strlen($imgTitle) < 1 || strlen($imgTitle) > 255) {
$error[] = 'Title must be at between 1 and 255 characters.';
}

// location where initial upload will be moved to
$target = "images/" . $_FILES['uploaded']['name'] ;

// find thevtype of image
switch ($_FILES["uploaded"]["type"]) {
case $_FILES["uploaded"]["type"] == "image/gif":
    move_uploaded_file($_FILES["uploaded"]["tmp_name"],$target);
    break;
case $_FILES["uploaded"]["type"] == "image/jpeg":
       move_uploaded_file($_FILES["uploaded"]["tmp_name"],$target);
    break;
case $_FILES["uploaded"]["type"] == "image/pjpeg":
       move_uploaded_file($_FILES["uploaded"]["tmp_name"],$target);
    break;
case $_FILES["uploaded"]["type"] == "image/png":
    move_uploaded_file($_FILES["uploaded"]["tmp_name"],$target);
    break;
case $_FILES["uploaded"]["type"] == "image/x-png":
    move_uploaded_file($_FILES["uploaded"]["tmp_name"],$target);
    break;

default:
    $error[] = 'Wrong image type selected. Only JPG, PNG or GIF accepted!.';
}

// if validation is okay then carry on
if (!$error) {

    // post form data
    $imgTitle   = $_POST['imgTitle'];

    //strip any tags from input
    $imgTitle   = strip_tags($imgTitle);

    // remove any harhful code and stop sql injection
    $imgTitle = mysql_real_escape_string($imgTitle);

    // insert data into images table
    $query = mysql_query("INSERT INTO images (itemTitle, itemPath) VALUES ('$imgTitle', '$target')")or die ('Cannot add image because: '. mysql_error());

    // show a message to confirm results
    echo 'Image Added';

}
}


//display any errors
if (!empty($error))
{
        $i = 0;
        echo "<p><span class='error'>";
        while ($i < count($error)){
        echo $error[$i].'<br />';
        $i ++;}
        echo "</span></p>";
}

?>

<form enctype="multipart/form-data" action="" method="post">
<p><label>Title:</label> <input name="imgTitle" type="text" size="40" value="<?php if (isset($error)){ echo $imgTitle; }?>" /></p>
<p><label>Image:</label><input name="uploaded" class="text-input" type="file" maxlength="20" value="" /></p>
<p><input type="submit" name="sub" class="button" value="Add Image"></p>
</form>

 

Read articles directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Copyright © 2006 - 2024 DC Blog - All rights reserved.