首页 > 解决方案 > 打开php文件,更改一个变量的值,保存

问题描述

我正在尝试通过此代码使用文件中的表单通过脚本修改$denumire produs=' ';php 文件中的变量的值,但我有一些错误。变量的新值将成为通过表单从键盘输入的值。任何人都可以帮助我,好吗?_inc.config.phpindex.php

<?php 

if (isset($_POST['modify'])) {
    $str_continut_post = $_POST['modify'];

    if (strlen($_POST['search']) > 0 || 1==1) {
        $fisier = "ask003/inc/_inc.config.php";
        $fisier = fopen($fisier,"w") or die("Unable to open file!");

        while(! feof($fisier)) {
            $contents = file_get_contents($fisier);
            $contents = str_replace("$denumire_produs =' ';", "$denumire_produs ='$str_continut_post';", $contents);
            file_put_contents($fisier, $contents);

            echo $contents;
        }
        fclose($fisier);
        die("tests");
    }
}
?>

 <form  method="POST" action="index.php"  >  
    <label>Modifica denumire baza de date: </label>  
    <input  type="text" name="den"> 
    <button type="submit" name="modify"> <center>Modifica</center></button>

     </div></div>
  </form> 

标签: php

解决方案


这是一个 XY 问题 ( http://xyproblem.info/ )。

与其让某种系统开始重写自己的文件,不如让带有要更改的变量的文件加载一个 json 配置文件?

{
    "name": "Bob",
    "job": "Tea Boy"
}

然后在脚本中:

$json = file_get_contents('/path/to/config.json');
$config = json_decode($json, true);
$name = $config['name'];

更改配置中的值就像编码数组并将 json 放入文件一样简单。

$config['denumireProdu'] = 'something';
$json = json_encode($config);
file_put_contents('/path/to/config.json', $json);

这比让 PHP 自己重写要明智得多!

这些命令的文档:

http://php.net/manual/en/function.json-decode.php

http://php.net/manual/en/function.json-encode.php

http://php.net/manual/en/function.file-get-contents.php

http://php.net/manual/en/function.file-put-contents.php


推荐阅读