How does the use of filter_input differ from htmlentities in PHP and what are the advantages of each method?

Filter_input is used to sanitize input data, while htmlentities is used to escape output data. Filter_input filters input data based on the specified filter, such as filtering input as an integer or a string. On the other hand, htmlentities converts characters to HTML entities, which helps prevent XSS attacks by rendering the HTML tags as text.

// Using filter_input to sanitize input data
$input = filter_input(INPUT_POST, 'input_field', FILTER_SANITIZE_STRING);

// Using htmlentities to escape output data
$output = htmlentities($output_data, ENT_QUOTES);