Search code examples
phpfile-get-contentsfile-exists

PHP file_exists With Contents Instead of Name?


Is there a function built into PHP that acts like file_exists, but given file contents instead of the file name?

I need this because I have a site where people can upload an image. The image is stored in a file with a name determined by my program (image_0.png image_1.png image_2.png image_3.png image_4.png ...). I do not want my site to have multiple images with the same contents. This could happen if multiple people found a picture on the internet and all of them uploaded it to my site. I would like to check if there is already a file with the contents of the uploaded file to save on storage.


Solution

  • This is how you can compare exactly two files with PHP:

    function compareFiles($file_a, $file_b)
    {
        if (filesize($file_a) == filesize($file_b))
        {
            $fp_a = fopen($file_a, 'rb');
            $fp_b = fopen($file_b, 'rb');
    
            while (($b = fread($fp_a, 4096)) !== false)
            {
                $b_b = fread($fp_b, 4096);
                if ($b !== $b_b)
                {
                    fclose($fp_a);
                    fclose($fp_b);
                    return false;
                }
            }
    
            fclose($fp_a);
            fclose($fp_b);
    
            return true;
        }
    
        return false;
    }
    

    If you keep the sha1 sum of each file you accept you can simply:

    if ($known_sha1 == sha1_file($new_file))