Aryan Aryan - 6 months ago 8
PHP Question

after early return does next code execute

I have php file where i use if statments and i call this file via ajax.. onSuccess it gives me result if file is upload successfully or error.

Code look like this:

if(empty($_FILES['file']['name'])){
return "no image was selected";
}
if($two_many_images){
return "Only x images are alowed to upload";
}
if($size>2014522){
return "Size error";
}
foreach($_FILES["file"]['tmp_name'] as $key=>$imgLocation){
uploadImage($_FILES["fileToUpload"]['tmp_name'][$key], $imgLocation);
}


Question : In first if statment condition is true, wil my second if statment execute ?

Answer

This can be easily demonstrated, for example you have a function:

funciton foo(){
    echo "foo\n";
    return;
    echo 'bar';
}

if you call

foo();

It will print out

foo

But not bar. Once execution pointer hits the return it will return back to where foo() was called from. This can also be easily shown.

foo();
foo();
foo();

Prints

foo
foo
foo

UPDATE: based off your comments the correct way to do what you want is this

if(empty($_FILES['file']['name'])){
    echo "no image was selected";
    exit();
}
if($two_many_images){
    echo "Only x images are alowed to upload";
    exit();
}
if($size>2014522){
    echo "Size error";
    exit();
}
foreach($_FILES["file"]['tmp_name'] as $key=>$imgLocation){ 
    uploadImage($_FILES["fileToUpload"]['tmp_name'][$key], $imgLocation);
}

I use exit() instead of return, because it's more readable and makes more sense, even though in your case return has the same effect.