How can PHP be used to check if a file already exists and rename it if necessary?

When working with file uploads or file manipulation in PHP, it's important to check if a file already exists before attempting to save a new file with the same name. If a file with the same name already exists, you can rename the new file by appending a unique identifier to its name to avoid overwriting the existing file.

$targetDir = "uploads/";
$fileName = $_FILES["file"]["name"];
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);

if (file_exists($targetFilePath)) {
    $fileName = uniqid() . "_" . $fileName;
    $targetFilePath = $targetDir . $fileName;
}

move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath);