如何通过仅允许一个扩展文件来验证上传表单并避免在PHP中重复输入?

时间:2016-09-27 10:36:25

标签: php

我的代码工作正常,但我希望它只允许上传“xls”或“xlsx”。你可以帮助我在我的PHP验证吗?在我的backend.php上的代码中的“”:type“=> $ _FILES ['upload-file'] ['tmp_name']”也在工作,这是文件的文件扩展名,但我没有关于如何在验证中使用它的任何想法。您可以查看下面的示例数组:

 "My sample array"

Array (
    [upload-file] => Array
        (
            [name] => Jellyfish.jpg
            [type] => image/jpeg
            [tmp_name] => C:\xampp\tmp\php222D.tmp
            [error] => 0
            [size] => 775702
        )

)


"My code in the backend.php"
case 'upload-file':
                $folder = time();
                mkdir("path/".$folder);

                $file = "path".DIRECTORY_SEPARATOR.$folder.DIRECTORY_SEPARATOR.$_FILES['upload-file']['name'];

                move_uploaded_file($_FILES['upload-file']['tmp_name'], $file);

                $arr = [ 
                        ":userid" => $_SESSION['loggedIn_PH'][0]['user_id'],
                        ":filename" => $_FILES['upload-file']['name'],
                        ":filelink" => $_FILES['upload-file']['tmp_name'],
                        ":type" => $_FILES['upload-file']['tmp_name']
                ];

                $query = "INSERT INTO file_rec_tbl ( `file_name`, `file_datetime`,`file_link`, `user_id` )
                    VALUES (:filename, '".date('Y-m-d H:i:s')."',:filelink,:userid)";

                $stmt = $con -> prepare( $query );
                $stmt -> execute( $arr );


                // exit(print_r($stmt, true));


            break;

1 个答案:

答案 0 :(得分:1)

$allowed =  array('gif','png' ,'jpg');
$filename = $_FILES['upload-file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) ) {
    echo 'error';
}

试试这段代码......