如何上传仅具有特定扩展名的文件?

时间:2016-01-20 13:23:34

标签: php file-upload

我只想上传扩展名为.mp3的文件。

我尝试使用以下代码上传文件:

index.php

<form action="upload.php" method="post" id="myForm" enctype="multipart/form-data">
<label for="file">Filename:</label>

<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" class="btn btn-success" value="Upload Image">
</form>

upload.php

$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ($extension == "mp3"){
    $target = "upload/";
    move_uploaded_file($_FILES["file"]["tmp_name"], $target. $_FILES["file"]["name"]);
}
else {
    echo "Failed";
}

我的代码出了什么问题?

3 个答案:

答案 0 :(得分:0)

尝试以下代码:

$name = $_FILES["file"]["name"];
$extension = end((explode(".", $name))); //extra () to prevent notice

if ($extension == "mp3"){
    $target = "upload/";
    move_uploaded_file($_FILES["file"]["tmp_name"], $target. $_FILES["file"]["name"]);
}
else {
    echo "Failed";
}

这应该有效。确保$_FILES["file"]["name"]

中的值正确

您也可以使用pathinfo()。例如:

$path_parts = pathinfo($_FILES["file"]["name"]);
$extension = $path_parts['extension'];

答案 1 :(得分:0)

这似乎是字符串大小写比较的一种情况。比较低或高格式应该有效。

$temp = end(explode(".", $_FILES["file"]["name"]));
$extension = strtolower($temp);
if ($extension == "mp3"){
    $target = "upload/";
    move_uploaded_file($_FILES["file"]["tmp_name"], $target. $_FILES["file"]["name"]);
}
else {
    echo "Failed";
}

答案 2 :(得分:0)

我认为OP错过了表单标签中的表单类型。以下是经过测试的代码:

<?php
if(!empty($_POST)){
    $temp = explode(".", $_FILES["file"]["name"]);
    $extension = end($temp);
    if ($extension == "mp3"){
        $target = "upload/";
    move_uploaded_file($_FILES["file"]["tmp_name"], $target. $_FILES["file"]["name"]);
    }
    else {  
        echo "Failed";  
    }
}
?>

<form method="post" enctype="multipart/form-data">
<input type='file' name='file'/>
<input type='submit' name='submit'/>
</form>