In this tutorial you will learn about the PHP File Uploading and its application with practical example.
PHP built in support for you to upload files using a HTML form from your web page directly to the server. There are few things that need to do to make it working – page with web form, uploading script, folder on your server with permission set to be able to write in it.
1 2 3 4 |
<form action="upload.php" method="post" enctype="multipart/form-data"> File: <input type="file" name="filename" /> <input type="submit" value="Upload" /> </form> |
The most important about the form is that you should make it uses POST and not GET method and also you should use enctype=”multipart/form-data” so it knows that a file will be transferred.
Now we need to make a folder (names ‘uploads’) on our web server and set its permissions to 777 so the upload.php script that we will do is able to write the file in it.
Code for “upload.php”
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php $folder = "uploads"; if (is_uploaded_file($_FILES['filename']['tmp_name'])) { if (move_uploaded_file($_FILES['filename']['tmp_name'], $folder."/".$_FILES['filename']['name'])) { Echo "File uploaded"; } else { Echo "File not moved to destination folder. Check permissions"; }; } else { Echo "File is not uploaded."; }; ?> |
Now, I will explain what the above code do. When, a file is uploaded it is first given a temp filename and then put in the temp folder of your web server. That temp filename is accessible using the global $_FILES array variable. On our web form we have our browse field named “filename” (<input type=”file” name=”filename” />), so the name of that temp file is:
1 |
$_FILES['filename']['tmp_name'] |
The real name of the file being uploaded is stored in another variable called $_FILES[‘filename’][‘name’]. As you can see this just another array element named “name” in the $_FILES[‘filename’] array.
Now after having that file upload in our web server temp folder we need to move it to the folder specified $folder=“uploads”. This is done using the move_uploaded_file() function.
1 2 |
move_uploaded_file($_FILES['filename']['tmp_name'], $folder.$_FILES['filename']['name']) |
the first parameter that it takes is the temp filename and the second parameter is the destination folder and filename. If it successfully moves the temp file to the folder that we want it returns TRUE and we made it print “File uploaded” message on the screen.