1

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!

3
  • 2
    does the checked='yes' show up in the generated html? If not, then make SURE that what's coming out of the ini parse is really just the three letters y, e, s, and doesn't contain extra stuff, like spaces or line breaks or whatever. e.g. var_dump($ini) and see what actually parsed out of there. Commented Oct 14, 2016 at 20:05
  • I would use var_dump() instead of echo in this case, to ensure what @MarcB is saying. Commented Oct 14, 2016 at 20:05
  • you're right... A var_dump() revealed it comes up as: ["string2_enable"]=> string(0) "". How is this possible? It's clearly saves as "yes". Commented Oct 14, 2016 at 20:07

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Notice "checked=true". Just "checked" would also work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.