允许php上传脚本上的所有文件扩展名

时间:2015-10-21 05:51:36

标签: php html file-upload upload

所以我使用的是覆盆子pi,并希望将它用作我可以上传和下载任何类型文件的地方。

这是我的HTML

<!DOCTYPE html>
<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="upload">
</form>

</body>
</html>

这是我的php

<?php  
if(isset($_FILES['file'])) {
    $file = $_FILES['file'];

    $file_name = $file['name'];
    $file_tmp = $file['tmp_name'];
    $file_size = $file['size'];
    $file_error = $file['error'];

    $file_ext = explode('.', $file_name);
    $file_ext = strtolower(end($file_ext));

    $allowed = array('txt', 'jpg');

    if(in_array($file_ext, $allowed)) {
        if($file_error === 0) {
            if($file_size <= 1073741824) {

                $file_name_new = uniqid('', true) . '.' . $file_ext;
                $file_destination = 'files/' . $file_name_new;

                if(move_uploaded_file($file_tmp, $file_destination)) {
                    echo $file_destination;
                }
            }
        }
    }
}

效果很好但只允许我上传.txt和.jpg文件。我试图一起删除“$ allowed”的东西,但打破了脚本。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我认为您应该将代码更改为:

    if($file_error === 0) {
        if($file_size <= 1073741824) {

            $file_name_new = uniqid('', true) . '.' . $file_ext;
            $file_destination = 'files/' . $file_name_new;

            if(move_uploaded_file($file_tmp, $file_destination)) {
                echo $file_destination;
            }
        }
    }