如何使用PHP检查图像是否存在并删除它

huangapple go评论87阅读模式
英文:

How to check if an image exists and delete it using PHP

问题

以下是您的内容的中文翻译:

"我已经苦苦挣扎了将近8个小时了。我在我的PHP文件editAuthor.php中有以下代码,允许我在特定目录中上传图像以及其他输入字段。在我的情况下,这个目录是(/uploads/authorAvatars/)。

问题是,当我提交表单时,如果针对特定作者我要编辑的图像已经存在,它不会用我在文件输入框中选择的新图像替换掉它,而是会创建一个新的并将其添加到目录中。所以如果我点击提交按钮5次,它将创建5个图像,而不是一个。图像的文件名存储在表格“authors”的列“avatar”中。

我尝试用PHP检查输入文件是否为空,以便我可以取消链接已存在的图像,但它不起作用。我真的没有主意了。

这是我的代码:

  1. // 处理上传的头像图像
  2. if (isset($_FILES['authoravatar']) && $_FILES['authoravatar']['error'] === UPLOAD_ERR_OK ) {
  3. $avatarFile = $_FILES['authoravatar'];
  4. $authorAvatar = isset($author["avatar"]) ? $author["avatar"] : '';
  5. $avatarImage = $avatarDirectory . $authorAvatar;
  6. if ($_FILES['authoravatar']['error'] == 4 || ($_FILES['authoravatar']['size'] == 0 && $_FILES['authoravatar']['error'] == 0)) {
  7. unlink($avatarImage);
  8. }
  9. // 提取文件扩展名
  10. $fileExtension = pathinfo($avatarFile['name'], PATHINFO_EXTENSION);
  11. // 生成头像图像文件名
  12. $imageFilename = $authorID . "_avatar_" . basename($avatarFile['name']);
  13. // 将上传的文件移动到头像目录
  14. $destination = $avatarDirectory . $imageFilename;
  15. move_uploaded_file($avatarFile['tmp_name'], $destination);
  16. // 使用图像文件名更新头像数据库记录
  17. $stmt = $connection->prepare("UPDATE authors SET avatar = ? WHERE id = ?");
  18. $stmt->bind_param("si", $imageFilename, $authorID);
  19. $stmt->execute();
  20. }

我真的完全没有主意了。任何帮助将不胜感激。谢谢。"

英文:

Its been almost 8 hours i am struggling with this. I have the code below in my PHP file editAuthor.php that allows me to upload an image among other input fields in a specific directory. In my case this directory is (/uploads/authorAvatars/).

The problem is that when I submit the form and it is already an existing image for the specific author I edit, instead of replace this image with the new I selected in my input type file, it creates a new one and adds it in the directory. So if I click the submit button 5 times it will create 5 images instead of one. The filename of the image is stored in the column "avatar" of the table "authors".

I tried to check with PHP if the input file is not empty so i can unlink the existed image but it doesn't work. I am really out of ideas.

Here is my code:

  1. // Process the uploaded avatar image
  2. if (isset($_FILES['authoravatar']) && $_FILES['authoravatar']['error'] === UPLOAD_ERR_OK ) {
  3. $avatarFile = $_FILES['authoravatar'];
  4. $authorAvatar = isset($author["avatar"]) ? $author["avatar"] : '';
  5. $avatarImage = $avatarDirectory . $authorAvatar;
  6. if ($_FILES['authoravatar']['error'] == 4 || ($_FILES['authoravatar']['size'] == 0 && $_FILES['authoravatar']['error'] == 0)) {
  7. unlink($avatarImage);
  8. }
  9. // Extract the file extension
  10. $fileExtension = pathinfo($avatarFile['name'], PATHINFO_EXTENSION);
  11. // Generate the avatar image filename
  12. $imageFilename = $authorID . "_avatar_" . basename($avatarFile['name']);
  13. // Move the uploaded file to the avatar directory
  14. $destination = $avatarDirectory . $imageFilename;
  15. move_uploaded_file($avatarFile['tmp_name'], $destination);
  16. // Update the avatar database record with the image filename
  17. $stmt = $connection->prepare("UPDATE authors SET avatar = ? WHERE id = ?");
  18. $stmt->bind_param("si", $imageFilename, $authorID);
  19. $stmt->execute();
  20. }

I am literally running out of ideas. Any help would be very much appreciated. Thanks

答案1

得分: 1

删除现有头像图像文件的条件取决于上传的文件是否无效,所以 unlink 在成功上传时永远不会被调用。

  1. $_FILES['authoravatar']['error'] == 4 // 未上传文件 (UPLOAD_ERR_NO_FILE)
  2. // 或者
  3. $_FILES['authoravatar']['error'] == 0 // 文件上传时没有错误 (UPLOAD_ERR_OK)
  4. $_FILES['authoravatar']['size'] == 0 // 上传的文件为空

操作顺序应确保文件已成功保存。

  1. if (isset($_FILES['authoravatar']) && $_FILES['authoravatar']['error'] === UPLOAD_ERR_OK) {
  2. $avatarFile = $_FILES['authoravatar'];
  3. // 生成头像图像文件名
  4. $imageFilename = $authorID . '_avatar_' . basename($avatarFile['name']);
  5. // 将上传的文件移动到头像目录
  6. $destination = $avatarDirectory . $imageFilename;
  7. $isSaved = move_uploaded_file($avatarFile['tmp_name'], $destination);
  8. if ($isSaved) {
  9. // 使用图像文件名更新头像数据库记录
  10. $stmt = $connection->prepare('UPDATE authors SET avatar = ? WHERE id = ?');
  11. $stmt->bind_param('si', $imageFilename, $authorID);
  12. $stmt->execute();
  13. // 验证来自作者数据的现有头像
  14. if (isset($author["avatar"])) {
  15. $avatarImage = $avatarDirectory . $author['avatar'];
  16. // 确保文件存在且目录具有写入权限
  17. if (is_file($avatarImage) && is_writable(dirname($avatarImage))) {
  18. // 从文件系统中删除旧头像图像
  19. unlink($avatarImage);
  20. }
  21. }
  22. }
  23. }

如果意图是在 file 表单字段为空时删除现有头像图像文件,您需要额外的 unlink 调用。

  1. if (!isset($_FILES['authoravatar']) ||
  2. UPLOAD_ERR_NO_FILE === $_FILES['authoravatar']['error'] ||
  3. 0 === $_FILES['authoravatar']['size']) {
  4. // 验证来自作者数据的现有头像
  5. if (isset($author["avatar"])) {
  6. $avatarImage = $avatarDirectory . $author['avatar'];
  7. // 确保文件存在且目录具有写入权限
  8. if (is_file($avatarImage) && is_writable(dirname($avatarImage))) {
  9. // 从文件系统中删除旧头像图像
  10. unlink($avatarImage);
  11. }
  12. }
  13. }
英文:

The condition to delete the existing avatar image file is contingent on the uploaded file being invalid, so unlink will never be called during a successful upload.

  1. $_FILES['authoravatar']['error'] == 4 // no file uploaded (UPLOAD_ERR_NO_FILE)
  2. // or
  3. $_FILES['authoravatar']['error'] == 0 // no error during file upload (UPLOAD_ERR_OK)
  4. $_FILES['authoravatar']['size'] == 0 // uploaded file was empty

The order of operations should ensure that the file was saved successfully as well.

  1. if (isset($_FILES['authoravatar']) && $_FILES['authoravatar']['error'] === UPLOAD_ERR_OK) {
  2. $avatarFile = $_FILES['authoravatar'];
  3. // Generate the avatar image filename
  4. $imageFilename = $authorID . '_avatar_' . basename($avatarFile['name']);
  5. // Move the uploaded file to the avatar directory
  6. $destination = $avatarDirectory . $imageFilename;
  7. $isSaved = move_uploaded_file($avatarFile['tmp_name'], $destination);
  8. if ($isSaved) {
  9. // Update the avatar database record with the image filename
  10. $stmt = $connection->prepare('UPDATE authors SET avatar = ? WHERE id = ?');
  11. $stmt->bind_param('si', $imageFilename, $authorID);
  12. $stmt->execute();
  13. // verify pre-existing avatar from Author data
  14. if (isset($author["avatar"])) {
  15. $avatarImage = $avatarDirectory . $author['avatar'];
  16. // ensure a file exists and the directory has permissions
  17. if (is_file($avatarImage) && is_writable(dirname($avatarImage))) {
  18. // delete the old avatar image from the filesystem
  19. unlink($avatarImage);
  20. }
  21. }
  22. }
  23. }

If the intention is to delete the existing avatar image file when the file form field is empty, you would need an additional unlink call.

  1. if (!isset($_FILES['authoravatar']) ||
  2. UPLOAD_ERR_NO_FILE === $_FILES['authoravatar']['error'] ||
  3. 0 === $_FILES['authoravatar']['size']) {
  4. // verify pre-existing avatar from Author data
  5. if (isset($author["avatar"])) {
  6. $avatarImage = $avatarDirectory . $author['avatar'];
  7. // ensure a file exists and the directory has permissions
  8. if (is_file($avatarImage) && is_writable(dirname($avatarImage))) {
  9. // delete the old avatar image from the filesystem
  10. unlink($avatarImage);
  11. }
  12. }
  13. }

huangapple
  • 本文由 发表于 2023年7月18日 08:12:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76708806.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定