自定义保存上传的文件名

I use the following code to upload the file:

<?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"];
}
}
?>

I want to save the uploaded file with "1.jpg" name. If it already exists in the "upload" folder, save with "2.jpg", and if file "2.jpg" already exists in the "upload" folder, Wait until the another script clears one of them. If, after some time (about 120 seconds), none of the two files was erased, it will display an error message. What code should I use?

In PHP your code works while the request being processed. You cannot pause your script and wait until another request. To realize your task you can store the file in a temporary location if file with name 1 or 2 exists and respond to the client. Then another script should process another request from client which contains information of client’s choice. This second script could delete old file and copy the new one to specified location.