【问题标题】:PHP & MySQL: Replace Image if the File Name (not file extension) is Identical?PHP和MySQL:如果文件名(不是文件扩展名)相同,则替换图像?
【发布时间】:2018-05-16 21:31:16
【问题描述】:

例如,如果我将“profile1.jpg”上传到我的网站,然后上传“profile1.png”或“profile1.gif”,如果文件名相同,则新图像应该替换旧图像即使如果 文件扩展名不同。我上传个人资料图片的代码是这样的:

if (isset($_POST['submit'])) {
    $file = $_FILES['file'];

    $fileName = $_FILES['file']['name'];
    $fileTmpName = $_FILES['file']['tmp_name'];
    $fileSize = $_FILES['file']['size'];
    $fileType = $_FILES['file']['type'];
    $fileError = $_FILES['file']['error'];

    $fileExt = explode('.', $fileName);
    $fileActualExt = strtolower(end($fileExt));

    $allowed = array('jpg', 'jpeg', 'png', 'pdf');

    if (in_array($fileActualExt, $allowed)) {
        if ($fileError === 0) {
            if ($fileSize < 1000000) {
                $fileNameNew = "profile".$id.".".$fileActualExt;
                $fileDestination = 'uploads/'.$fileNameNew;
                move_uploaded_file($fileTmpName, $fileDestination); /*Something like then_replace_all_files_with_this_filename (example) */
                $sql = "UPDATE profileimg SET status=0 WHERE userid='$id';";
                $result = mysqli_query($conn, $sql);
                header("Location:index.php?upload=success");
            } else {
                echo "File too large!";
            }
        } else {
            echo "Error uploading your file!";
        }
    } else {
        echo "Format not allowed!";
    }
}

【问题讨论】:

    标签: php mysql


    【解决方案1】:

    您可以在调用 move_uploaded_file 之前立即执行以下操作:

    foreach(glob("uploads/profile{$id}.*") as $match) {
        unlink($match);
    }
    

    【讨论】:

    • 完全按照我的意愿工作!一个++
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 2013-06-02
    • 1970-01-01
    • 2015-04-04
    • 2018-12-12
    相关资源
    最近更新 更多