PHP-在保存图像之前检测图像文件大小

PHP-在保存图像之前检测图像文件大小,php,file-get-contents,file-put-contents,Php,File Get Contents,File Put Contents,我正在使用以下代码从URL保存图像,但有时图像URL不好,并且没有图像,或者图像有问题,它保存的文件大小为零 <?php file_put_contents ("/var/www/html/images/" . $character . ".jpg", file_get_contents($image)); Imagick软件包具有执行此操作的方法 -返回图像的宽度和高度,或引发异常 function isValidImage($filename) { if (!fi

我正在使用以下代码从URL保存图像,但有时图像URL不好,并且没有图像,或者图像有问题,它保存的文件大小为零

<?php 
file_put_contents ("/var/www/html/images/" . $character . ".jpg", 
    file_get_contents($image));

Imagick软件包具有执行此操作的方法

-返回图像的宽度和高度,或引发异常

function isValidImage($filename)
{
    if (!fileexists($filename) return false;
    if (filesize($filename) == 0) return false;

    $image = new imagick($filename);
    $img=$image->getImageGeometry();

    return ($img['width'] > 0 && $img['height'] > 0);
}

编辑:我用更多的检查更新了我的答案

我尝试通过URL获取图像大小。我有
get_headers()
函数来获取图像大小。下面是一个示例:

function checkImageSize($imageUrl){
   if(!empty($imageUrl)){
       $file_headers = @get_headers($imageUrl, 1); // it gives all header values .
       // for image size, we use **Content-Length** for size.
       $sizeInKB = round($file_headers['Content-Length'] / 1024, 2));           
       return $sizeInKB;
   } else {
       return 0;
   }
}
$imageSize =checkImageSize($imageUrl);
if($imageSize<=$conditionalSize){
     // upload code
} else {
     // error msg
}
函数checkImageSize($imageUrl){
如果(!empty($imageUrl)){
$file_headers=@get_headers($imageUrl,1);//它给出所有的头值。
//对于图像大小,我们使用**内容长度**作为大小。
$sizeInKB=round($file_headers['Content-Length']/1024,2));
返回$sizeInKB;
}否则{
返回0;
}
}
$imageSize=checkImageSize($imageUrl);

如果($imageSizesorry,但它与问题有什么关系?“图像问题”有点模糊。我用更多的检查更新了我的答案。这个解决方案需要安装,这在默认的PHP安装中通常不会发生。是的!可靠地检查文件是否包含图像数据需要解析文件。这不是验证/检测文件是否为图像的正确方法。它感觉不正确,事实并非如此惯用。建议使用fileinfo,而不是完全不清楚你在问什么的标题。请编辑你的问题以澄清它。我想问的是,是否有更好的方法来检测我保存的图像的文件大小是否为零字节。为什么不在谷歌上搜索:“filesize php”?指向官方php文档filesize()的第一个结果链接 function@felipsmartins谢谢你的无益评论,我知道如何用谷歌搜索,其他人也清楚地理解了我的问题。我知道如何用PHP获取文件大小,我是在问我是否能在保存之前获取它。祝你愉快。
$foo=file_get_contents();if(strlen($foo)){file_put_contents('somefile',$foo);
…?
function checkImageSize($imageUrl){
   if(!empty($imageUrl)){
       $file_headers = @get_headers($imageUrl, 1); // it gives all header values .
       // for image size, we use **Content-Length** for size.
       $sizeInKB = round($file_headers['Content-Length'] / 1024, 2));           
       return $sizeInKB;
   } else {
       return 0;
   }
}
$imageSize =checkImageSize($imageUrl);
if($imageSize<=$conditionalSize){
     // upload code
} else {
     // error msg
}