如何在保存到文件之前验证图像

How to validate an image before saving in a file

我有一个功能可以将图像保存在相应的文件夹中。

我想检查图像是否已经存在于文件夹中,如果名称相同,则首先使用名称然后使用图像的 SHA1

我当前的函数看起来像这样

function descargarImagen($id,$url,$pais1)
{


    $ruta = rutaBaseImagen($id,$_POST['pais']);

    $contenido = file_get_contents($url);

    $ext = explode('.', $url);
    $extension = $ext[count($ext) -1];

    $imagen['md5'] = md5($contenido);
    $imagen['sha1'] = sha1($contenido);
    $imagen['nombre'] = $imagen['md5'].'.'.$extension;

    $ficherof = $pais[$pais1]['ruta_imagenes'].'/'.$ruta.'/'.$imagen['nombre'];
    $ficherof = str_replace('//', '/', $ficherof);

//Here before putting the file I want to check if the image already exist in the folder


    file_put_contents($ficherof, $contenido);

    $s = getimagesize($ficherof);

    $imagen['mime'] = $s["mime"];
    $imagen['size'] = $s[0].'x'.$s[1];
    $imagen['url'] = $urlbase_imagenes.'/'.$ruta.'/'.$imagen['nombre'];
    $imagen['url'] = str_replace('//', '/', $imagen['url']);
    $imagen['date'] = time();
    $imagen['fichero'] = $ficherof;

    return $imagen;
}

我正在尝试通过两种方式进行验证 1.If 图片名称是否存在于文件夹中。 2.If present 然后检查图像是否相同,因为可能有新图像但名称相同

如有任何建议,我们将不胜感激

提前致谢

该评论给出的提示:

//Here before putting the file I want to check if the image already exist in the folder

让我觉得你在问 file_exists,这是你在任何搜索引擎中搜索 "php file exist" 时显示的第一件事...

你可以用这个,

// Check if file already exists
if (file_exists($target_file)) {
    //echo "Sorry, file already exists.";

    /** 
    * validate images that are different but have same name 
    * we can use base64_encode function to compare the old and new image 
    * basics: http://php.net/manual/en/function.base64-encode.php 
    * online conversion help: http://freeonlinetools24.com/base64-image
    */
    $base64_encoded_new_image=base64_encode(file_get_contents($name_of_your_new_image_that_you_want_to_upload));
    $base64_encoded_old_image=base64_encode(file_get_contents($name_of_the_image_that_already_exists));
    if ($base64_encoded_new_image!=$base64_encoded_old_image) {
        /** so the images are actually not same although they have same name 
        * now do some other stuffs
        */
    }
}

更多信息请访问http://www.w3schools.com/php/php_file_upload.asp