Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will this only allow certain extensions?

Tags:

php

I found this snippet that says will only allow certain file types. Will it work and could someone bypass it to upload what ever file type they want? And could someone explain the substr part, i don't get how it works..

<?php
function CheckExt($filename, $ext) {
    $name = strtolower($filename);
    if(substr($name, strlen($name) -3, 3) == $ext)
        return true;
    else
        return false;
}
?>
like image 298
Dr Hydralisk Avatar asked Sep 14 '26 10:09

Dr Hydralisk


1 Answers

A better way to check extensions

function checkExt($filename, $ext)
{
  $fnExt = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
  if(!is_array($ext)) {
    $ext = (array)$ext;
  }
  $ext = array_map('strtolower', $ext);
  return in_array($fnExt, $ext);
}

You can then call it like

var_dump(checkExt('test.temp', 'tmp')); // false
var_dump(checkExt('test.temp', array('tmp', 'temp'))); // true

Avoid using substr as the extension length is unknown (you can use substr & strrpos as well but php provides this functionality for you)

like image 71
Ben Rowe Avatar answered Sep 17 '26 01:09

Ben Rowe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!