我使用以下代码上传文件:
<?php
// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if file was uploaded without errors
if(isset($_FILES["photo"]) && $_FILES["photo"]["error"] == 0){
$allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
$filename = $_FILES["photo"]["name"];
$filetype = $_FILES["photo"]["type"];
$filesize = $_FILES["photo"]["size"];
// Verify file extension
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
// Verify file size - 5MB maximum
$maxsize = 5 * 1024 * 1024;
if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");
// Verify MYME type of the file
if(in_array($filetype, $allowed)){
// Check whether file exists before uploading it
if(file_exists("upload/" . $filename)){
echo $filename . " is already exists.";
} else{
move_uploaded_file($_FILES["photo"]["tmp_name"], "upload/" . $filename);
echo "Your file was uploaded successfully.";
}
} else{
echo "Error: There was a problem uploading your file. Please try again.";
}
} else{
echo "Error: " . $_FILES["photo"]["error"];
}
}
?>
我想用“ 1.jpg”名称保存上传的文件。如果“ upload”文件夹中已经存在该文件,请保存为“ 2.jpg”,如果“ upload”文件夹中已经存在文件“ 2.jpg”,请等待另一个脚本清除其中的一个。如果经过一段时间(约120秒),两个文件都没有被删除,它将显示一条错误消息。我应该使用什么代码?
答案 0 :(得分:0)
在PHP中,您的代码可以在处理请求的同时工作。您不能暂停脚本并等到另一个请求。 要实现您的任务,可以将文件存储在一个临时位置(如果存在名称为1或2的文件)并响应客户端。然后,另一个脚本应处理来自客户的另一个请求,其中包含客户选择的信息。第二个脚本可以删除旧文件,然后将新文件复制到指定位置。