Consider the following PHP code that sanitizes user input before outputting it. What will be printed?
<?php $user_input = "<script>alert('XSS');</script>"; $sanitized = filter_var($user_input, FILTER_SANITIZE_STRING); echo $sanitized; ?>
FILTER_SANITIZE_STRING removes tags but keeps the text inside.
The filter FILTER_SANITIZE_STRING removes HTML tags but keeps the text inside. So the script tags are removed but the alert text remains.
What error will this PHP code produce when validating an invalid email?
<?php $email = "invalid-email@"; if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { throw new Exception("Invalid email format"); } echo "Valid email"; ?>
FILTER_VALIDATE_EMAIL returns false if the email is invalid.
The code throws an Exception when filter_var returns false for invalid email format.
Find the reason why this PHP code does not sanitize the input as expected.
<?php $input = "<b>Hello</b>"; $clean = filter_var($input, FILTER_SANITIZE_EMAIL); echo $clean; ?>
Check what FILTER_SANITIZE_EMAIL actually removes.
FILTER_SANITIZE_EMAIL only removes characters not valid in emails. It does not remove HTML tags, so <b> remains.
What will this PHP code print?
<?php $input = "<a href='test'>Test</a> & \"Quotes\""; $escaped = htmlspecialchars($input, ENT_QUOTES); echo $escaped; ?>
htmlspecialchars converts special characters to HTML entities.
htmlspecialchars with ENT_QUOTES converts <, >, &, ' and " to HTML entities.
Which of the following PHP functions is the best choice to prevent SQL injection attacks by properly sanitizing user input before using it in SQL queries?
Think about functions designed specifically for SQL context.
mysqli_real_escape_string() escapes special characters for SQL queries, preventing injection. htmlspecialchars() and filter_var() sanitize for HTML or general input, not SQL. addslashes() is less safe and not recommended.