PHP File Uploading

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.

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”

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:

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.

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.