File upload with php validation [duplicate]

0

I have a simple upload script of PHP files.

This upload uploads the files, which should be images, to a folder.

I can only accept images jpg , png e gif '.

I just realized that there are images that have upload with exploits , because it is not a valid image.

I'm trying to make more secure file validations for uploading. If it does not pass validation, it should return an error.

I tried to use [type] image/jpg , image/gif , image/png but still managed to do the upload

I also tried using

getimagesize($_FILES["imagem"]["tmp_name"])

But somehow they managed to circumvent it too.

Could anyone help me?

Follow my upload code:

$foto_name=$_FILES["foto"]["name"];
$foto=$_FILES["foto"]["tmp_name"];                
if (preg_match("/(.)+(jpg|JPG|jpeg|JPEG|gif|GIF|png|PNG)/",$foto_name)){                    
  $pieces = explode(".", $foto_name);
  $ext=$pieces[1];
  $tempo=date('YMDHMShms');
  $fot="$foto_name"."$tempo";
  $fot2=md5($fot);
  $fot3= $_SESSION['logadu']['slug']."-$fot2".".$ext";
  @move_uploaded_file("$foto" , "img/$fot3") 
  or exit("<script>window.top.erroimg();</script>");
  img("img/$fot3","640","480");      

  echo "<script>window.top.adicionouimg();</script>";
} else {
  echo "<script>alert('Somente imagens .jpg .gif ou .png');</script>";
}
    
asked by anonymous 20.01.2017 / 15:44

1 answer

1

First I believe you should create a class to manage Upload any file on the system, then you create a function within the class to take care of images. In my class, what allows you to insert only PNG and JPG is this (I have adapted it to your code):

$Upload = false;
switch ($_FILES["foto"]["type"]) {

    case "image/jpg";
    case "image/jpeg";
    case "image/pjpeg";
        $Upload = true;
        break;
    case "image/png";
    case "image/x-png";
        $Upload = true;
        break;
};

if ($Upload) {
    $pieces = explode(".", $foto_name);
    $ext = $pieces[1];
    $tempo = date('YMDHMShms');
    $fot = "$foto_name" . "$tempo";
    $fot2 = md5($fot);
    $fot3 = $_SESSION['logadu']['slug'] . "-$fot2" . ".$ext";
    @move_uploaded_file("$foto", "img/$fot3")
            or exit("<script>window.top.erroimg();</script>");
    img("img/$fot3", "640", "480");

    echo "<script>window.top.adicionouimg();</script>";
} else {
    echo "<script>alert('Somente imagens .jpg .gif ou .png');</script>";
}

If you want to add other types take a look here link . I'd rather use switch because I see better what types I'm allowing, making maintenance easier, but you can use an array instead, then validate with in_array ();

    
20.01.2017 / 16:38