06May2011
Author
Dave
Category
PHP
Tags
,
upload images through a simple form Thumbnail

upload images through a simple form

This tutorial will show you how to upload an image and give it a name in a simple form

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:

<?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.");
}
 
?>
 
<p>Check to see if the form has been submitted if so then run the code</p>
 
<pre lang="php">
// 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" <?php if (isset($error)){ echo "value="$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, imgPath) 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" <?php if (isset($error)){ echo "value="$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>
Author
Dave

About the Author

has written 72 articles on Dave is my name.

My name is David Carr I'm a PHP web developer based in Hull it is my passion to design and develop clean, accessible and usable websites using PHP and other web technologies, I'm an avid Twitter user why not follow me? https://twitter.com/daveismynamecom

Visit this author's website   ·   View more posts by

Sharing is caring.
  • Subscribe to our feed
  • Share this post on Delicious
  • StumbleUpon this post
  • Share this post on Digg
  • Tweet about this post
  • Share this post on Mixx
  • Share this post on Technorati
  • Share this post on Facebook
  • Share this post on NewsVine
  • Share this post on Reddit
  • Share this post on Google
  • Share this post on LinkedIn

Discussion

No responses to "upload images through a simple form"

There are no comments yet, add one below.

Leave a Comment