简体   繁体   中英

checking image height/width in PHP

I'm trying to check an images size in PHP but I'm getting a couple errors. I can save the image and view it, but if I add in a function to check it's size I get an error.

Warning: imagesx() expects parameter 1 to be resource, array given in...

Warning: imagesy() expects parameter 1 to be resource, array given in...

here's what I use to check the size/upload

if(isset($_POST['submitImage'])){
  $image = new imageProcessing;
  $image->checkSize($_FILES["image"]);
}

Here is the HTML

?>

<h2>Upload Profile Image</h2>
<form action="editinfo.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="image" id="file" /> <br />
<input type="submit" name="submitImage" value="Submit" />
</form>

And here is the function to check size

function checkSize($image){  
    if(imagesx($image) > 100 OR imagesy($image) > 100){
        echo "too large";
    }
}

Using getimagesize as DrAgonmoray suggested, I get the following error

Warning: getimagesize() expects parameter 1 to be string, array given in...

You could use the getimagesize() function to do this. see the php docs for more details.

http://php.net/manual/en/function.getimagesize.php

I was actually working with this a few hours ago. Here's my solution:

$bannersize = getimagesize($image);
if ($bannersize[0] > 100 || $bannersize[1] > 100) {
    //error
}

Be careful to make sure that $image isn't null.

You can read about getimagesize here: http://php.net/manual/en/function.getimagesize.php

$_FILES provides an ARRAY of information PER FILE you upload. This array contains the path to the temporary file that PHP has stored the file in. It's THAT temporary filename you need to use. As well, imagesx() and imagesy() do not accept filenames as their parameters. They expect a GD resource handle. So your code is broken on multiple levels.

if ($_FILES['image']['error'] !== UPLOAD_ERR_OK) {
   die("File upload failed with error code {$_FILES['image']['error']}");
}

$info = getimagesize($_FILES['image']['tmp_name']);
if ($info === FALSE) {
   die("Invalid file type");
}

if (($info[0] > 100) || ($info[1] > 100)) {
   die("Image must be at most 100x100");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM