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

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

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

问题

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

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

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

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

这是我的代码:

// 处理上传的头像图像
if (isset($_FILES['authoravatar']) && $_FILES['authoravatar']['error'] === UPLOAD_ERR_OK ) {
$avatarFile = $_FILES['authoravatar'];
$authorAvatar = isset($author["avatar"]) ? $author["avatar"] : '';
$avatarImage = $avatarDirectory . $authorAvatar;

if ($_FILES['authoravatar']['error'] == 4 || ($_FILES['authoravatar']['size'] == 0 && $_FILES['authoravatar']['error'] == 0)) {
unlink($avatarImage);
}

// 提取文件扩展名
$fileExtension = pathinfo($avatarFile['name'], PATHINFO_EXTENSION);

// 生成头像图像文件名
$imageFilename = $authorID . "_avatar_" . basename($avatarFile['name']);

// 将上传的文件移动到头像目录
$destination = $avatarDirectory . $imageFilename;

move_uploaded_file($avatarFile['tmp_name'], $destination);


// 使用图像文件名更新头像数据库记录
$stmt = $connection->prepare("UPDATE authors SET avatar = ? WHERE id = ?");
$stmt->bind_param("si", $imageFilename, $authorID);
$stmt->execute();

}

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

英文:

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:

// Process the uploaded avatar image
if (isset($_FILES['authoravatar']) && $_FILES['authoravatar']['error'] === UPLOAD_ERR_OK ) {
$avatarFile = $_FILES['authoravatar'];
$authorAvatar = isset($author["avatar"]) ? $author["avatar"] : '';
$avatarImage = $avatarDirectory . $authorAvatar;

if ($_FILES['authoravatar']['error'] == 4 || ($_FILES['authoravatar']['size'] == 0 && $_FILES['authoravatar']['error'] == 0)) {
unlink($avatarImage);
}

// Extract the file extension
$fileExtension = pathinfo($avatarFile['name'], PATHINFO_EXTENSION);

// Generate the avatar image filename
$imageFilename = $authorID . "_avatar_" . basename($avatarFile['name']);

// Move the uploaded file to the avatar directory
$destination = $avatarDirectory . $imageFilename;

move_uploaded_file($avatarFile['tmp_name'], $destination);


// Update the avatar database record with the image filename
$stmt = $connection->prepare("UPDATE authors SET avatar = ? WHERE id = ?");
$stmt->bind_param("si", $imageFilename, $authorID);
$stmt->execute();

}

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

答案1

得分: 1

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

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

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

if (isset($_FILES['authoravatar']) && $_FILES['authoravatar']['error'] === UPLOAD_ERR_OK) {
    $avatarFile = $_FILES['authoravatar'];

    // 生成头像图像文件名
    $imageFilename = $authorID . '_avatar_' . basename($avatarFile['name']);

    // 将上传的文件移动到头像目录
    $destination = $avatarDirectory . $imageFilename;

    $isSaved = move_uploaded_file($avatarFile['tmp_name'], $destination);
    if ($isSaved) {
        // 使用图像文件名更新头像数据库记录
        $stmt = $connection->prepare('UPDATE authors SET avatar = ? WHERE id = ?');
        $stmt->bind_param('si', $imageFilename, $authorID);
        $stmt->execute();
        
        // 验证来自作者数据的现有头像
        if (isset($author["avatar"])) {
            $avatarImage = $avatarDirectory . $author['avatar'];
            // 确保文件存在且目录具有写入权限
            if (is_file($avatarImage) && is_writable(dirname($avatarImage))) {
                // 从文件系统中删除旧头像图像
                unlink($avatarImage);
            }
        }
    }
}

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

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

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.

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

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

if (isset($_FILES['authoravatar']) && $_FILES['authoravatar']['error'] === UPLOAD_ERR_OK) {
    $avatarFile = $_FILES['authoravatar'];

    // Generate the avatar image filename
    $imageFilename = $authorID . '_avatar_' . basename($avatarFile['name']);

    // Move the uploaded file to the avatar directory
    $destination = $avatarDirectory . $imageFilename;

    $isSaved = move_uploaded_file($avatarFile['tmp_name'], $destination);
    if ($isSaved) {
        // Update the avatar database record with the image filename
        $stmt = $connection->prepare('UPDATE authors SET avatar = ? WHERE id = ?');
        $stmt->bind_param('si', $imageFilename, $authorID);
        $stmt->execute();
        
        // verify pre-existing avatar from Author data
        if (isset($author["avatar"])) {
            $avatarImage = $avatarDirectory . $author['avatar'];
            // ensure a file exists and the directory has permissions
            if (is_file($avatarImage) && is_writable(dirname($avatarImage))) {
                // delete the old avatar image from the filesystem
                unlink($avatarImage);
            }
        }
    }
}

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.

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

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:

确定