How can versioning be implemented in a PHP script to avoid overwriting user-uploaded files during updates?

When updating a PHP script that involves user-uploaded files, versioning can be implemented by appending a timestamp or version number to the filenames of the uploaded files. This ensures that new files are not overwritten during updates, as each file will have a unique identifier.

// Example code to implement versioning in PHP for user-uploaded files

$uploadDir = 'uploads/';
$timestamp = time(); // Get current timestamp

if(isset($_FILES['file'])){
    $fileName = $_FILES['file']['name'];
    $fileTmp = $_FILES['file']['tmp_name'];

    $fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);
    $newFileName = $timestamp . '_' . $fileName; // Append timestamp to filename

    // Move uploaded file to directory with versioned filename
    move_uploaded_file($fileTmp, $uploadDir . $newFileName);

    echo "File uploaded successfully!";
}