user1559811
user1559811

Reputation: 449

creating file type condition when uploading files in php

I am using this condition, but it's not working as it is always false i.e no file types meet the condition, so i fighre there must be an error in syntax but I can't figure it out.

if (!($_FILES["uploaded"]["type"] == "video/mp4")
&& (!$_FILES["uploaded"]["type"] == "video/flv")
&& (!$_FILES["uploaded"]["type"] == "video/webm" )
&& (!$_FILES["uploaded"]["type"] == "video/ogg" ))

{
   $message="not an accepted file format";
}    

Upvotes: 0

Views: 424

Answers (3)

hakre
hakre

Reputation: 197554

A common case for in_array:

$type          = $_FILES["uploaded"]["type"];
$allowedTypes  = ["video/mp4", "video/flv", "video/webm", "video/ogg"];
$isRefusedType = !in_array($type, $allowedTypes);
if ($isRefusedType) {
    $message = "not an accepted file format";
}

Or isset against a flipped array:

$type          = $_FILES["uploaded"]["type"];
$allowedTypes  = array_flip(["video/mp4", "video/flv", "video/webm", "video/ogg"]);
$isRefusedType = !isset($allowedTypes[$type]);
if ($isRefusedType) {
    $message = "not an accepted file format";
}

Upvotes: 5

Dan Lugg
Dan Lugg

Reputation: 20592

Longer on a vertical scale, but in my opinion more readable.

switch ($_FILES["uploaded"]["type"]) {
    case "video/webm":
    case "video/mp4":
    case "video/flv":
    case "video/ogg":
        $message = "Okie dokie";
        break;
    default:
        $message = "Invalid format";
}

Upvotes: 2

jeroen
jeroen

Reputation: 91734

if ( !($_FILES["uploaded"]["type"] == "video/mp4"
       || $_FILES["uploaded"]["type"] == "video/flv"
       || $_FILES["uploaded"]["type"] == "video/webm"
       || $_FILES["uploaded"]["type"] == "video/ogg") )
{
   $message="not an accepted file format";
} 

I assume valid means any of these types, so you check for any of these (using or) and than negate it.

Upvotes: 5

Related Questions