简体   繁体   中英

POST checkbox name even if its not checked

Is it possible to POST checkbox name even if its not checked?

    <input type='checkbox' class='tinyField' name='alert_by_email' value="1" <?PHP echo $alert_by_emailChecked  ?> />


foreach ($_POST AS $field => $value)
    $sql[] = $field." = '". $value."'";

$sql = implode(' , ',$sql);

$query = "UPDATE user_setup SET ".$sql." WHERE (userID = ".$userID.") " ;               

$res = mysql_query($query);     

So when I PRINT_R the POST i will get the field, but it will be empty

 Array ( [alert_by_email] => '' ) 

在您的复选框之前添加它。

<input type='hidden' name='alert_by_email' value="" />

The straight forward answer is no. The HTML form wont send the checkbox if it's not checked.

However, there are some workarounds:

  1. use js to Generate a hidden input for each checkbox you have, set the value to 0 or '', and whenever you check them, remove the hidden input.
  2. you could simply test if the key exist in the post like so: if (isset($_POST['alert_by_email']))

In Short, No this is not possible if you are posting FORM without using any Javascript.

Also, Your code may be injected easily as you are relying on user provided column names without validating those. I am posting alternative way to do that. Hope that helps:

Suppose you have this HTML Form:

<form method="POST">
First name:<br />
<input type="text" name="firstname" />
<br />
Last name:<br />
<input type="text" name="lastname" /><br />
<input type="submit" />
</form>

Now, if you want to update values using PHP, your code should be:

<?php
  $columnArray = array('firstname' => NULL, 'lastname' => NULL); // This is list of columns which can be updated using form input values (NULL is default value here)
  $submittedValues = array_intersect_key($_POST, $columnArray); 
// Above code will produce an array like `array('firstname' => 'anyname', 'lastname' => 'anylastname')

//--> Now you can generate your SQL using `$submittedValues`
$sql = array();
foreach ($submittedValues as $field => $value)
{
  $sql[] = $field." = '". $value."'";
}

$sqlString = implode(' , ',$sql);               

Using this way, hacker will not be able to add extra columns which shouldn't be updated by user ie last_login_date or something.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM