有关文件上传和解释的正确示例,请参阅
this website.此外,
this site似乎是您发现此特定脚本的地方,如果没有提供一个很好的解释.
我已修改您的代码以包含一些注释,以便您和其他人可以更好地了解正在发生的事情.从理论上讲,代码不应该像你说的那样覆盖现有文件,但我已经添加了你需要更改的内容,以便将文件名设置为随机字符串.
此外,您将原始文件名存储到会话中,而不是修改后的文件名.
define("UPLOAD_DIR", "/path/to/uploads/");
if (!empty($_FILES["ambum_art"]))
{
// The file uploaded
$myFile = $_FILES["ambum_art"];
// Check there was no errors
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "
An error occurred.
";exit;
}
// Rename the file so it only contains A-Z, 0-9 . _ -
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
// Split the name into useful parts
$parts = pathinfo($name);
// This part of the code should continue to loop until a filename has been found that does not already exist.
$i = 0;
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
// If you want to set a random unique name for the file then uncomment the following line and remove the above
// $name = uniqid() . $parts["extension"];
// Now its time to save the uploaded file in your upload directory with the new name
$success = move_uploaded_file($myFile["tmp_name"], UPLOAD_DIR . '/'.$name);
// If saving failed then quit execution
if (!$success) {
echo "
Unable to save file.
";exit;
}
// Set file path to the $Dir variable
$Dir = UPLOAD_DIR .'/'. $name;
// Set the permissions on the newly uploaded file
chmod($Dir, 0644);
// Your application specific session stuff
unset($_SESSION['video']);
$_SESSION['album_art'] = $Dir; // Save the file path to the session
$ambum_art_result = array();
$ambum_art_result['content'] = $Dir;
echo json_encode($ambum_art_result);
}
阅读有关PHP uniqid的更多信息.
我还强烈建议做一些文件类型检查,因为它似乎可以上传任何文件.上面的第二个链接有一个标题为“安全注意事项”的部分,我建议您仔细阅读.