12/02/2018 5:08 WIB | Function
Correct Way TO Upload Image To Server

This article show you how to upload image and store data to database safely. That mean, avoid intruder upload shell file to server.

I Found, many site, that related to goverment site, has upload form that allow to upload php file. This is dangerous, hacker can upload shell file to break security.

Basically, when upload image, code must examined what file that being uploaded.
1. We only allow image file like jpg, png or jpeg.
2. file size not more than 2 MB (for example)
3. we encrypt file name with md5 combined with any string.

In this example, we had a database with following columns:
id, nama, tlp, laporan, namafile

Where
id = auto increament, Interger
nama = varchar (250)
tlp = varchar (16)
laporan = text
namafile = varchar (100)

We need create folder inside file uploader, let say “upload” folder. Make it chmod 777.

And, this The code

<?php
function angkahurupspasisaja( $string ) {
    return preg_replace( "/[^a-z0-9 ]/i", "", $string );
}

$nama = angkahurupspasisaja($_POST['name']);
$tlp = angkahurupspasisaja($_POST['tlp']);
$laporan = $_POST['laporan'];
$foto = $_POST['poto'];

/* connection */
$host = 'localhost';
$db   = 'DB_NAME_HERE';
$user = 'USER_NAME_HERE';
$pass = 'PASSWORD_HERE';
$charset = 'utf8';
    

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES   => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);
GLOBAL $pdo;

/* if photo exist on form upload */
if(isset($_FILES['poto'])){
      $errors= array();
      $namabaru = explode('.',$_FILES['poto']['name']);
     
      $file_size = $_FILES['poto']['size'];
      $file_tmp = $_FILES['poto']['tmp_name'];
      $file_type = $_FILES['poto']['type'];
      $file_ext=strtolower(end(explode('.',$_FILES['poto']['name'])));
      
      $namafile = md5($namabaru[0]).'.'.$file_ext;
      
      $expensions= array("jpeg","jpg","png");
       
      
      if(isset($_FILES['poto']) && $_FILES['poto']['size'] > 0) {
          
            if(in_array($file_ext,$expensions)=== TRUE && $file_size < 2097152){


            $sql = "INSERT INTO pilkada(`id`,`nama`,`tlp`,`laporan`,`foto`) VALUES('?','$nama','$tlp','$laporan','$namafile')";
            $q = $pdo->query($sql);
            if($q)
                {
                echo "Thanks data geus abus";
                }
                move_uploaded_file($file_tmp,"upload/".$namafile);
            }
            else
                {
                echo "file kegedean";
                }
       
        }
    
    else{
         print_r($errors);
      }
   }

 

?>


Other Topics