How can I check if the image already exists in the mysql database and directory?

Asked

Viewed 55 times

-2

Hello, I’m doing crud And now it’s given me a headache in the picture stage. Basically I want to be able to register an image that has a unique name in the bank and in the directory and then if necessary in the update page I can check if the user is trying to put the same image that was already in the system. I wonder if the way I am creating the file name I can recover somehow later to be able to check whether it is already registered or not... Below is the code of how I am creating the name of the image in the bank and in the directory, thanks for your attention!

$imageFileType = strtolower(pathinfo(basename($_FILES["linkimg"]["name"]),PATHINFO_EXTENSION));
$imagem = md5(uniqid()) . '-' . time() . '.'.$imageFileType;
$target_file = $target_dir . $imagem;
  • Remove this image and put the code in text format, please.

  • Okay, just this or something else ?

  • 2

    Just one remark, doing md5(uniqid()) is a "crime". It is corrupting the uniqid feature by generating chance of collisions and killing the uniqueness of it.

1 answer

0

Instead of a "random name" (your code does not achieve this goal either!) you could use a "deterministic and unique name" for each file.

For such cases there are hashing algorithms. I could use the hash_file().

The goal is very simple, do the hash of the content that was sent, it will be the same for the same content and will be different for each different photo sent (ignoring the beginning of pigeon houses, since collisions are considered insignificant on safe hashes).


$imageFileType = strtolower(pathinfo(basename($_FILES["linkimg"]["name"]),PATHINFO_EXTENSION));

$imagem = hash_file('sha384', $_FILES['linkimg']['tmp_name']) . '.' . $imageFileType;
$target_file = $target_dir . $imagem;

I don’t know if the code will achieve this goal (I no longer use PHP and I don’t have it installed for testing). The idea is as described earlier. The new image name will be the hash (SHA-384) of the image itself contents sent, should not hash the image name. The choice of SHA-384 is because it is not vulnerable to length-Extension Attack.

Whenever you send the same photo (same content) will always have the same name, so you know that it has already been sent.

  • 2

    I was wondering why -1, if the code does not work as it should or if it does not solve the OP problem or if there is some inaccuracy in the explanation contained answer. (:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.