我一直在研究一种改变服务器文件中值的PHP表单。表单正确地更改了值,但我需要表单的<option value="round" <?php if($shape == 'round'){?>selected="selected"<?php }?>>Round</option>
部分始终显示在文件中设置的当前值,目前它没有。
#file contents (the lines the values are on changed on a regular basis)
size=large
color-name=red
shape=round
height=short
weight=heavy
<?php
$file = "/home/user/color.props";
$contents = file($file, FILE_SKIP_EMPTY_LINES);
foreach($contents as $line) {
list($option, $value) = explode('=', $line);
if ($option == 'color-name') {
$color_name = $value;
} elseif ($option == 'shape') {
$shape = $value;
}
}
if(isset($_REQUEST['color_choice'])){
exec('sed -i '.escapeshellarg('s/color-name=.*/color-name='.$_REQUEST['color_choice'].'/g')." /home/user/color.props");
echo 'Color setting has been updated';
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="color_choice">;
<option value="round" <?php if($shape == 'round'){?>selected="selected"<?php }?>>Round</option>;
<option value="square" <?php if($shape == 'square'){?>selected="selected"<?php }?>>Square</option>;
</select>
<input type="submit" name="Submit" value="Submit" />
</form>
答案 0 :(得分:0)
我仍然不清楚你究竟想要完成什么。您当前的代码仅保存从文件中读取的最后'color-name'
和'shape'
个对象。然后,它可以通过进行此更改来配置selected
选项:
<option value="red" <?php if($color_name == 'red'){?>selected="selected"<?php }?>>Red</option>;
<option value="blue" <?php if($color_name == 'blue'){?>selected="selected"<?php }?>>Blue</option>;
<option value="green" <?php if($color_name == 'green'){?>selected="selected"<?php }?>>Green</option>;
<option value="purple" <?php if($color_name == 'purple'){?>selected="selected"<?php }?>>Purple</option>;
注意:您在文件中读取的方式会在变量末尾添加回车符/换行符...例如,我的末尾的$color_name
在末尾包含两个额外的十六进制值。字符串:x0d
和x0a
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select id="color_choice">
<option id="round">Round</option>
<option id="square">Square</option>
</select>
<input type="submit" name="Submit" value="Submit" />
</form>
<script>
var option = document.getElementById("color_choice");
option.options['<?php echo $shape ?>'].selected = true;
</script>
我很确定这会奏效,我所做的改变是:
1)使用javascript代替php更改选中的
2)使用id
属性而不是value
或name
3)在表格末尾添加了<script>
标签(如果之前可能无效)
您必须根据从文件中提取的值的类型对表单和脚本进行更改...但您应该能够弄清楚如何处理它。