How to upload file using php

Written By Naveen on Tuesday, November 29, 2011 | 8:21 AM

The following code and functions are used in file upload  and I would these are must for file uploading.


- move_uploaded_file() - using this function we can move the file from temp path to destination path.
- $_FILES -  using this variable we can get the file details.
- enctype="multipart/form-data"  we must need it in the form.
- method="POST" this should be post only.
- <input name="filename" type="file" /> -using this we will get file upload button.

In the HTML body tag write the following code
 <form enctype="multipart/form-data" action="fileupload.php" method="POST">
   Select a file to upload: <input name="filename" type="file" /><br />
   <input type="submit" name='fileupload' value="Upload File" />
</form>
The following code can be in the same file or it can in the action="fileupload.php"
<?php
if($_POST['fileupload']=='Upload File')
{
    $destination_path = "uploads/";
    $destination_path = $destination_path . basename( $_FILES['uploadedfile']['name']); 


    if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $destination_path )) {
        echo "The file ".  basename( $_FILES['uploadedfile']['name']). 
        " has been uploaded";
    } else{
        echo "There was an error uploading the file, please try again!";
    }
}
?>
$_FILES['uploadedfile']['name'] - contains the file name
$_FILES['uploadedfile']['tmp_name'] - contains the server temp path where it has been uploaded
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path) -  this will move the file from temp path to $destination_path


No comments:

Post a Comment