HTML 复选框 tick/untick 带有 PHP 代码

HTML checkbox tick/untick with PHP code

大家好!

我正在尝试 tick/untick 在我的 PHP 代码的帮助下 HTML 复选框。

我从 config.ini 文件中获得的复选框必须勾选或取消勾选的选项,如下所示:

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

并且我已经激活了 index.php 文件中的 config.ini 文件:

index.php

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

现在,就 HTML 而言,我试过这个:

<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>

它不会抛出错误,但它肯定不会启用。然而,一个简单的:

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

在我的 PHP 页面上显示是。

如有任何帮助,我们将不胜感激!

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

问题

你的 $ini['string2_enable'] 的值被转换为 boolean (true) 所以你的 if 案例将失败,因为它不再等于 yes

解决方案 1

所以你必须用这个替换你的 if 案例:

if($ini['string2_enable'])

解决方案 2

如果出于某种原因你想在解析时保留你的 yes 值,你可以在你的函数中添加一个 INI_SCANNER_RAW 标志:

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

有了这个选项,您的 if 案例现在可以正常工作了。

来源

更多信息:http://php.net/manual/en/function.parse-ini-file.php

<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>

通知"checked=true"。只需 "checked" 也可以。