Hey everybody I want to let you know that I have undertaken the grueling task of getting the heck away from WordPress. I was so sick of the problems and updates I had to do all the time. I am now using my ezbloo system and I am integrating all my old posts into the new system. It sucks, but in the end, I will save bundles of time. I needed to keep things simple and that is why I created ezbloo. I'll have more on this later for you guys after I am done with the total integration of my old posts here. So if you are looking for a post and need it faster, shoot me an email and I will make it a priority. [email protected]

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.";
 }
}
?>