0

Is the way i am handling image uploads secure? Is there ANY way someone could upload a .php file, or some other file which can somehow execute php code (even if the attacker would know the actual file path after the upload?)

function random($longueur = 10)
  {
    return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($longueur/strlen($x)) )),1,$longueur);
  } 

  $random = random(5);

  //POST DATA
  $img_name = htmlspecialchars($_POST["img_name"]);

  //IMAGE
  mkdir('../../assets/images/'.$random.'/');
  $target_dir = '../../assets/images/'.$random.'/';
  $target_file = $target_dir . basename($_FILES["img_src"]["name"]);
  $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

  //ARRAY EXTENSION GOOD
  $extension_autorisee = array('.png', '.jpg', '.jpeg', 'png', 'jpg', 'jpeg');

  if (in_array($imageFileType, $extension_autorisee)){

  //MOVE IMAGE
  move_uploaded_file($_FILES["img_src"]["tmp_name"], $target_file);
  $filename = $random."/".$_FILES['img_src']['name'];

  }
gitrit
  • 1
  • These days, I prefer to store this kind of files seperatly to the application files, eg on cloud hosted solutions like Amazon S3 or in a MySQL database itself. For your situation, ensure PHP can't be executed within the upload folder, I would also avoid using the user provided filename for the name on disk, aka don't use `$_FILES['img_src']['name']` when writing to the file system or at least put it through validation/filterting. – Scuzzy Aug 25 '19 at 10:33

1 Answers1

0

It appears reasonably secure, the only thing is that it doesn't check MIME types. I don't really know for what purpose you are storing these files and most modern browsers will just throw an error when they receive an image with HTML embedded in it, but it's still something to look into.

Also I'm not an expert in cryptography but you might want to look into the "randomness" of that string. This might be a good resource. Cryptographically Secure Random String Function Apart from that it looks fine.

Lightning edit: This kind of questions are, I think, more suited for https://codereview.stackexchange.com/

Joeri
  • 626
  • 5
  • 18