I have to create a login in form which a user will insert a username and a password. I have to ensure that html entities are not processed, and I can not allow single quotes or double quotes to be processed either. I must echo the data entered into the form and display it.
I must use htmlentities and str_replace. I have the htmlentities correct, but am unsure on how to utilize the str_replace function to replace the single and double quotes that the user might enter into the form. Any help would be awesome.
Here is my current PHP (which works)
<?php
$username = htmlspecialchars($_POST['username']);
$password = htmlspecialchars($_POST['password']);
$comment = htmlspecialchars($_POST['comment']);
?>
<html>
<body>
Your username is: <?php echo $username; ?><br />
Your password: <?php echo $password; ?><br />
Your Comment was: <?php echo $comment; ?>
First of all, it is always better to check for the unwanted characters and get back to the user, than silently stripping them. Say, a user added a quote to their password, you removed it, and so they won't be able to login at all! So it's better to check and tell the user instead:
if (!ctype_alnum($username)) {
$errors[] = "Only letters and numbers allowed in username";
}
...
if ($errors) {
echo "You've got some errors, please fix them: ". implode("<br>", $errors);
} else {
// proceed with normal flow
But in this specific case I would advise against replacing any characters. Imagine Shaquille "Shaq" O'Neal
is going to register on your site. What's the point in stripping him of all those quotes? Let alone the password, where use of punctuation is strongly encouraged.
After all, those quotes don't do any harm, if you properly handle them.
for HTML, simply use htmlspecialchars()
with ENT_QUOTES
attribute:
Your username is: <?= htmlspecialchars($username, ENT_QUOTES) ?><br />
for SQL, use prepared statements to avoid any problems with quotes
But just for sake of literal answer, here is how to remove quotes (or any other characters and even multi-character substrings) in PHP
$yourVariable = "scor\"pi'on";
$substringsToRemove = ['\'', '"'];
$yourVariable = str_replace($substringsToRemove, "", $yourVariable);
$keyItem = str_replace ("'","\'",$keyItem);
This replaces a single quote with an 'escaped' single quote \' .
$username = htmlentities(str_replace(array('"', "'"), '', $_POST['username']));
$username = str_replace(array("'", "\""), "", htmlspecialchars($_POST['username']));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With