Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP form will not submit value="0"

With a good deal of help I have created a script that edits a file on my VPS. It has been working great but I have one issue that has me totally stumped. When I need to adjust a value in the file to 0 it will not work. Pretty much any other value will work (i.e. value="3") except 0 (value="0"). I'm very confused. I need to have the script change the color= value to color=0 I have no idea why 0 won't work but any other number or letter will. Here is my code:

<?php
//Color
    $color = explode("=", trim($contents[1]));

    if(isset($_REQUEST['difficulty_choice'])){
        exec('sed -i '.escapeshellarg('s/color=.*/color='.$_REQUEST['color_choice'].'/g')." /home/user/color.props");
        echo 'Color choice has been updated';
    }

?>


<?php echo $contents[1]; //Color ?>
<form method="get" action="update.php">
    <select name="color_choice">;
        <option value="0" <?php if($color[1] == '0'){?>selected="selected"<?php }?>>Red</option>;
        <option value="1" <?php if($color[1] == '1'){?>selected="selected"<?php }?>>Blue</option>;
        <option value="2" <?php if($color[1] == '2'){?>selected="selected"<?php }?>>Black</option>;
        <option value="3" <?php if($color[1] == '3'){?>selected="selected"<?php }?>>Yellow</option>;
    </select>
    <input type="submit" name="Submit" value="Submit" />
</form>

The file contents:

# The color file
color=1

Update: I switched !empty with isset and it works!

like image 526
jcrane Avatar asked Apr 26 '26 14:04

jcrane


1 Answers

In php, when $val = "0", empty($val) evaluates to true. It's unexpected, but that's the way php does it. The php docs for empty() give you a list of values considered empty under the "Return Values" section. Here's a little test script to prove it:

<?php
$val = "0";
if (empty($val)) {
        echo $val . " is empty!\n";
} else {
        echo $val . " is not empty.\n";
}

$val = "1";
if (empty($val)) {
        echo $val . " is empty!\n";
} else {
        echo $val . " is not empty.\n";
}
?>

The output is:

0 is empty!
1 is not empty.

Consider using another kind of check such as the === operator instead of empty().

like image 150
Asaph Avatar answered Apr 29 '26 06:04

Asaph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!