Are there best practices for securely handling and evaluating user input in PHP, especially when it involves dynamically generated strings?

When handling user input in PHP, especially dynamically generated strings, it is important to sanitize and validate the input to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. One way to securely handle user input is by using functions like htmlspecialchars() to escape special characters and prevent script injection. Additionally, using prepared statements when interacting with databases can help prevent SQL injection attacks.

// Example of securely handling user input in PHP

// Sanitize user input using htmlspecialchars()
$userInput = htmlspecialchars($_POST['user_input']);

// Validate the input further if needed
if (strlen($userInput) > 50) {
    // Handle error if input is too long
}

// Use prepared statements when interacting with databases
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $userInput);
$stmt->execute();