PHP file_exists包含内容而不是名称?

时间:2018-04-24 23:52:56

标签: php file-get-contents file-exists

PHP内置的函数是否像file_exists一样,但是给定文件内容而不是文件名?

我需要这个,因为我有一个人们可以上传图片的网站。图像存储在一个文件中,其名称由我的程序(image_0.png image_1.png image_2.png image_3.png image_4.png ...)确定。我不希望我的网站有多个具有相同内容的图像。如果多人在互联网上找到一张图片并且所有人都将其上传到我的网站,就会发生这种情况。我想检查是否已有包含上传文件内容的文件以保存在存储中。

3 个答案:

答案 0 :(得分:2)

这就是你可以用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;
}

如果你保留你接受的每个文件的sha1总和,你可以简单地:

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

答案 1 :(得分:0)

您可以使用while循环查看所有文件的内容。这显示在下面的示例中:

function content_exists($file){
  $image = file_get_contents($file);
  $counter = 0;
  while(file_exists('image_' . $counter . '.png')){
    $check = file_get_contents('image_' . $counter . '.png');
    if($image === $check){
      return true;
    }
    else{
      $counter ++;
    }
  }
  return false;
}

上述功能会查看所有文件并检查给定图像是否与已存储的图像匹配。如果图像已存在,则返回true,如果图像不存在,则返回false。下面显示了如何使用此功能的示例:

if(content_exists($_FILES['file']['tmp_name'])){
  // upload
}
else{
  // do not upload
}

答案 2 :(得分:0)

您可以将散列文件存储在由.txt分隔的\n文件中,以便您可以使用以下函数:

function content_exists($file){
  $file = hash('sha256', file_get_contents($file));
  $files = explode("\n", rtrim(file_get_contents('files.txt')));
  if(in_array($file, $files)){
    return true;
  }
  else{
    return false;
  }
}

然后您可以使用它来确定是否应该保存文件,如下所示:

if(content_exists($_FILES['file']['tmp_name'])){
  // upload
}
else{
  // do not upload
}

只需确保存储 IS 文件时,您可以使用以下代码行:

file_put_contents('files.txt', hash('sha256', file_get_contents($file)) . "\n");
相关问题