Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have an image upload form with which I call multiple functions before uploading the file such as checking the size and dimensions, and that it is in a valid image. The code works, but calling the functions and dealing with the results seems quite cumbersome and complex.

Is there a tidier way of structuring the code?

This is what I currently have:

//Upload an image
if(checkvalidfile("img",$ext)){
    if(checksize($size, 524288)) {
        if(checkdimensions($tmp, 300)) {
            $newfilename = renamefile($ext);
            recordfileindb($brand_id, $newfilename, $mysqli);
            uploadfile($tmp, $bucket, "user_docs/agency_".$agency_id."/brand_logos/", $newfilename, $s3);
            header('Location: ./message.php?action=newlogo'); 
        } else {
            echo "Your image can't be bigger than 300 x 300px";
            die;
        }
    } else {
        echo "File size is too big!";
        die;
    }
} else {
    echo "Not a valid file";
    die;
}
share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

Yes, there's room for a lot of improvement here!

First of all, you can "break early" to avoid excessive indentation. Since die terminates the script, you can check if the file is not valid.

Secondly, instead of echoing first and die later, you can call die with a parameter.

This code works in the same way, but is cleaner:

if (!checkvalidfile("img",$ext)) {
    die("Not a valid file");
}
if (!checksize($size, 524288)) {
    die ("File size is too big!");
}

if (!checkdimensions($tmp, 300)) {
    die("Your image can't be bigger than 300 x 300px");
}

$newfilename = renamefile($ext);
recordfileindb($brand_id, $newfilename, $mysqli);
uploadfile($tmp, $bucket, "user_docs/agency_".$agency_id."/brand_logos/", $newfilename, $s3);
header('Location: ./message.php?action=newlogo'); 
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.