I have a form where the user enters data and uploads an image. This image will be checked if there is an image that is exactly the same using md5 hashing. Each image that is uploaded will have its own md5 hash code. If a user decides to upload an image that is exactly like the one on the server, then that image will not be moved. Instead, when creating the entry, the image will inherit the name of that file from the different entry with the same hash code. But I am running into several problems with my current code. For one, when the user uploads an image for the first time, there is no hash code. Another problem I am experiencing with my code is that even when I upload an image with the same hash code, the name of the image is changing to a uniqid. It is executing the else block and not the if block.
Here's my code:
PHP
if (isset($_POST["pageNum"], $_FILES["image"], $_POST["subtitle"], $_POST["text"]))
{
$page = $_POST["pageNum"];
$url = $_SESSION["articleUrl"];
$subtitle = filter_data($_POST["subtitle"]);
$text = filter_data($_POST["text"]);
$name = $_FILES["image"]["name"];
$tempName = $_FILES["image"]["tmp_name"];
$target_file = $_SERVER['DOCUMENT_ROOT'] . "/stories/media/images/$name";
$hash = md5_file($target_file);
$resultHash = $db->query("SELECT * COUNT(*) FROM `Stories` WHERE hash = '$hash' LIMIT 1");
if ($resultHash->num_rows > 0)
{
$row = $resultHash->fetch_array();
$name = $row["image"];
}
else
{
if (@getimagesize($target_file) == true)
{
$ext = pathinfo($name, PATHINFO_EXTENSION);
$name = basename($name, "." . $ext);
$name = $name . uniqid() . "." . $ext;
$target_file = $_SERVER['DOCUMENT_ROOT'] . "/stories/media/images/$name";
}
move_uploaded_file($tempName, $target_file);
}
$result = $db->query("SELECT * FROM Stories WHERE page = '$page' AND url = '$url'");
if ($result->num_rows == 0)
{
$db->query("INSERT INTO `Stories` (`image`, `text`, `url`, `subtitle`, `page`, `hash`) VALUES ('$name', '$text', '$url', '$subtitle', '$page', '$hash')");
}
else
{
$db->query("UPDATE Stories SET image = '$name', text = '$text', url = '$url', subtitle = '$subtitle', page = '$page', hash = '$hash' WHERE url = '$url' AND page = '$page'");
}
}