|
|
|
$$::
Create File-Upload website using PHP:
This exclusive tutorial will show you how to write
a PHP
program that can upload images to your web site
and you will learn how to create a library
consists from all uploaded images.
You will learn how to create it by two methods,
the first is that we will create it using
a TEXT file for retrieving and inserting data,
The second is that we will create it
using a database for inserting and retrieving
data. Also you will learn how to authenticate a
web page and locking its contents.
Try The script Here
|
|
|
THE 2nd METHOD:
How to Create it using a database for retrieving and
inserting data. You can
download the script files
from here and test it on your web server.
You can
jump
to the 1st method if you Don't like
MySQL.
What you will learn in this section?
-
You
will learn how to create a table in a
database.
-
You
will learn how to write a script
responsible for inserting, deleting and
retrieving data from a database.
-
You
will learn how to create images library
consists from all images uploaded by the
users.
-
You
will learn how to create admin control
panel to delete any illegal images and
how to authenticate it and block its
contents.
-
You
will learn how to transmit data between
web pages using the hyperlink and getting
those data from the hyperlink.
Firstly:
You
should view this script on a web server or a
local host server in order to understand it .And
for viewing with script without any errors you
must change the variables stored in the
config.php file :
the $root
variable is the path of the "uploads" folder
for example
if you upload our script to
http://www.example.com/script/
you must change the $root to
"http://www.example.com/script/uploads/"
config.php >>>
the $data_server,
$data_user and $data_pw variables stores the
server name, the database user name and the
database user password respectively
STEP:1
Create a
database and name it "upload" and create a table
in it and name it "image_table" which consists
of two fields name the first "id", and the
second "image".
Or instead
of creating the database use the database "upload.sql"
which you will find it when you download the
script files from here.
and then import it from
the server.
We need to
create a form that ask the user to specify an
image to be uploaded .to do that form write the
following script in the
uploadform.php
.
<?
session_start();
$_SESSION['firsttimeupload']= "ok";
?>
<body
bgcolor="#FF6699">
<br />
<br />
<br />
<br />
<center>
<p>Choose the image you want to upload, The
image must be less than 100 kb in size.</p>
<form action="upload.php"
enctype="multipart/form-data"
method="POST">
<p>Select a file:
<input type="file" name="user_file"
size="50">
<br />
<br />
<input type="submit" name="submit"
value="Upload Now" />
</p>
</form>
<br><h2><a href='library.php'>View Images
Library</a></h2>
</center>
NOTE: we use
$_SESSION[] variable to store a value in a session
and in this case we stored the value ((ok)) in the variable ((firsttimeupload))
, And you must enter this part of PHP code at the top of the script and I
will explain why i used the session commands
|
|
|
|
STEP 2 :
Once the user
specify the file and press "upload now" button the
file will be uploaded to the tmp folder of the
server and wait your script to move it to the
permanent place.
we must Know some
things about the uploaded file like its
name, its size and its type and to do that we will
use the
$_FILES [ ] super variable that
stores many information about the file in an array
and we can retrieve them easily
for example :
if we want to get
the file name we will type
$_FILES['user_file']['name']
and if we want to
get the size of the file in bytes we will use
$_FILES['user_file']['size']
NOTE that the
user_file variable is the name of the input located
in the form And NOTE that
$_FILES[]
also does the work of
$_POST[] in retrieving data from a form.
the first chunk of
our script will be
$n=$_FILES['user_file']['name'];
$type=$_FILES['user_file']['type'];
$size=$_FILES['user_file']['size'];
After we get
information we need, we should change the name
of uploaded image to ensure that there is no image
overwriting will be. and also to struggle any
hacking attempts So we want a unique name
for each image.
for that reason I
decided to use the
UNIX time as a name for images
(UNIX time is the time by seconds since1970 and we
can get it by
time( ) function )
$time=time();
$n=$time;
$path="uploads\\". $n;
After that we must
ensure that the file is in an image format and its
size is below 100000 bytes.
NOTE that
when we check the file type by
$_FILES[] it returns
>>> image/file-extension <<< in case of it
was an
image file, for example (image/jpeg)
So to ensure that
the uploaded file is in an image format
we should check the presence of "image" string
in the returned file type and to do that we
will use the
ereg ( ) function.
For moving the
uploaded image from the tmp directory to its
permanent one we will use a PHP function called
move_uploaded_file( ) which receive
two parameter the first one is the current path of the file
and the second is the new path you that want to move
the
image to it.
if
($size<100000 && ereg("image", $type))
{
move_uploaded_file($_FILES['user_file']['tmp_name'],
$path);
/////we
will add other decisions here
}
After that we want
to print the link to the user and view the image to
him So we will put the following code in the previous
if statement code
$root=
"http://localhost/uploadingprog/uploads/";
$path2=$root . $n;
echo "<center>";
echo "<h3>Your Image Link Is: </h3><a
href=$path2>$path2</a><br><br>";
echo "<br>";
echo "<img src=$path2 border='5'></img>";
echo "<center>"
We want to insert the
link of the uploaded image to our data base because we
want to create a library contains all images
uploaded by users and this library will retrieve all
images directories from this database:
$link =
mysql_connect($data_server, $data_user, $data_pw)
or die("couldnt connect to database");
mysql_select_db("upload") or die("Could not
select database");
$query = "INSERT INTO image_table SET image
= '$path2' ";
$result = mysql_query($query);
-
NOTE
:
-
We use
mysql_connect( )
to connect to the database and this function
will receive the connection information
located in the
config.php file. And if the function
couldn't establish the connection , "couldnt
connect to database" will be printed.
-
We use
mysql_select_db( )
to select the database and in this case the
database name is "upload".
-
We use The
mysql_query( ) function to path any query
through the selected database.
-
The
$query variable stores the commands
of the query and our commands tells the
database "upload" that it must
receive the "$path2"
value and put it in the "image"
field located in the "image_table"
table.
|
STEP 3:
Now we want to
put our decisions about any file more than our
size limits and also about any file in any format
rather than image format:
if
($size>100000)
{
echo "ERROR <br> the image size is too big";
}
if (!ereg("image", $type) )
{
echo "ERROR <br> the file is not image<br>";
}
|
STEP 4:
Create The Library
We must establish a
connection to the database and select it then
retrieving data from the
image_table table
$con =
mysql_connect($data_server, $data_user, $data_pw)
or die("couldnt connect to database");
mysql_select_db("upload");
$query = "SELECT image FROM image_table
ORDER BY id";
$result = mysql_query($query);
for
($count=0; $count< mysql_num_rows($result);
$count++)
{
$image = mysql_result($result, $count,
"image");
echo
"<center><img height='200' width='200' src=$image></img><br><br><br></center>";
}
-
Our $query
tells the database to select the
image field
from the image_table
table and order the results by the
id field .
-
We use the
mysql_result( )
function to get the query results and it
receives 3 parameters the first represents
the query, the second represents the number
of the result, the third represent the field
we want to get from. for example if we write
mysql_result($result,
2, "image") it will get one link
which takes number 2 in the results .
Consequently we need a counter to provide
the mysql_result( )
with the numbers to get all results.
So we used the for ( )
loop.
-
The
mysql_num_rows(
) function get the total number of results.
|
STEP 5:Create
admin control panel.
Trivial
peoples may enter your site and upload illegal
images So we need to delete them.We will create
a simple control panel which will display
all uploaded images and a link under each
image, this link will store the information
of the its corresponding image and provide deleting
that image.
We will write
the same code we wrote in the
library.php
to retrieve all images from the database and we
will add a line responsible for printing the
deletion link.
echo "<a
href='deleted.php?name=$image'>delete
this</a>";
NOTE:
the
deleted.php page is
the page that contains the code responsible for
the deletion of the selected image, And the "name"
variable is the variable that will carry the
information of the image a cross the hyperlink
and give that information to to the deletion
code And note that the "name" variable is
disconnected from the name of the page by
"?" and also it is
storing the value of $image
variable which stores the path of the image.
The Deletion
Code:
$illegal_image=
$_GET['name'];
$query2 = "DELETE FROM image_table WHERE
image = '$illegal_image'";
$result2 = mysql_query($query2);
if ($query2) echo "SUCCESSFUL DELETION";
else "there is a problem";
NOTE:
-
we used the
$_GET [ ]
variable to retrieve the value of the "name"
variable from the hyperlink and certainly
the value is the path of the illegal image.
-
The the
code searches the database for the
$illegal_image
and then delete them from the
database.
-
the
WHERE word
means " The row
in which....." .
|
STEP 6:Securing
the admin.php
we must lock
the admin.php by a password and a user name and
to do that we will write this code:
<?
header('WWW-Authenticate:
Basic Realm="admin area"');
header('HTTP/1.0 401 Unauthorized');
?>
this code is
responsible for locking the page unless the
admin supplies the correct username and
password.
After that we
want to store the username and password in the
page. So we will modify the previous code to the
following one
if
(($_SERVER['PHP_AUTH_USER'] != 'myname') ||
($_SERVER['PHP_AUTH_PW'] != 'mypw'))
{
header('WWW-Authenticate: Basic Realm="admin
area"');
header('HTTP/1.0 401 Unauthorized');
print('You must provide the proper
credentials!');
exit;
}
$_SERVER['PHP_AUTH_USER']
and
$_SERVER['PHP_AUTH_PW']
are
variables that responsible for storing and
retrieving the authentication username and
password respectively.
So that the
page will not be unlocked unless the user apply
the username "myname" and the password "mypw".
|
STEP 7:Why we used
that session?!!
if you upload
an image and then refresh the upload.php page
you will find that the uploaded image is
uploaded again and stored in the library.
So what we will
do if a user upload an image and then refreshed
the upload.php page 100 times?!! you will find
that this image was uploaded 100 times and 100
image were add to your library
for that reason
i used the session
in the
uploadform.php page which is the first
page that user will see I created a session and
in it I create a variable named
"firsttimeupload" and stored the value "ok" in
this variable .
in the
upload.php which is the second page we will
check the value of the "firsttimeupload"
whether it is "ok" or not. And if it was "ok" we will
move the image to the permanent folder and write
its path in the text file and then Destroy the
session using
session_destroy
( );
$uploaded =
$_SESSION ['firsttimeupload'];
if ($uploaded == "ok")
{
if ($size <100000 && ereg("image", $type ))
{
/////put the code responsible for moving
file and writing its path in the text.
session_destroy();
}
}
Consequently
when the user refresh the page , the if
statement will search for the value of "firsttimeupload"
and certainly it will not find the session and
then it will not move the image, or write it in
the text file. and it will print a message for
the user tells him that he cant upload the same
image more than one times and he must go back
*(why?? >> to trigger the destroyed session
again)* to select another or the same
image again.
When the user
return to the uploadform.php page the session
will created again with the value "ok";
<?
session_start();
$_SESSION['firsttimeupload']= "ok";
?>
|
|
|
|
|
The End
Dr Smith
urlearn@gmail.com
info@urlearn.com
JUMP
TO THE 1st METHOD
|