Aug 19, 2011

PHP : Handling file uploads - easy tutorial with example

Handling file uploads with PHP is very easy task and here you will learn how to do it. And because I believe that people learn best with examples lets start with this.
Now lets upload one file to some user directory on a server. Lets create file upload_form.php on our server. It will contain mainly html code:

<form enctype="multipart/form-data" action="upload.php" method="POST">

    File: <input name="ourfile" type="file" />
    <button type="submit">Upload</button>


Its very simple file with only one form. Don’t forget to add enctype="multipart/form-data" to your form when its used for file uploads. In this form we have to fields - the first is our file and the second is the submit button.
Now we need another file upload.php. Here is its content

$dir = '/var/www/files/';

$destinationfile = $dir . basename($_FILES['ourfile']['name']);

if (move_uploaded_file($_FILES['ourfile']['tmp_name'], $destinationfile)) {

   echo "Upload successful!";
} else {
   echo "File attack!\n";


Here we have destination directory for our uploads - $dir = '/var/www/files/'. Our file will be saved in this directory and will have the name of the uploaded file.
The function move_uploaded_file checks if the file (first parameter) is a valid uploaded file and if its valid it moves it to $destinationfile. If you just want to check the file without moving it use is_uploaded_file instead.
And that’s all. Now if you have done everything the right way you must see “Upload successful!” when you use upload_file.php and upload file.

The original of this tutorial is here

No comments:

Popular Posts