简体   繁体   中英

File type check is not working

I have a problem with the file type check when uploading on server. My function is not working as it should. On the server is always uploaded absolutely everything. Please help me

<?php
session_start();
include_once 'dbconnect.php';

if (isset($_POST['ulozitzmeny'])) {

    $valid_mime_types = array(
        "image/gif",
        "image/png",
        "image/jpg",
        "image/jpeg",
    );

    if (in_array($_FILES["file"]["type"], $valid_mime_types)) {

        $file = rand(1000, 100000) . "-" . $_FILES['file']['name'];
        $file_loc = $_FILES['file']['tmp_name'];
        $file_size = $_FILES['file']['size'];
        $file_type = $_FILES['file']['type'];
        $folder = "images";

        $new_size = $file_size / 1024;
        $new_file_name = strtolower($file);
        $final_file = str_replace(' ', '-', $new_file_name);

        if (move_uploaded_file($file_loc, $folder . $final_file)) {
            $sql = "UPDATE users SET file='$file', type='$file_type', size='$file_size' WHERE username = '$_SESSION[user]'";
            mysql_query($sql);
        }
    }else{

        echo 'error';
    }
}
?>

There's a much easier way to validate the type of file being uploaded. Use fileinfo to get the extension of the file being uploaded and then compare against permissible file extensions.

Here's the reference:

Your code should be like this:

// your code

// valid file extensions
$valid_extensions = array("gif", "png", "jpg", "jpeg");

// get the file extension
$ext = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));  // png

// now check against permissible extensions
if(in_array($ext, $valid_extensions)){
    // allowed
}else{
    // not allowed
}

// your code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM