Home » PHP » PHP File Upload Example

About Olayemi Odunayo

Olayemi Odunayo
I am a programmer and web developer, who has experience in developing websites and writing desktop and mobile applications. I have worked with both schematic and schemaless databases. I am also familiar with third party API and working with cloud servers. I do programming on the client side with Java, JavaScript, html, Ajax and CSS while I use PHP for server side programming.

PHP File Upload Example

File uploads has now become an integral part of many, if not all social apps (both web apps and mobile apps).

The ability to view, upload and share pictures, videos and other media types are components of a viral social app. For this singular reason most web masters and app developers incorporate file uploads into the social apps they develop.
 
 
 
 
 
 

 
File uploads are also used to collect needed materials from users. File uploads are used in quite a number of different applications (too numerous to mention here). How to add a file upload system into a web app is now an important skill every (PHP) web developer should possess. In this example we are going to learn how to add a file upload mechanism to a website or web app.
For this example we will use:

  • A computer with PHP >= 5.5 installed
  • notepad++

1. Getting Started

File uploads are created with the HTML input tag which is always inside a form tag. We are going to get started by taking a short crash course into HTML forms (what they are and how to effectively use them) if you are already familar with HTML form please skip the next section.

1.1 HTML Forms

HTML forms are created with the opening <form> and closing <form> tag. The form tag defines an html form. Form elements are different, they can be text fields, checkboxes, radio buttons, submit buttons, and more.

An HTML form contains an action and a method attribute. The “action” attribute in a form tag tells the form where to submit its content while the “method” attribute lets the form know which method to use when transmitting its content. The method attribute can either be GET or POST.

Some attributes of the GET method are:

  • The get method is visible to everyone
  • The GET method sends encoded user information appended to the page. e.g http://www.server.com/index.htm?name1=value
  • The GET method has a limitation of about 2000 characters
  • The GET method should never be used to transmit sensitive information(e.g passwords)
  • PHP provides $_GET associative array to access all the data sent using GET method.

Some attributes of the POST method are:

  • Information sent with POST is invisible to others
  • It has no limitations on data size
  • PHP provides $_POST associative array to access all the information sent using POST method

We have learnt how to create HTML forms and how data in HTML forms are sent to the server. How do we write a script that handles and manipulates the form data when it arrives at the server?
First of all, the form action attribute needs to contain the URL of the PHP script that will handle the form. e.g < form action="index.php" method ="post" >. Next we need to create the form handler ( e.g index.php ).

When the form data gets to the server the script “index.php” is called. The script then needs to read the form data and act on it. We use $_GET and $_POST superglobal arrays to read data sent to the server.
$_GET: Contains a list of all the field names and values sent by a form using the GET method.
$_POST: Contains a list of all the field names and values sent by a form using the POST method.

For example we have created a form using the GET method and the form contains a text field
< input type=text name=text >.
We can access the data in this form field by using the $_GET superglobal array
$text=$_GET["text"];

index.html

 
<?php
<!DOCTYPE html> 
 <html lang="en"> 
 <head>    
 <title>Programming Club Membership Form</title>     
</head>
 <body>    
 <h1>  Programming Club Membership Form </h1>
    <p>Thanks for choosing to join our Programming Language Club.</p>
	
	
    <form action=index.php method=post>   
	<div style="width: 30em;" >
        <label for=firstName> First name </label> <br>        <input type=text name=firstName id=firstName required /> <br> <br>
        <label for=lastName> Last name </label> <br>       <input type=text name=lastName id=lastName  required/> <br> <br>
        <label for=password1> Choose a password </label> <br>       <input type=password name=password1 id=password1 required /> <br>  <br>  
		<label for=password2> Retype password </label><br>        <input type=password name=password2 id=password2 required /> <br> <br>
        <label for=genderMale> Are you male... </label>        <input type=radio name=gender id=genderMale value=Male />       
		<label for=genderFemale>...or female?</label> <input type=radio name=gender id=genderFemale value=Female checked /> <br> <br>
        <label for=favoriteWidget> What's your favorite programming language? </label>        <select name=favoriteWidget id=favoriteWidget size=1>        
		<option value=java> Java </option>     
		<option value=php> PHP </option>          
		<option value=phyton> PHYTON </option>     
		</select> <br> <br>
        <label for=newsletter> Do you want to receive our newsletter? </label>        
		<input type=checkbox name=newsletter id=newsletter value=yes /> <br> <br>
        <label for=comments> Any comments? </label>       
		<textarea name=comments id=comments rows=4 cols=50> </textarea>
        <div style=”clear: both;”>         
	<input type=submit name=submitButton id=submitButton value=Send Details />       
	<input type=reset name=resetButton id=resetButton value="Reset Form" style="margin-right: 20px;" />      
	</div>     
	</div>
	
	</form>
  </body> 
