What is the best practice for renaming uploaded files in PHP before moving them to a server?

When uploading files in PHP, it is a good practice to rename the files before moving them to a server to prevent potential conflicts with existing files and to improve security. One common approach is to generate a unique filename based on a combination of timestamp and a random string to ensure uniqueness.

// Generate a unique filename for uploaded file
$originalFilename = $_FILES['file']['name'];
$extension = pathinfo($originalFilename, PATHINFO_EXTENSION);
$newFilename = time() . '_' . uniqid() . '.' . $extension;

// Move uploaded file to server with the new filename
$uploadDirectory = 'uploads/';
if(move_uploaded_file($_FILES['file']['tmp_name'], $uploadDirectory . $newFilename)) {
    echo 'File uploaded successfully.';
} else {
    echo 'File upload failed.';
}