使用表单和PHP读取和修改存储在单独文件中的值

问题描述:

I'm new to PHP so excuse me in advance! I have done the following code to show two different buttons depending on if $status in the file vars.php is set 1 or 0 using . So far so good.

The problem: I now trying to make a very simple page with two option fields to set the $status in the vars.php. I want the script to read what the value of $status is and pres-select the corresponding option box, and have a submit button that saved either 1 or 0 to $status.

It sounds so simple, but I can't get this it to work.. I don't want to use a database, the file can be txt, xml or whatever. Please anyone help me!

Below is the IF script that just checks for the status value 1 or else.

<?php include 'vars.php'; ?>
<?php if ($status == "1") { ?>
<a class="button" href="pageA.php">Read more</a>
<?php } else { ?>
<a class="button" href="pageB.php">Read more</a>
<?php } ?>

What I'm trying to create is a tiny form with two options where I can swap the $status value between 1 and 0 (with the form option being pre-selected with whatever value $status has). When I press update it should overwrite the $status value in the vars.php.

我是PHP的新手,请原谅我! 我已经完成了以下代码来显示两个不同的按钮,具体取决于文件vars.php中的$ status是否设置为1或0。 到现在为止还挺好。 p>

问题:我现在尝试创建一个非常简单的页面,其中包含两个选项字段,用于在vars.php中设置$ status。 我希望脚本读取$ status的值,并选择相应的选项框,并有一个提交按钮,保存1或0到$ status。 p>

这听起来很简单,但我无法让它工作..我不想使用数据库,文件可以是txt,xml或其他什么。 请任何人帮助我! p>

以下是仅检查状态值1的IF脚本。 p>

 &lt;?php include'vars.php';  ?&gt; 
&lt;?php if($ status ==“1”){?&gt; 
&lt; a class =“button”href =“pageA.php”&gt;了解更多&lt; / a&gt; 
&lt;?  php} else {?&gt; 
&lt; a class =“button”href =“pageB.php”&gt;了解更多&lt; / a&gt; 
&lt;?php}?&gt; 
  code>  pre>  
 
 

我正在尝试创建的是一个带有两个选项的小形式,我可以在$和0之间交换$ status值(表单选项预先选择$ status具有的值)。 当我按下更新时,它应该覆盖vars.php中的$ status值。 p> div>

I would use JSON.

vars.json:

{
    "status": 1
}

then on your PHP:

<?php
$json = json_decode(file_get_contents("vars.json"));
$href = ($json->status) ? "pageA.php" : "pageB.php";
?>
<a class="button" href="<?= $href ?>">Read more</a>

UPDATE: if you want to have a form set these variables without you having to manually modify the JSON data, then create another file, call it anything you want, we'll say form.php and place this inside:

 <?php
 $json = json_decode(file_get_contents("vars.json"));
 if (isset($_POST['status'])) {
    $json->status = (int)$_POST['status'];
    file_put_contents('vars.json', json_encode($json));
 }
 ?>
 <form method="post">
     <label>Status</label>
     <select name="status">
        <option value="1" <?= ($json->status) ? "selected" : "" ?>>TRUE</option>
        <option value="0" <?= (!$json->status) ? "selected" : "" ?>>FALSE</option>
     </select>
     <input type="submit"/>
 </form>