Skip to content

Instantly share code, notes, and snippets.

@emailjohnthomascaballero
Last active January 19, 2024 01:52
Show Gist options
  • Save emailjohnthomascaballero/696d1d65f52e7e1d2b4c4305a48aba3f to your computer and use it in GitHub Desktop.
Save emailjohnthomascaballero/696d1d65f52e7e1d2b4c4305a48aba3f to your computer and use it in GitHub Desktop.
PHP FORM: Prevent Cross-site scripting (XSS)
<!-- SOURCE: https://www.w3schools.com/php/php_form_validation.asp -->
<!--
LOGIC:
htmlspecialchars() - prevent Cross-Site Scripting (XSS) attacks.
trim() - Strip unnecessary characters (extra space, tab, newline).
stripslashes() - Remove backslashes (\).
-->
<!-- SCRIPT -->
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment