Password protect?

Note: Undefined index

I have a checkbox that can make a password password protected -

<p><strong><label for="password">Password protect?</label></strong> <input type="checkbox" name="password" id="password" value="1" /></p>

My php is trying to post

 $password = htmlspecialchars(strip_tags($_POST['password']));

I get an undefined index error.

Now, if I first try to check if a password has been set, I get the same error -

$sql = "INSERT INTO blog (timestamp,title,entry,password) VALUES ('$timestamp','$title','$entry','$password')";

$result = mysql_query($sql) or print("Can't insert into table blog.<br />" . $sql . "<br />" . mysql_error());

How to fix it? Do I have to do this for every field, such as a header text field and that's it?

+3
source share
4 answers

Why are you removing tags and avoiding a boolean? You could just do it like this:

$password = (isset($_POST['password']) && $_POST['password'] == 1) ? 1 : 0;

or

$password = isset($_POST['password']) ? (bool) $_POST['password'] : 0;
+5
source

, undefined . , , , $password , _POST [xyz] .

$password = isset($_POST['password']) ? $_POST['password'] : '0';

. http://docs.php.net/ternary

+1

You get an undefined index because you are accessing nonexistent array indices.

You must make sure that the value is set before setting it:

if (isset($_POST['password'])) {
   $password = $_POST['password'];
}
+1
source

The value of the flag is returned only if the check box is selected. Therefore, if the password check box is not selected, the key passworddoes not exist in the array $_POST.

You can do:

$password = array_key_exists('password', $_POST) ? '1' : '0';
0
source

Source: https://habr.com/ru/post/1730773/


All Articles