首页 > 解决方案 > move_uploaded_file - 文件仅在直接加载该页面后更改

问题描述

所以,我正在制作一个聊天室,我想允许我的用户上传个人资料图片。我知道 AJAX 正在工作,并且文件正在上传并移动到用户/[他们的用户名],但在其他帐户上,他们的个人资料图像不会更改为新的,直到他们加载实际的个人资料图像。这有点令人困惑,所以我将其简化:

  1. 用户成功更改个人资料图片(文件已上传)
  2. 同一用户返回聊天室,他们的个人资料图像已更改
  3. 在上传新头像之前在聊天室的新用户重新加载页面以查找其他用户的头像仍然相同。

此外,我发现如果第二个用户转到包含另一个用户的个人资料图像的文件,它并没有改变,但是在重新加载图像文件时它会改变。这非常令人困惑,我不知道为什么会发生这一切。也没有任何错误。这是我的代码:(我也尝试过复制而不是 move_uploaded_file)

if(!isset($_FILES["profileImage"])){
    echo '<script>window.setTimeout(function(){window.location = "messageRoom.php";}, 3000);</script>';
    die("No image recieved.<br>Automatically redirecting in 3 seconds...");
}


$target_file = "users/" . $username;




$file = $_FILES["profileImage"];

if(!exif_imagetype($file["tmp_name"])){
    echo '<script>window.setTimeout(function(){window.location = "messageRoom.php";}, 3000);</script>';
    die("File type not an image.<br>Automatically redirecting in 3 seconds...");
}

if(filesize($file["tmp_name"]) > 2000000){
    echo '<script>window.setTimeout(function(){window.location = "messageRoom.php";}, 3000);</script>';
    die("Image size over 2MB (".(round(filesize($file["tmp_name"])/100000)/10)." MB)<br>Automatically redirecting in 3 seconds...");
}


/*Deletes file if it exists*/
if(file_exists($target_file)){
    unlink($target_file);
}


if(move_uploaded_file($file["tmp_name"], $target_file)){
    echo "The file '" . basename($file["name"]) . "' has been uploaded to " . $target_file . "<br>Automatically redirecting in 3 seconds...";
} else {
    die("Error in file upload.<br>Automatically redirecting in 3 seconds...");
}

此外,在代码中,$username 和 $password 似乎没有定义,但它们是之前定义的。请帮忙,我不知道发生了什么。

最后,这需要能够覆盖预先存在的文件,我希望用户能够更改他们的个人资料图像。

太感谢了!!!

标签: phpfile

解决方案


推荐阅读