1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 5.00 out of 5)

Uploading Files With PHP and HTML Forms

This tutorial will show you how to use a form to upload a file with PHP. As discussed in a previous tutorial about HTML5 forms you need to have a form tag that starts and stop everything within your form. However when your are uploading a file you need to add encoding type. The form tag would look something like this.

<form action="uploadfile.php" method="post" enctype="multipart/form-data"></form>

The PHP.ini File *

You would also have to make sure the your php.ini file has file uploads turned on. The way you can do this is create a php file called phpinfo.php. Then put in this PHP function.

<?php phpinfo(); ?>

Lat the phpinfo.php file into your browser and you will see a php information page. Hit control “F” on your keyboard. Type in file_uploads the page will jump to that section. It should read ON. If it does not read ON then your file upload will not work.

Back To The File Upload Form *

We discussed input type heavily on our HTML input type file lesson. This is another input type that you will need when having a use upload a file.

<input type="file" name="fileToUpload" id="fileToUpload">

Complete Example for Form for File Uploads *

<!DOCTYPE html>
<html>
<body>

<form action="uploadfile.php" method="post" enctype="multipart/form-data">
 Select image to upload:
 <input type="file" name="file" id="file">
 <input type="submit" value="Upload File" name="submit">
</form>

</body>
</html>

 

Create and Upload Folder For PHP Processing *

In order for PHP to upload a file you will have to have a folder designated for uploads. Then you will tell PHP where that folder is located so that it can put the files in the right place. To make a directory in terminal you would use the following.

mkdir uploads

The PHP Script for File Uploads *

Here is an example of the PHP script for file uploads.

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if(isset($_POST["submit"])) {
 if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
 echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
 } else {
 echo "Sorry, there was an error uploading your file.";
 }
}
?>

 

Please follow and like us:
Uploading Files With PHP and HTML Forms was last modified: March 7th, 2017 by Maximus Mccullough

Leave a Reply

Your email address will not be published. Required fields are marked *

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