Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to upload a file to hosting server using PHP

In this article we will see how we can upload a file to our hosting server using PHP.

Enabling the clients to upload a file to server can be very useful and fascinating for different sort websites. You may have seen different sort of websites that gives you facility to upload a picture or file while making a profile, submitting your CV (curriculum vita) for job online or doing any other sort of activity that require uploading a file etc. These files when uploaded to servers are stored in specific directories/folders or moved to particular database and are retrieved back for the front end of a website.

In this tutorial we will practically learn how we can enable our client/users to upload files to hosting server/website.

To achieve the above goal we divide our tutorial into two parts.

  • Make an interface for uploading a file.
  • Php script to save and process the file.

Make an interface for uploading a file.

For interface we need to make use of a HTML forms.

Make a new file and name it index.php containing the following code.

Listing 1: index.php

<!DOCTYPE html >
<head>
<title> My website - MrBool tutorial </title>
</head>
<body>
<h1>MrBool tutorial </h1>
<form action="upload.php" method="post" enctype="multipart/form-data">
File name: < input type = "file" name = "userfile" > < br >
< input type="submit" name="submit" value="Submit" >
</form>
 </body>
</html>

Understanding the code in index.php

If we just look at the above code we will come to know that this form contains an extra attribute that is usually not used when we just want to make forms that merely submit the text field values (just as filling signups for Gmail or face book account). The attribute is : enctype="multipart/form-data".

This attribute enctype which is given a value of “multipart/form-data” is used to determine which content type to be used and when the value is given multipart/form-data it means that the data is in binary form.

The files which we are going to upload are also in the binary form.

Next line of code is given below.

<input type = "file" name = "userfile">

The input type is set to file.

Next line of code is given below:

<input type = "submit" name = "submit" value = "Submit">

This is simply submitting button that is used to submit the form, its name and submit attributes are given values.

When the submit button is pressed the form is submitted to page link that is given in the action attribute in this case we have upload.php as given in the code.

action = "upload.php"

Along with this, form has one more attribute that is method, which is assigned Post or Get value which means that data submitted to upload.php is not accessible, it is transferred in the header section and cannot be accessed in the URL .And if “method” is assigned a value of GET the its data can be accessed and seen in the URL, because data is transferred as URL parameter.

Now viewing the index.php file in the browser will give you the following look.

index.php view

Figure 1: index.php view

In above figure on clicking Choose file button will enable you to select any sort of file that you may want to upload to server. Till now we have just provided simple interface for the client so that the desired file can be selected for the upload no further operation is performed only the file can be selected on clicking submit button file is not stored to do this we have to follow second step of our tutorial that is .

Php script to save and process the file.

First of all make a new folder with a name userfile and place this folder in the folder that contains the index.php file. Now make a new file in with name upload.php which contains the following code.

Listing 2 : upload.php

<!DOCTYPE html>
<head>
<title>  My website -  MrBool tutorial </title>
</head>

<body bgcolor = "#99CC99">
<?php
$directory = "./userfiles";

  $File_name = $_FILES["userfile"]["name"];
  $Type  = $_FILES["userfile"]["type"] ;
  $Size   = ($_FILES["userfile"]["size"] / 1024); 
  $File_temp_name  = $_FILES["userfile"]["tmp_name"];
  if($Size<= 0){
	  
	  die('cant not upload a file ');
	  }
if (file_exists($directory . " / " .  $_FILES["userfile"]["name"]))
      {
      die($_FILES["userfile"]["name"] . " already exists. ");
      }

  if(is_uploaded_file($_FILES["userfile"]["tmp_name"])){
	  
	  if(!move_uploaded_file($File_temp_name,$directory."/".$File_name)){
		      die('cant not file'.$File_name);
		  }
	  }
	  else
	  {
	    die('attack on file');
		  }	  
		  echo $File_name . "  is sucessfully uploaded " . " <br/> " ;
		  echo "file size : " .$Size. " <br/> ";
		  echo"type :".$Type." <br/> ";
  
 ?>
</body>
</html>

Understanding the code in upload.php

Let’s look at the first line of code in upload.php.

$directory = "./userfiles";

This is simply assigning a directory name (userfiles) to a variable.

In Php while dealing with files to be uploaded to server we need to understand the concept of Global PHP $_FILES Array.

Global PHP $_FILES Array.

With help of $_FILES we can upload our file to the hosting server.

When a file is uploaded to the sever the $_FILES array contain the following information about the file.

  • Uploaded file name
  • Uploaded file type
  • Uploaded file size
  • Uploaded file temporary location name
  • Uploaded file error

These information can be achieved with help $_FILES array with first parameter being form’s input and second parameter can be either name, size, type, temp_name and error as shown in the code from upload.php. We can assign these information to our desired variable.

$File_name = $_FILES["userfile"]["name"];
$Type = $_FILES["userfile"]["type"] ;
$Size = ($_FILES["userfile"]["size"] / 1024); 
$File_temp_name  = $_FILES["userfile"]["tmp_name";

Here we should know that whenever we try to upload a file it is first saved to tempary location. Its name is randomly specified by php and the location can be set in PHP.ini.

So in order to save this file to a desired location it must be moved from the temporary location and this can be done with help a function that is move_uploaded_file.

Some condition to be checked before uploading a file

Listing 3: Check if the file is empty.

 
 if($Size<= 0){
	  
	  die('cant not upload a file');
	  }

Listing 4: Check weather file already exist or not


if (file_exists($directory ." / ". $_FILES["userfile"]["name"]))
      {
      die($_FILES["userfile"]["name"] . " already exists. ");
      }

The file_exists function checks weather file is already present in the directory or not if file is found the user is displayed a message that the file already exists and the rest of the code dies.

Listing 5: Check weather file is uploaded via http post method.


  if(is_uploaded_file($_FILES["userfile"]["tmp_name"])){
	  
	  if(!move_uploaded_file($File_temp_name,$directory."/".$File_name)){
		      die('cant not file'.$File_name);
		  }
	  }

Copying the file to our desired directory.

This is achieved by move_uploaded_file function.

Listing 6: Check if there is some sort of attack on file.

  else
	{ die('attack on file');
		  }	  

This line of code is executed if the file is not uploaded via http.

The next few line of code show the information about file on the screen along with giving a successful upload message to user so that user get information that the desired file is uploaded successfully.

echo $File_name . “is successfully uploaded " . " <br/> ";
echo "file size : " .$Size. " <br/> ";
echo "type :".$Type." <br/> ";

The information is shown in the figure below.

Result of successfully uploaded

Figure 2: Result of successfully uploaded

Conclusion

This code is simply just suitable to upload files, as we see there are different website they allow only specific type of files to be uploaded and there are also restrictions on the size of the file. So through Php we can imply different sort of restriction on files. For example if you want to restrict user to upload only picture then restriction should be applied on file type i.e. to check the extension of the file weather it is type of file having extension .jpeg or .png etc.



computer science Graduate :Ceo at www.gigsclerk.com (Best Marketplace to Buy and sell service online from 2$-100$ ) and www.trustingeeks.com. Interested in programming, online buissiness. Android development.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login