Lec 15uploading Files Using PHP
Lec 15uploading Files Using PHP
In the previous lecture, we discussed how we can connect a web page with MySQL using PHP.
We also discussed the data insertion using PHP. In this lecture we will learn how we can upload
files to web server in PHP.
1. File uploading in PHP:
Sometimes we need to allow a user to attach some file with the form as input. For example,
while registering a user we can ask the user to attach its picture. The attached file exists at the
client’s machine. To use this attached file we need to have it at the server. For this, the attached
file is transferred from the client’s machine to the server. This process is called file uploading.
$_FILES super global variable: when a user submits a form with an attachment, information
about the attached file is stored in $_FILES super global variable. $_FILES super global variable
contains any item uploaded to the server when the post method is used. Like other super global
variables, $_FILES is also an array type variable and it is created automatically. We can access its
contents on other pages. $_FILES keeps information about the name, size and type of the
attached file.
To allow a user to attach a file with a form, we have to use the post method and set the
enctype attribute of the form tag. The enctype attribute specifies how the form-data should be
encoded when submitting it to the server. The default value of enctype attribute is
‘application/x-www-form-urlencoded’. It means all data is encoded before sending to the
server. When we have to allow a user to attach a file with the form, we don’t encode the data.
Therefore, we have to set the value of enctype attribute to ‘multipart/form-data’; it means no
encoding is performed before sending the data to the server.
Accessing file related information: as we discussed, $_FILES super global array contains
information about the attached files. We can retrieve this information on the action page.
Suppose in a form; we have a field of file type with name ‘pic’ where the user can attach its
picture. When the user submits the form, a field in #_FILES super global variable is created. The
name of the filed will be same as of the input filed in the form that is ‘pic’ in this example. We
can retrieve the name, size and type of the file from $_FILES super global array as
$_FILES[‘pic’][‘name’];
$_FILES[‘pic’][‘type’];
$_FILES[‘pic’][‘size’];
In the following example we create a form where a user can attach its picture. On the action
page we retrieve the information about the user’s attached file.
<html> fileacton.php
<head>
<title>File Uploading</title> <?php
</head>
<body> echo $filename=$_FILES['pic']['name'];
<form id="form1" name="form1"
enctype="multipart/form-data" method="post" echo $size =$_FILES['pic']['size'];
action="fileaction.php">
Please attach your picture: echo $type =$_FILES['pic']['type'];
<input type="file" name="pic" />
<input type="submit" name="Submit"
?>
value="Submit" />
</form>
</body>
</html>
Uploading file: in previous example, we retrieved the information about the user’s attached file
on the action page. To upload this file to the server we use the PHP function
move_uploadded_file(). The syntax of the function is
bool move_uploaded_file ( string $filename , string $destination );
This function checks to ensure that the file designated by filename is a valid upload file
(meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it
will be moved to the filename given by destination.
We can write the file uploading script as
First we identify the file to be uploaded. For this we use tmp_name of the attached file
We define the destination where the file is to be uploaded. This destination consists of
the name of the directory and the file name
Upload the file using move_uploaded_file() function
Following example code uploads the user’s attached file to the ‘uploads’ directory on the server
<html> fileacton.php
<head>
<title>File Uploading</title> <?php
</head> $filename = $_FILES['pic']['name'];
<body> $size = $_FILES['pic']['size'];
<form id="form1" name="form1" $type = $_FILES['pic']['type'];
enctype="multipart/form-data" method="post" $tmpname= $_FILES['pic']['tmp_name'];
action="fileaction.php"> $destination="uploads/"$filename;
Please attach your picture: move_uploaded_file($tmpname,$destination);
<input type="file" name="pic" /> ?>
<input type="submit" name="Submit"
value="Submit" />
</form>
</body>
</html>
Applying restrictions on attached files: We can impose different restriction on attached files.
The most common restrictions are size of the file and the type of the file. In the following
example we check the file size and type before uploading the file
<html> fileacton.php
<head>
<title>File Uploading</title> <?php
</head> $filename = $_FILES['pic']['name'];
<body> $size = $_FILES['pic']['size'];
<form id="form1" name="form1" $type = $_FILES['pic']['type'];
enctype="multipart/form-data" method="post" $tmpname= $_FILES['pic']['tmp_name'];
action="fileaction.php"> $destination="uploads/"$filename;
Please attach your picture: if($size<100000 AND $type=='image/jpeg')
<input type="file" name="pic" /> move_uploaded_file($tmpname,$destination);
<input type="submit" name="Submit" else
value="Submit" /> echo "Invalid File";
</form> ?>
</body>
</html>
File renaming: Sometimes users attach files with same name. When such a file is uploaded to
the server the previous file is overwritten. To avoid such scenario we have to rename the file
before uploading. In the following example we create a random umber and attach this number
with the file name before uploading the file
<html> fileacton.php
<head>
<title>File Uploading</title> <?php
</head> $filename = $_FILES['pic']['name'];
<body> $size = $_FILES['pic']['size'];
<form id="form1" name="form1" $type = $_FILES['pic']['type'];
enctype="multipart/form-data" method="post" $tmpname = $_FILES['pic']
action="fileaction.php"> ['tmp_name'];
Please attach your picture: $destination="uploads/".rand().$filename;
<input type="file" name="pic" /> if($size<100000 AND $type=='image/jpeg')
<input type="submit" name="Submit" move_uploaded_file($tmpname,$destination);
value="Submit" /> else
</form> echo "Invalid File";
</body> ?>
</html>
Storing file reference to database: in the previous section we learnt file uploading. In web
applications, we have to use these uploaded files. For this we have to store reference of the
uploaded file in the database. In the above example, $destination stores the information about
the name and location of the file. We can store this variable in the database as a reference.
In the following example we create a form which asks the users to enter their name, email and
password; and to attach their picture. On the action page we upload the attached file and store
the user’s information in the ‘users’ table in the ‘testdatabase’ database.
<html> reg_action.php
<head> <?php
<title>User Registration Form</title> $name = $_POST['name'];
</head> $email = $_POST['email'];
<body> $password = $_POST['password'];
<form enctype="multipart/form-data" id="form1" $filename =$_FILES['picture']['name'];
name="form1" method="post" $size =$_FILES['picture']['size'];
action="reg_action.php"> $type =$_FILES['picture']['type'];
Name: $tmpname = $_FILES['picture']['tmp_name'];
<input type="text" name="name" /> $destination= "uploads/".rand().$filename;
Email: move_uploaded_file($tmpname,$destination);
<input type="text" name="email" /> mysql_connect("localhost","root","");
Password: mysql_select_db("testdatabase");
<input type="text" name="password" /> $sql="INSERT INTO `testdatabase`.`users`
Your Picture: (`user_Name`, `user_Email`, `user_Password`,
<input type="file" name="picture" /> `user_Picture`)
<input type="submit" name="Submit" VALUES ('$name', '$email', '$password',
value="Register" /> '$destination')";
</form> mysql_query($sql);
</body> header("location:form.php?msg=Recod is added");
</html> ?>
Retrieving data from MySQL using PHP
In previous lecture we discussed one of the basic tasks we perform while working with
database that is data insertion. We have to retrieve this data in order to see/display the stored
information. In this lecture we will learn how to retrieve data from MySQL using PHP.
Selecting data: once we have connected with database, now we have to select the data we
want to read. For selecting the data we use the SQL select instruction. The syntax of select
instruction is given below
SELECT column-name
FROM table-name
For example if we have to select user’s name from the users table, we can do this by
SELECT user_Name
FROM users
In the above example we have selected only one column, If we have to select all of the column
we can do this by
SELECT *
FROM users
Similarly we can select data on the basis of some conditions. For this we use ‘where’ clause in
the select instruction. For example if we want to select the users whose id is greater than four,
we write the following select instruction
SELECT *
FROM users
WHERE user_Id>4
After writing the select instruction, we have to execute this instruction. In the following
example we selected user’s record from users table and assign the result to a variable
<?php
mysql_connect(‘localhost’,’root’,’’);
mysql_select_db(‘testdatabase’);
$sql = ‘select * from users’;
$result = mysql_query($sql);
?>
We can use mysql_num_rows() function to count the number of rows selected by a select
instructions. In the following example we have used this function to count the number of users
exist in the database
<?php
mysql_connect(‘localhost’,’root’,’’);
mysql_select_db(‘testdatabase’);
$sql = ‘select * from users’;
$result = mysql_query($sql);
$users = mysql_num_rows($result);
echo “There are total ”. $users .”users found”;
?>
Data fetching: in the previous example we have selected the data from a table and assigned
this data to a variable. This variable keeps all of the selected rows. We can use
mysql_fetch_array() to fetch one record or row. mysql_fetch_array() function draws one row
and return this row in the form of an array. Values of this array can be accessed either by index
or by name. The name of the column in the table becomes the name of that value in the array.
After fetching the array, we can process the fetched data. In the following example we have
fetched and displayed a record from the $result of the previous example
<?php
mysql_connect(‘localhost’,’root’,’’);
mysql_select_db(‘testdatabase’);
$sql = ‘select * from users’;
$result = mysql_query($sql);
$row=mysql_fetch_array($result)
echo “User name is”.$row[1];
echo “User email is”.$row[2];
?>
In the following example, we have summarized the lecture. We have displayed users from the
users table of testdatabase in tabular form.
<html>
<head>
<title> Retrieving data</title>
</head>
<body>
<?php
mysql_connect(‘localhost’,’root’,’’);
mysql_select_db(‘testdatabase’);
$sql = "select * from users";
$result = mysql_query($sql);
$users= mysql_num_rows($result);
?>
<table border="1">
<trbgcolor="#CCCC00">
<th>User Name</th>
<th>User Email</th>
<th>User Password</th>
<th>User Picture</th>
</tr>
<?php
while($rows=mysql_fetch_array($result))
{
?>
<trbgcolor="#CCCCCC">
<td><?php echo $rows[1]; ?></td>
<td><?php echo $rows[2]; ?></td>
<td><?php echo $rows[3]; ?></td>
<td><imgsrc="<?php echo $rows[4]; ?>" height="100" width="100"></td>
</tr>
<?php
}
?>
</table>
</body>
</html>