0

So this is a snip of my current PHP script:

// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
    // Check if file was uploaded without errors
    if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0){
        //$allowed = array("PNG" => "image/png");
        $allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
        $filename = $_FILES["photo"]["name"];
        $filetype = $_FILES["photo"]["type"];
        $filesize = $_FILES["photo"]["size"];
    
        // Verify file extension
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        if(!array_key_exists($ext, $allowed)) die("Error: Choose between .jpg, .jpeg, .gif, .png. Your format is: $ext");

So currently these extensions are allowed: .jpg, .jpeg, .gif, .png. When someone add image with extension image.jpg it works fine, but when trying to save `image.JPG, it doesn't work. How can I fix this?

2 Answers 2

2

Use strtolower() to make what is sent to you, into lower case like the data you are comparing to.

$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
Sign up to request clarification or add additional context in comments.

Comments

1

You can use array_change_key_case() to convert all cases to lower, and check on the lowercase key in array_key_exists(). array_change_key_case() changes all keys to lowercase by default (but you can also change them to uppercase, by supplying the CASE_UPPER to the second argument - CASE_LOWER is default).

This of course means that the key you're looking for, must be lowercase when you're passing it to the first argument of array_key_exists(). You pass a variable through, you can use strtolower() to ensure that it is.

$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists(strtolower($ext), $allowed)) die("Error: Choose between .jpg, .jpeg, .gif, .png. Your format is: $ext");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.