Wednesday, December 24, 2014

File Uploading in PHP

Files can be upload using PHP in an HTML form.Firstly the files are uploaded in initial/ temporary folder and later it is relocated to the target defined by PHP script. There are certain criteria for uploading files in PHP like upload_max_filesize. You can find information in the phpinfo.php about file uploads.

Here the example is divided in two parts please carefully go through it to have a proper formulation.
[NOTE : Please create a folder "upload" in your server directory]


PHP Script (upload.php)

 <?php  
 $name = $_FILES['file']['name'];  
 $tmp_name = $_FILES['file']['tmp_name'];  
 if (isset($name)) {  
   if (!empty($name)) {  
     $location = 'upload/';  
     $target_file = $location . $name;  
     if (!file_exists($target_file)) {  
       if (move_uploaded_file($tmp_name, $location . $name)) {  
         echo('uploaded');  
       }  
     }else{  
       echo 'File already exist.';  
     }  
   } else {  
     echo 'please choose a file';  
   }  
 }  
 ?> 


PHP Script (index.php)

 <!DOCTYPE html>  
 <html>  
 <head lang="en">  
   <meta charset="UTF-8">  
   <title>nirajanghimirey's workshop</title>  
 </head>  
 <body>  
 <h3>File Upload:</h3>  
 <form action="upload.php" method="POST" enctype="multipart/form-data">  
   Select file to upload: <input type="file" name="file"><br>  
   <input type="submit" value="Submit">  
 </form>  
 </body>  
 </html> 

No comments:

Post a Comment