Checking for file extensions can be done in a 3 step process.

Large explosionFirst we check for the characters after the dot. Most file extensions contain three characters but this is not always the case so we must allow for this and find all characters after the last dot.

Once we have the characters after the dot, we need to remember that these characters could contain upper and lowercase letters. Therefore it's important that we always change the case of the characters to either uppercase or lowercase for checking.

Lastly, always use a white list approach and only allow extensions that you are looking for. One of the best ways to do this is to create an array and list all the acceptable file extensions. This will help keep out any unwanted data. Below are the first two steps:

$extension = strtolower(end(explode('.', $file)));

Above is the PHP code that we use to get a lower case extension. We use the explode function which is simply splitting a string into an array. Once we have the array we use the end function which finds the last element of the array. Finally we change the extension found to lowercase which will help in checking.

Once we have found the extension in lowercase, we can check it against acceptable file extensions that we store in an array.

$acceptableFileExtensions = array('jpg', 'jpeg', 'gif', 'png'); if (in_array($extension, $acceptableFileExtensions)) { #code }

If you really want to you could create a global function that contains our three 3 step method to check for file extensions. This function should return true or false depending on if the file extension is valid or invalid.

$acceptable = isFileExtensionValid($file, array('jpg', 'jpeg', 'gif', 'png'));