Left Quote    Maybe this world is another planet's Hell.
- Aldous Huxley    
Right Quote
[login] | [Register]

Uploading Image Files with PHP

by: bs0d
Page: 4 of 5
(View All)

Rename the Image and Store It

This is the heart of the script that all other segments of code has lead to. Before storing the file, you as the reader need to decide how you would like to name the file. Several options exist, but they are conditional to your intentions. If you plan on multiple users uploading multiple files then each image name must be unique. If a user will only upload one file, say for an AVATAR in the forums, then you can name the image as their username if you like and be done with it.

You do not want to allow the user to control the name of the file, and upload it directly to your site. This can cause problems, as the user can have a filename that includes something like: "../../" which could be potentially malicious or cause multiple complications with your database. So come up with a way you would like to name the file yourself.

The code in this article will be aimed towards a scenario where a user can upload multiple files. In this case, you can create an "images" table in your database with the following fields:
  1. ID: primary key & auto_increment field.
  2. user_id: ID of the user (assuming you have implemented a Members System).
  3. image_name: The name you decide for the image.
  4. user_images: This would maintain a count of the number of images the user has uploaded.
For quick reference, the SQL to create the table mentioned above:

With the table created, you can store the appropriate values for image uploads from the subject script into your database. One method that can be utilized in order to name the file would be a combination of the username and number of user images. The code below will follow this method:

Lets walk through the code. In the first line, we base all actions on the is_uploaded_file() function. This function tells PHP if an image was uploaded (temporarily) via HTTP POST. With in this condition, the maximum number of images is queried from the table outlined in the code sample above. Next, another condition gets the number we will use for the filename. If none exist, then the $image_number variable will equal one (1). If previous images exist, the maximum number is incremented by one (1) and that will be the number utilized for the current upload.

The $filename variable combines the username and new image number. Finally, the one line of code that performs the actual upload. From within an IF condition, the move_uploaded_file() function will take the uploaded file specified (must be valid, aka through HTTP POST) and move it to the specified destination. Of course, the comma (,) separates the two parameters.

As you can see in the destination part of the move_uploaded_file() function, you must use the absolute path to the file (document root). You can just specify a URL, that just doesn't make much sense. Also, remember $ext from the "Check File Extension" part of the article? We use it here to append to the filename.

Note:If the filename already exists, the existing image will be overwritten by the new image. This is why its important to use a unique naming system if you elect to upload multiple files for multiple users.

If the upload was a success, the condition will return TRUE and the "file uploaded successfully" line will be displayed. If not, the function will return FALSE, and the "error occurred while uploading" message will be displayed.

1  |  2  |  3  |  4  |  5  |  
Next »


  Subject: "image data into database??" Date: Apr 04 2008 at 12:17 pm    
Hey, cheers for this tutorial, its awesome!!

I have one question, regarding entering the data of the image into the database, there isn't any sql code in the tutorial to show how to do this...have you missed it out?

i mean, if you have, i know the sql in order to do this, but where would i put it? because you have the sql to select the number of image for a user, given their 'user_id'.

But if it the first time the user posts an image, they are not yet going to have a record on the image table, is that right?

I ahve a memebers table which has the user_id field, auto-incremente d, with a session created for this when logging in to my system. When my user resgiters do i need to create a record for them in the images table, and how do i do this?? is it to do with foreign keys between the tables or something?

Sorry, bit unsure on this, dont want to go ahead and try stuff and ruin all my code.....

  Subject: "RE: Image data into database???" Date: Apr 05 2008 at 3:36 am    

I was kind of vague on this because it depends on your setup how you decide to do it. One thing though you should establish an image naming convention like username + image number. If you have an images table, query it to see how many images they already have. Then excecute an insert query with the image name ($filename) where username = user signed in. Pretty straight forward. If you want to discuss details, lets do that in the forums, Thanks.
  Subject: "problem with code" Date: May 20 2008 at 8:02 pm    
