Skip to content
Advertisement

How to code for file upload with use defined extension using php

i have a main.php file ,in that file i have upload file code

<input type="file" id="uploadfile" value="Upload Key File" name="uploadfile" />

after clicking on submit button it will redirect to mainresult.php in this page i write the logic to save the uploaded file in uploads/ directory and i created this directory where my php files placed.

i kept echo ‘s to debug it from this condition

if(in_array($filetype, $allowed)){ from this condition echo’s not printed

i tried this please help me with this .

<?php
echo "1111";
// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
echo "222";
    // Check if file was uploaded without errors
    if(isset($_FILES["uploadfile"]) && $_FILES["uploadfile"]["error"] == 0){
echo "3333";
        $allowed = array("key");
        $filename = $_FILES["uploadfile"]["name"];
        $filetype = $_FILES["uploadfile"]["type"];
        $filesize = $_FILES["uploadfile"]["size"];

echo "4444";
        // Verify file size - 5MB maximum
        $maxsize = 50000;
        if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");

echo "555";
        // Verify MYME type of the file
        if(in_array($filetype, $allowed)){
echo "666";
            // Check whether file exists before uploading it
            if(file_exists("uploads/" . $filename)){
                echo $filename . " is already exists.";
            } else{
                move_uploaded_file($_FILES["uploadfile"]["tmp_name"], "uploads/" . $filename);
                echo "Your file was uploaded successfully.";
                $uploadstatus = "true";
            }
        } else{
            echo "Error: There was a problem uploading your file. Please try again.";
                $uploadstatus = "false";
        }
    } else{
        echo "Error: " . $_FILES["uploadfile"]["error"];
                $uploadstatus = "error";
    }
echo "000";
}
?>

my file extension is .key (demo.key)

Thank you

Advertisement

Answer

Have you tried echoing out what the contents of $filetype is?

$_FILES["uploadfile"]["type"] will likely contain a mimetype like [type] => text/plain or “application/x-pem-file“.

If you echo out filetype you can see what the mimetype is of the file you are willing to allow.

Be aware that php is not always able to tell the correct mimetype.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement