phpphp-7.1getimagesize

getimagesize() not working in PHP 7.1


I have a code that gets an imgur link and fetches the height and width of the image using the simple:

list($width, $height) = getimagesize($link);

I was running PHP 7.1 and everything worked fine until I got to the use of getimagesize(). When the function was called it returned false everytime. I then reverted back to PHP 5.3 and the code worked immediately.

I just wanted to ask whether there was a reason getimagesize() stopped working in 7.1? The documentation says PHP 7 so I guess I am just confused.


Solution

  • best guess, $link is an url, which means that it requires the php.ini setting allow_url_fopen to be true for getimagesize to check it, and you have it to true in php5's php.ini, and false in php7's php.ini - that would cause the problem you're describing. an alternative, compatible with both php versions and both php.ini settings, would be:

    $tmp=tmpfile();
    $file=stream_get_meta_data($tmp)['uri'];
    $ch=curl_init($link);
    curl_setopt_array($ch,array(
    CURLOPT_FILE=>$tmp,
    CURLOPT_ENCODING=>''
    ));
    curl_exec($ch);
    curl_close($ch);
    list($width, $height) = getimagesize($file);
    fclose($tmp); // << explicitly deletes the file, freeing up disk space etc~ - though php would do this automatically at the end of script execution anyway.
    

    edit: as pointed out by @marekful , the original proposed workaround code would give the wrong result. the updated code should give the correct result.

    edit: fixed some code-breaking typos (in the variable names)