phparrayswhitelist

Determine if a string value exists in a whitelist array


I have code:

$acceptFormat = array(
  'jpg' => 'image/jpeg',
  'jpg' => 'image/jpg',
  'png' => 'image/png'
);

if ($ext != "jpg" && $ext != "jpeg" && $ext != "png") {
  throw new RuntimeException('Invalid file format.');
}

$mime = mime_content_type($_FILES['file']['tmp_name'][$i]);
if ($mime != "image/jpeg" && $mime != "image/jpg" && $mime != "image/png") {
   throw new RuntimeException('Invalid mime format.');
}

I have an $acceptFormat array with allowed file formats and two ify:

  1. if ($ mime! = "Image / jpeg" && $ mime! = "Image / jpg" && $ mime! = "Image / png")

  2. if ($ ext! = "Jpg" && $ ext! = "Jpeg" && $ ext! = "Png")

Is it possible to somehow modify this if to check extensions and mime type based on acceptFormat array?


Solution

  • Try with in_array() , array_keys() for file extension and array_values() for mime value. Let's see,

    <?php
    
    $acceptFormat = array(
      'jpg' => 'image/jpeg',
      'jpg' => 'image/jpg',
      'png' => 'image/png'
    );
    
    $ext ='jpg'; // demo value
    
    if (!in_array($ext,array_keys($acceptFormat))) {
      throw new RuntimeException('Invalid file format.');
    }
    
    $mime = 'video/mkv'; // demo value
    
    if (!in_array($mime,array_values($acceptFormat))) {
       throw new RuntimeException('Invalid mime format.');
    }
    ?>
    

    DEMO: https://3v4l.org/aNdMM