File upload in PHP on Amazon EC2 Linux Server

0
107
PHP

This article explains that how to upload a file to folder in PHP on Linux Server

Follow the steps

  1. Change the setting in configuration of Server in php.ini
nano /etc/php.ini

2. Do the following changes in this file

file_uploads = On
upload_max_filesize = 10M
post_max_size = 10M

By doing these changes, you will be allowed to upload the file with max size of 10MB. by default Max size is set to 2 MB.

3. Create the folder in html directory and change the permission to 777. so files can be uploaded to this folder.

sudo chmod 777 uploads

4. Create the html page with following code.

 <form action="uploadfile.php" method="post" enctype="multipart/form-data">
    Browse File :
    <input type="file" name="uploadfile" >
    <input type="submit" value="Upload File" name="submit">
</form> 

5. Create the uploadfile.php page and paste the following code.

<?php
if(isset($_FILES['uploadfile']))
{
$errors=array();
 $file_name = $_FILES['uploadfile']['name'];
      $file_size = $_FILES['uploadfile']['size'];
      $file_tmp = $_FILES['uploadfile']['tmp_name'];
      $file_type = $_FILES['uploadfile']['type'];
$allowed =  array('pdf','doc' ,'docx'); 
    $ext = pathinfo($file_name, PATHINFO_EXTENSION);
    if(!in_array($ext,$allowed) ) {
        $errors[]='Error';
    }

      	$random=rand(1111,9999);
  	$new_name=$random.$file_name;
      
      if($file_size > 2097152) {
         $errors[]='Error';
      }
   
      if(empty($errors)==true) {
         move_uploaded_file($file_tmp,"uploads/".$new_name);
         echo "Success";
        
      }else{
         print_r($errors);
      }
}
?>

LEAVE A REPLY

Please enter your comment!
Please enter your name here