Thursday, October 29, 2015

Apache HTTP Server - Handle POST request

If you already have a Apache HTTP server setup, you can use a PHP script (combine with HTML form) to handle "POST" request from usres. This blog shows a simple implementation.

Initially files are updated into a temp directory which you can configure in your "/etc/php.ini", then it got relocated to a target destination by php script.

Below is an example of php script (http://www.tutorialspoint.com/php/php_file_uploading.htm)that allows "jpeg, jpg, png" file upload.

<?php
   if(isset($_FILES['image'])){
      $errors= array();
      $file_name = $_FILES['image']['name'];
      $file_size =$_FILES['image']['size'];
      $file_tmp =$_FILES['image']['tmp_name'];
      $file_type=$_FILES['image']['type'];
      $file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));

      $expensions= array("jpeg","jpg","png");

      if(in_array($file_ext,$expensions)=== false){
         $errors[]="extension not allowed, please choose a JPEG or PNG file.";
      }

      if($file_size > 2097152){
         $errors[]='File size must be excately 2 MB';
      }
     
      if(empty($errors)==true){
         move_uploaded_file($file_tmp,"images/".$file_name);
         echo "Success";
      }
      else{
         print_r($errors);
      }
   }
?>

<html>
   <body> 
      <form action="" method="POST" enctype="multipart/form-data">
         <input type="file" name="image" />
         <input type="submit"/>   
         <ul>
            <li>Sent file: <?php echo $_FILES['image']['name'];  ?>
            <li>File size: <?php echo $_FILES['image']['size'];  ?>
            <li>File type: <?php echo $_FILES['image']['type'] ?>
         </ul>  
      </form>  
   </body>
</html>

For a successfuly upload, it produces the following results:
Success

Sent file: games.jpg
File size: 33562
File type: image/jpeg

You need to create a "images" directory where upload_img.php resides. In my case is "/var/www/html"
# ls /var/www/html/
images  index.htm  upload_img.php

Assume your HTTP server is 192.169.0.2, you can use the following curl command to test:
# curl --form image=@test1.jpg  http://192.168.0.2/upload_img.php
Success<html>
   <body>
      <form action="" method="POST" enctype="multipart/form-data">
         <input type="file" name="image" />
         <input type="submit"/>
         <ul>
            <li>Sent file: test1.jpg            <li>File size: 22            <li>File type: image/jpeg         </ul>
      </form>
   </body>
</html>


# ll /var/www/html/images/
total 22
-rw-r--r--. 1 apache apache    22 Oct 29 15:21 test1.jpg

You can use "--form username=" etc for other form parameters.

No comments: