PHP脚本完全擦除字符串 - 如何修复?

时间:2016-02-09 14:35:05

标签: php html

enter image description here

我制作了一个脚本,可以将几行PHP保存到.php文件中。我的所有脚本都运行得很好,但只是这个页面开始变得烦人。

解释GIF中发生的事情:

1:我更改了设置 - 当您启用名为"自定义样式"的第二个设置时,需要显示最后2个设置。这很好,所有。 2:所以你启用它并且由于某种原因它完全擦除了其他2个设置(" primarycolor"和" adminbg")。

这怎么可能发生?我究竟做错了什么?如果您想亲自尝试,我的脚本如下。

<?php
if (isset($_POST["submit"])) {
$string = '<?php 
$customoptions = '. $_POST["customoptions"] .';
$primarycolor = "'. $_POST["primarycolor"] .'";
$adminbg = "'. $_POST["adminbg"] .'";
?>';

$fp = fopen("includes/userstyle.php", "w");
fwrite($fp, $string);
fclose($fp);
}

include("includes/userstyle.php");
?>
<form action="" name="customopt" method="post">
<table>
<tr>
<td>Panel language</td>
<td>
<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
<option><?php echo $lang['chooselanguage']; ?></option>
<option value="dashboard.php?lang=en">English</option>
<option value="dashboard.php?lang=nl">Dutch</option>
</select>
</td>
</tr>
<tr>
<td>Custom Style</td>
<td><select name="customoptions" id="customoptions"><option value="true" <?php if($customoptions == true){ echo 'selected'; }; ?>><?php echo $lang['enabled']; ?></option><option value="false" <?php if($customoptions == false){ echo 'selected'; }; ?>><?php echo $lang['disabled']; ?></option></select></td>
</tr>
<?php if($customoptions) { ?>
<tr>
<td>Primary Color</td>
<td><input name="primarycolor" type="text" id="primarycolor" value="<?php echo $primarycolor; ?>"></td>
</tr>
<tr>
<td>Background Color</td>
<td><input name="adminbg" type="text" id="adminbg" value="<?php echo $adminbg; ?>"></td>
</tr>
<?php } ?>
</table>
<input type="submit" name="submit" value="<?php echo $lang['ok']; ?>">
</form>

编辑:userstyle.php

<?php 
$customoptions = true;
$primarycolor = "555";
$adminbg = "fff";
?>

1 个答案:

答案 0 :(得分:2)

当您第二次发布表单时,您发布空值,并按预期将它们保存到文件中。

您应该添加类似

的内容
if (isset($_POST["submit"]) && !empty($_POST['primarycolor']) && !empty($_POST['adminbg'])) {
    // ...

但实际上可以有另一个验证规则。

正如其他人在评论中注意到的那样 - 即使在教育方面,这也是将用户数据保存到php文件然后执行该文件的非常愚蠢的想法。最简单的替代方法 - 使用json_encode将设置保存到json文件,然后解码,并且不要忘记使用至少htmlspecialchars来删除它们。