Jump to content

for loop to populate switch statement


doddsey_65

Recommended Posts

i am trying to get the allowed file types from the database into a switch statement but with no luck so far. They types are in the database like: jpg, png, gif. All seperated with a comma and all in one db column. I am then splitting them at the comma and inserting them into $file_list. In the switch statement i want it to be like:

 

switch($ext)
{
case "jpg": case "png": case "gif":
break;
}

 

how can i make this possible? here is my code so far:

 

	
$ext = strtolower(pathinfo($_FILES['Filedata']['name'], PATHINFO_EXTENSION));

$f_types = $f_types_info['file_types'];
$f_types = preg_split("|\,|", $f_types);
$types = count($f_types);
$file_list = "";

for($i=0; $i<$types; $i++)
{
	$file_list .= $f_types[$i];
}

switch ($ext)
{
case $file_list:
break; 
default:
$error = "File Type Not Allowed";
break;
}

Link to comment
https://forums.phpfreaks.com/topic/224589-for-loop-to-populate-switch-statement/
Share on other sites

You're over thinking this.

 

Just use explode to put the allowed filetypes into an array and in_array to see if the extension is valid:

<?php
$ext = strtolower(pathinfo($_FILES['Filedata']['name'], PATHINFO_EXTENSION));
$f_types = explode(',',$f_types_info['file_types']);
$error =  (!in_array($ext,$f_types))?'File Type Not Allowed':'';
?>

 

Ken

You should instead look into in_array(). Makes this very simple:

 


$allowed_exts = array('jpg','png');
$file_ext = 'jpg';

if(!in_array($file_ext, $allowed_exts)){
  $error = "File Type Not Allowed";
}

..ken beat me to it. Well, here's a simple example anyhow.

thanks for the help. I cant get it to work though. It shows an error on allowed extensions.

 

here is the code now:

 

$ext = strtolower(pathinfo($_FILES['Filedata']['name'], PATHINFO_EXTENSION));
$f_types = explode(',',$f_types_info['file_types']);

if (!in_array($ext, $f_types))
{
$error = "File Type (.$ext) Not Allowed<br />Only $f_types[1] are allowed";
}

 

but when i load something with ext .jpg it shows an error even though .jpg is in the array list:

 

content of db table:

 

.jpg, .jpeg, .png, .gif

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.