</html>

The script above is a typical example of an HTML form. I particularly love it because it features different elements that can be used in an html form.

1.2 PHP File Upload

To get started with file uploads, make sure PHP is configured to allow file uploads. In your php.ini file search for file_upload and set it to on. If you dont know how to locate your php.ini file just create a script and add the line below to it.

<?php

echo phpinfo();

?>

The above code prints out the PHP information for your server. Check the section named “loaded configuration file” you will see the path to the php.ini file.

index.html

 

<!DOCTYPE html>
<html>
<body>
<form action ="file.php" method ="post" enctype ="multipart/form-data">
<label for=firstName> Select the image to upload: </label> <br> <br>
<input type="file" name="fileToUpload" id ="fileToUpload"> <br> <br>
<input type="submit" value ="Upload Image" name="submit"> <br>
</form>
</body>
</html>

In the HTML file above, we create an HTML form that allows users to upload and submit a file. The HTML file displays an upload file button and a submit button.

Some rules that must be followed for the HTML form above to work are:

  • Make sure that the form uses method=”post”
  • The form also needs the following attribute: enctype=”multipart/form-data”. It specifies which content-type to use when submitting the form
    Without the requirements above, the file upload will not work.

Other things to take cognisance of are:

  • The type="file" attribute of the tag shows the input field as a file-select control, with a “Browse” button next to the input control

The form above sends the data inputed by the user to a script named “file.php”

file.php

 
<?php
$save_dir =
"uploads/" ;
$save_file = $save_dir . basename( $_FILES
[ "fileToUpload" ][ "name" ]);
$uploadOk = 1;
$fileType = pathinfo($save_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or  a fake image
if ( isset($_POST
[ "submit" ])) {
$check = getimagesize( $_FILES
[ "fileToUpload" ][ "tmp_name" ]);
if ($check !== false) {//returned a valid image
echo "File is a valid image - " . $check[ "mime" ] . ". <br>" ;
$isuploadok =true ;
} else {//whatever was returned is not a valid image
echo "File is not an image. <br>" ;
$isuploadok = false;
}
}
// Check if file already exists
if (file_exists($save_file)) {
echo "Sorry, file already exists. <br>" ;//the uploaded file already exists on the server
$isuploadok = false;//define error code
}
// Check file size
if ($_FILES
[ "fileToUpload" ][ "size" ] > 500000 ) {//get the file size and check if it too large
echo "Sorry, your file is too large. <br>" ;
$isuploadok = false;
}
// Allow only some certain file formats(jpg, png, jpeg and gif)
if ($fileType !=
"jpg" && $fileType != "png" && $fileType !=
"jpeg"
&& $fileType !=
"gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed. <br>" ;
$isuploadok =false;
}
// 
if (!$isuploadok) {// this upload is not ok there is an error associated with it
echo "Sorry, your file was not uploaded. <br>" ;
// if everything is ok, try to upload file
} else {//upload very ok
if (move_uploaded_file( $_FILES
[ "fileToUpload" ][ "tmp_name" ], $save_file)) {//try to move file
echo "The file " . basename( $_FILES
[ "fileToUpload" ][ "name" ]). " has been uploaded. <br>" ;
} else {//file was not moved successfully
echo "Sorry, there was an error uploading your file. <br>";
}
}
?>

The script above handles data sent from the file upload input.

2. Summary

In this example we learnt about file uploads, and how to handle file upload data with PHP. We also took a very short crash course into HTML forms.

3. Download the source code

Download
You can download the full source code of this example here: fileuploadexample

 

(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
Do you want to know how to develop your skillset to become a Web Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. Building web apps with Node.js
2. HTML5 Programming Cookbook
3. CSS Programming Cookbook
4. AngularJS Programming Cookbook
5. jQuery Programming Cookbook
6. Bootstrap Programming Cookbook
and many more ....
I agree to the Terms and Privacy Policy
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments