-2

I want to only upload a file with extension name .mp3.

I tried to upload file with this code:

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";
}

What's wrong with my code?

k0pernikus
  • 60,309
  • 67
  • 216
  • 347
Swister
  • 51
  • 1
  • 6

3 Answers3

0

Try below code:

$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";
}

This should work. Make sure about proper value into $_FILES["file"]["name"]

You can also use pathinfo(). For example:

$path_parts = pathinfo($_FILES["file"]["name"]);
$extension = $path_parts['extension'];
AddWeb Solution Pvt Ltd
  • 21,025
  • 5
  • 26
  • 57
  • 2
    Why should the OP "try this"? A ***good answer*** will always have an explanation of what was done and why it was done that way, not only for the OP but for future visitors to SO. – Jay Blanchard Jan 20 '16 at 13:28
0

This seems to be a case of string case comparison. Comparing in lower or upper format should work.

$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";
}
Rahul Kate
  • 700
  • 1
  • 5
  • 10
  • 1
    Why should the OP "try this"? A ***good answer*** will always have an explanation of what was done and why it was done that way, not only for the OP but for future visitors to SO. – Jay Blanchard Jan 20 '16 at 13:29
  • Well perhaps I thought the character comparison might be the issue here. And I have explained what I am trying to suggest. I will try to be more specific in future. I am a newbie to StackOverflow so please bare with me. – Rahul Kate Jan 20 '16 at 13:31
0

I think OP has missed the form type in the form tag. Below is the tested code:

<?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>
Devendra Soni
  • 391
  • 2
  • 11