1
<?php 
if(isset($_FILES['menubg'])){
    $errors= array();
    $targetDir = $_SERVER['DOCUMENT_ROOT'].'/user/usermenu_background/'.($_SESSION['user_id']).'';

    // Create target dir
    if (!file_exists($targetDir)) {
        @mkdir($targetDir);
    }
        $file_name = 'menubg.jpg';
//      $file_name = $_FILES['menubg']['name'];
        $file_size =$_FILES['menubg']['size'];
        $file_tmp =$_FILES['menubg']['tmp_name'];
        $file_type=$_FILES['menubg']['type'];   
        $file_ext=strtolower(end(explode('.',$_FILES['menubg']['name'])));
        $extensions = array('jpg');         
        if(in_array($file_ext, $extensions) === false){
            $errors[]='extension not allowed, please choose a JPG file.'; 
        }
        if($file_size > 2097152){
            $errors[]='File size must be under 2 MB';
        }               
        if(empty($errors)==true){
            move_uploaded_file($file_tmp,'user/usermenu_background/'.($_SESSION['user_id']).'/'.$file_name);
            echo "No errors ";
        } else {
            print_r($errors);
        }
}
?>

For some reason every time I save my form I get an error message ( Array ( [0] => extension not allowed, please choose a JPG file. )) that shouldn't be printing unless a file is being uploaded.

When you upload a file it is supposed to check to make sure you are uploading a .jpg file. It is trapped in: if(isset($_FILES['menubg'])){}. On my form people aren't always going to be uploading a file, and it shouldn't tell me that a blank file has an unallowed extension.

1 Answers1

1

You should use the is_uploaded_file method rather than isset.

See the answer here: How to check whether the user uploaded a file in PHP?

Community
  • 1
  • 1
Preston S
  • 2,751
  • 24
  • 37
  • I changed the first line to if(is_uploaded_file($_FILES['menubg']['tmp_name'])){ and that fixed the problem I wrote about, however I also no longer get an error message if I upload a file with the wrong extension! – James Lyngaas Sep 25 '14 at 20:04
  • @JamesLyngaas Can you still upload a file with the .jpg extension? – Preston S Sep 25 '14 at 20:06
  • Yes, that works. But if I choose a png file it uploads it and names it menubg.jpg. – James Lyngaas Sep 25 '14 at 20:09