user5740843 user5740843 - 1 month ago 12
PHP Question

HTML checkbox tick/untick with PHP code

Everyone, hello!

I'm trying to tick/untick a HTML checkbox with help from my PHP code.

The option if a checkbox has to be ticked or unticked I get from a config.ini file, which looks like this:

config.ini

[com]
p_ip = x.x.x.x.
p_port = xxx
p_username = xxx
p_password = xxx

[trigger]
string1_enable = no
string2_enable = yes
string3_enable = no


And I've activated the config.ini file in my index.php file as such:

index.php

<?php $ini = parse_ini_file('config.ini'); ?>


Now, as far as the HTML is concerned, I've tried this:

<td><li><input type="checkbox" class="categories-checkbox" name="chk2" id="chk2"<?php if ($ini['string2_enable']=="yes") echo 'checked="yes"';?>><label for="chk2">Enable</label></li></td>


It doesn't throw an error, but it certainly won't enable. However, a simple:

<?php $ini = parse_ini_file('config.ini'); ?>
<?php echo $ini['string2_enable']; ?>


yields a yes on my PHP page.

Any help would be greatly appreciated!

Answer

String values "true", "on" and "yes" are converted to TRUE. "false", "off", "no" and "none" are considered FALSE.

Problem

The value of your $ini['string2_enable'] is converted to boolean (true) so your if case will fail as it's not equal to yes anymore.

Solution 1

So you have to replace your if case with this:

if($ini['string2_enable'])

Solution 2

If for some reason you want to keep your yes value when parsing, you could add a INI_SCANNER_RAW flag to your function:

$ini = parse_ini_file('config.ini', false, INI_SCANNER_RAW);

With this option, your if case will now work properly.

Source

For more information: http://php.net/manual/en/function.parse-ini-file.php