Hello fellow programmers,

I've built an upload script that, as usual, verifies if a file extension is allowed. However, the comparison seems to not be working, as it gives me an unhauthorized file trying to be uploaded (when in fact the file has an authorized extension).

If i comment the block below, the upload works fine

Anyone could give me a hint?

//Array containing the authorized extensions
$ext_permitidas = array("jpg","jpeg","gif","png"); 

/* SOME CODE HERE */

//String comparison and validation

$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);

if(!in_array($ext,$ext_permitidas))
    die('A extensão da imagem '.$ext.' não é permitida');

This might not be the best way to do this but it should work.

You could try something like this instead of using an array.

$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);

if (($ext == "png") || ($ext == "jpg") || ($ext == "jpeg") || ($ext == "gif")) {
  //ADD FILE CODE HERE
} else {
 die('A extensão da imagem '.$ext.' não é permitida');
}
Member Avatar for diafol

the $ext includes the "." - so none of your array extensions will work. Try this:

substr($filename, strpos($filename,'.')+1, strlen($filename))

BTW - this doesn't wok if there are multiple periods in the name. In whic case, use this:

substr($filename, strrpos($filename,'.')+1, strlen($filename))

note the strrpos (get first period in reverse order)

Solved.

thanks for your sugestions, but I ended up using a "." before each extension in the array though.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.