How can the PHP move_uploaded_file function be used to rename uploaded files while preserving the file extension?

When using the move_uploaded_file function in PHP to handle file uploads, you may want to rename the uploaded files while preserving their original file extensions. To achieve this, you can extract the file extension from the original file name and append it to the new file name when moving the uploaded file to the desired directory.

$uploadedFile = $_FILES['file']['tmp_name'];
$originalFileName = $_FILES['file']['name'];
$extension = pathinfo($originalFileName, PATHINFO_EXTENSION);
$newFileName = 'new_filename.' . $extension;

if (move_uploaded_file($uploadedFile, 'upload_directory/' . $newFileName)) {
    echo 'File uploaded and renamed successfully.';
} else {
    echo 'Error in uploading file.';
}