What potential pitfalls or errors can occur when trying to get the length of a text input in PHP forms?

When trying to get the length of a text input in PHP forms, potential pitfalls or errors can occur if the input is not properly sanitized or validated. This can lead to security vulnerabilities such as SQL injection or cross-site scripting attacks. To mitigate these risks, it is important to always sanitize and validate user input before processing it.

// Sanitize and validate the text input before getting its length
if(isset($_POST['text_input'])){
    $text_input = htmlspecialchars($_POST['text_input']); // Sanitize input
    $text_input = trim($text_input); // Remove leading and trailing whitespaces
    $text_length = strlen($text_input); // Get the length of the sanitized input
    echo "The length of the text input is: " . $text_length;
}