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, first you’ll need a database table to store the title and path to the image, create the following structure in phpmyadmin:
|
1 2 3 4 5 |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?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."); } ?> |
Check to see if the form has been submitted if so then run the code
|
1 2 |
// 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
|
1 2 3 4 5 |
// 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:
|
1 2 |
// 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
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// 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
|
1 |
if (!$error) { |
Next get the title from the form and remove any tags and make it safe for database entry:
|
1 2 3 4 5 6 7 8 |
// 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.
|
1 2 3 4 5 6 7 8 |
// 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
|
1 2 3 4 5 6 7 8 9 10 11 |
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.
|
1 2 3 4 5 |
<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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
<?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" 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> |