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:
ID: primary key & auto_increment field.
user_id: ID of the user (assuming you have implemented a Members System).
image_name: The name you decide for the image.
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.
Subject: "image data into
database??"
Date: Apr 04 2008 at 5:17 am
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 04 2008 at 8:36 pm
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 1:02 pm
Hey, i tried
using your code
and I keep
getting a 500
error code....
have any ideas
where it is?
<?php
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) {
//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