So is that better to use $code
when validating password inputs or i just have to use $_POST['code']
?
When exactly should the secure_input
function be used when it comes to security?
Is there a better way to perform the below password validation?
More on php form security here
<?php
function secure_input($data) {
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$code = secure_input($_POST['code']);
if($code == "ok") echo 'success';
?>
<form method="post" action="">
Name: <input type="text" name="code">
<input type="submit">
</form>
When exactly should the secure_input function be used when it comes to security?
Never. It is just awful.
$data = stripslashes($data);
— Don't do this. It is hack to deal with the magic quotes problem. In 2018 you should not be using a version of PHP which even supports magic quotes.
$data = htmlspecialchars($data);
— This makes it safe to insert a string of text into an HTML document. You are not outputting the value into an HTML document, so don't do that here.
Is there a better way to perform the below password validation?
You should not store the password in plain text. It should be hashed, and then the user input (which should be the original user input without any escaping as you are comparing the password and not the html representation of the password) should be compared to it using the password_verify function.
PHP has a FAQ about how to handle passwords.
<?php
$submitted_password = $_POST['code'];
$submitted_password = "ok"; # Because this demo doesn't get any POST data
if (password_verify($submitted_password, "$2y$10$76xEMDyKtZEo036w2mQ/zemy3VUDXFhOHRvrljK1F9/6a7rVqlsdi")) {
print "Good password";
} else {
print "Bad password";
}
?>