Hey, i tried using your code and I keep getting a 500 error code.... have any ideas where it is?
if(isset($_POST ['submit'])) { //see if submit button is pressed.

//check if they decided to upload a pic:
if($_FILES['us erfile']['siz e'] > 1) {

$max_size = 100000;

$info = getimagesize($_ FILES['userfil e']['tmp_name ']);
//check file-size (in bytes):
if(($_FILES['u serfile']['si ze'] > $_POST['MAX_FI LE_SIZE']) || ($_FILES['user file']['size '] > $max_size)) {
die("< BR><BR> ;Error: Upload file size too large: (<b>&quo t; . $_FILES['userf ile']['size' ] . "</b&g t;). Must not exceed 2 megabytes.&quo t;);

//check the extension.
$array = explode(" .", $_FILES['userf ile']['name' ]);
$nr = count($array);
$ext = $array[$nr-1];< br /> if(($ext !="jpg&q uot;) && ($ext !="jpeg& quot;) && ($ext !="png&q uot;))
die("< BR><BR> ;Error: file extension un-recognized. Be sure your image follows the correct extension (.JPG or .PNG)");< br />
//CHECK TYPE: (what the browser sent)
if(($_FILES['u serfile']['ty pe'] != "image/jp eg") && ($_FILES['user file']['type '] != "image/pj peg") && ($_FILES['user file']['type '] != "image/pn g")) {
die("< ;BR><BR&g t;Error: Upload file type un-recognized. Only .JPG or .PNG images allowed." );

//DOUBLE CHECK TYPE: if image MIME type from GD getimagesize() -In case it was a FAKE!
if(($info['mim e'] != "image/jp eg") && ($info['mime' ] != "image/pj peg") && ($info['mime' ] != "image/pn g")) {
die("< ;BR><BR&g t;Error: Upload file type un-recognized. Only .JPG or .PNG images allowed." );

//rename file, move it to location.
if(is_uploaded_ file($_FILES[' userfile']['t mp_name']))

//get max number of images the user has uploaded
$m = mysql_query(&q uot;SELECT max(user_images ) as `total_images` FROM `images` WHERE `user_id` = '".$_SES SION['user_id ']."'&q uot;);
if(!$m) die('An Error Occurred.'){ $result = mysql_fetch_obj ect($m);
if($result-> total_images <= 0) {
$image_number = 1;
} else {
$image_number = $result->tot al_images + 1;
} //end if

$filename = strtolower($_SE SSION['usernam e']) . $image_number;< br />
if(move_uploade d_file($_FILES[ 'userfile'][ 'tmp_name'] , $_SERVER['DOCU MENT_ROOT'].& quot;/removed for privacy/" .$filename . '.' . $ext)) {
echo("Fil e uploaded successfully.& quot;);
} else {
echo("An error occurred while uploading.&quo t;);
}//end upload
} //end is_uploaded_fil e

} else { //display form

<form enctype=" multipart/form- data" action="$ _SERVER['PHP_S ELF'];" method="p ost" name="upl oadImage" >
<input type="hid den" MAX_UPLOAD_SIZE = "10000&q uot; />
<input type="fil e" name="use rfile" size="35 " />
<input type="sub mit" name="sub mit" value="Up load Image"> ;</form>< br /> } //end else
You Must be logged in or a member to comment.

Tutorial Stats

Tutorial Stats

8 Total Comments
5 Rating of 5 (1 Votes)


Tutorial Options

· Login to Rate This Article
· Login to Post a Comment
· Read more by this author
Digg This Article! Bookmark This Article Reddit: Bookmark This Article BlinkList: Blink This Article! YahooMyWeb BlogMarks: Add This Mark! Furl: Save This Article Spurl: Mark This Article



· Simple PHP Tutorial
· One File Website
· Pagination with PHP
· Building a Comments Script
· Complete Members System
· Variable Scope

"" Copyright © 2002-2020; All rights lefted, all lefts righted.
Privacy Policy  |  Internet Rank