0

我一直在研究一个 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>
4

1 回答 1

0

I'm still unclear on what exactly you're trying to accomplish. Your current code is only saving the last 'color-name' and 'shape' objects being read in from the file. It then can configure the selected option by making this change:

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

NOTE: The way you're reading in the file appends carriage returns/line returns at the end of your variables...for example, $color_name on my end contains two extra hex values at the end of the string: x0d and x0a

EDIT #2: Try making your form like this:

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

I'm pretty sure this will work, changes I made were:
1) Using javascript instead of php to change selected
2) Using id attributes instead of value or name
3) Added <script> tag at the end of form (it may not work if it's before)

You'll have to make changes to the form and the script depending on what type of values you're pulling from the file...but you should be able to figure out how to handle that.

于 2013-08-18T19:19:45.820 回答