BRHETT
BRHETT

Reputation: 55

PHP image extension error out

I'm trying get my site to error out if the file uploaded ins't a .jpg, .jpeg or .JPG

<?php
function error(){echo"<script>$(function(){alert('Error')});</script>"; exit();}
$fileName = $_FILES['image']['name'];
$ext = substr(strrchr($fileName, "."), 1);

if($ext != "jpg" || $ext != "jpeg" || $ext != "JPG"){ error(); }
?>

As of now, nothing is happening when another filetype (.png, .gif, .doc, etc...) is uploaded. The error() function stops the rest of the page from working, but it is not show the error alert to users.

Upvotes: 0

Views: 190

Answers (2)

Lix
Lix

Reputation: 47986

Here is a simple snippet for "white-listing" file extensions -

$path_info = pathinfo($fileName);
$ext = strtolower($path_info['extension']);
$extWhitelist = array(
 'bmp',
 'gif', 
 'jpeg',
 'jpg',
 'png'
);
if (!in_array($ext,$extWhitelist)){
  // invalid file extension! 
}

Only the file extensions in the $extWhitelist will be allowed.

Resources -

Upvotes: 0

Change this line:

function error(){echo"<script>$(function(){alert('Error')});</script>"; exit();}

for this one:

function error(){echo"<script>alert('Error');</script>"; exit();}

Upvotes: 1

Related Questions