What is the correct way to echo a user-selected background color in PHP?

When echoing a user-selected background color in PHP, it is important to validate the input to prevent any potential security risks such as cross-site scripting attacks. One way to do this is by using the htmlspecialchars() function to sanitize the input. After validating the input, you can then echo the user-selected background color within the style attribute of an HTML element.

<?php
// Assuming $userSelectedColor contains the user-selected background color

// Validate and sanitize the input
$userSelectedColor = htmlspecialchars($_POST['user_selected_color']);

// Echo the user-selected background color within a div element
echo '<div style="background-color: ' . $userSelectedColor . ';">User-selected background color</div>';
?>