Variable inside an if statement giving me an error even though if condition not met

I’m trying to upload an image to the database. I’m using getimagesize to check if it is an image. It is stored in a variable called $image_size. Even though this variable is inside the if statement, I keep getting an error that says:

Undefined variable: image_size in C:\xampp1\htdocs\admin.php on line 10

I believe the page is not supposed to worry about that variable unless we have $_POST [‘image’] being sent to the server. I do not know how I can fix this.

$status = '';

if (isset($_POST['image'])) {
    $image = file_get_contents ($_FILES ['image']['tmp_name']);
    $image_size = getimagesize ($_FILES ['image']['tmp_name']);
}
        
if ($image_size == 0) {
    $status = "That is not an image. Please select an image.";
} else {
    $sql = "UPDATE company_info SET 
    co_image = :co_image
    WHERE id = 1";
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':co_image', $image);
    $stmt->execute();
    $status = "Profile updated successfully!";
}

Hi the_loserkid,

The problem is that if no image is submitted, the variable $image_size is never created, so your second IF statement results in the ‘undefined variable’ error.

One way to fix this would be to change the second IF statement to this:

if ( empty($image_size) ) {

The empty() function will return true if the variable is not set, or has a zero value.

1 Like

Why don’t you nest the second conditional inside the first one, so it doesn’t kick in unless there is a $image and $image_size set?

Yes, I realised it was a silly error. I meant to nest it inside the first one and thought I had done that but was still getting the error. Don’t know how I managed that but thanks to you both for pointing it out.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.