-1

I have read another topics but I couldn't apply the other answer to my code :S

I have this function

function add_image($cFile) {

    //SET SETTINGS FOR THE IMAGE
    $target_dir = "../images/cuisines/";
    $target_file = $target_dir . basename($_FILES["cImage"]["name"]);
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    $cFile = basename($_FILES["cImage"]["name"], '.'. $imageFileType).uniqid($prefix = '-', $more_entropy = null) .'.'. $imageFileType;

    //BUT FIRST CHECK IF THERE IS NOT FILE
    if ($_FILES['cImage']['size'] == 0) {       
        echo "<script>alert('You forgot the image, you must complete the form again');</script>" ;
        echo '<script>window.location="'. $_SERVER['HTTP_REFERER'] .'"</script>' ;
        exit();
    } 

    // CHECK IF THE FILE IS AN IMAGE
    $check = getimagesize($_FILES["cImage"]["tmp_name"]);
    if($check == false) {
        echo "<script>alert('This is not an Image, you must complete the form again');</script>" ;
        echo '<script>window.location="'. $_SERVER['HTTP_REFERER'] .'"</script>' ;
        exit();
    }

    //ALLOW CERTAIN KIND OF FILES
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
        echo "<script>alert('Sorry, only JPG, JPEG, PNG & GIF files are allowed, you must complete the form again');</script>" ;
        echo '<script>window.location="'. $_SERVER['HTTP_REFERER'] .'"</script>' ;
        exit();
    }

    if(move_uploaded_file($_FILES["cImage"]["tmp_name"], $target_dir.$cFile)) { 
        return $cFile;
        } else {
return false;
}

    }

And then if the function is succesfull I want to do this:

if (add_image($cFile) !== false) {

        echo $cfile;
}

Can someone help me to know what I am doing wrong? I have read similar topics but I couldn't use them in my case.

The error I receive is about the variable cFile in the second part of code doesn't exist :S

Tomas Lucena
  • 1,204
  • 1
  • 14
  • 31

2 Answers2

0

Your function looks like it terminates the whole script if it fails, so the only way you can reach the bottom code is if the function was successful.

You probably don't need the if statement.

An approach that would probably be better is to return false; if the function failed, and then check if (add_image($cFile) !== false)

Robin Kanters
  • 5,018
  • 2
  • 20
  • 36
0

May be $target_dir, may not have write access permission. If not add write permission for target_dir using chmod command.

Jitendra Kumar. Balla
  • 1,173
  • 1
  • 9
  • 15