【发布时间】:2015-05-24 09:04:19
【问题描述】:
我正在尝试将某些变量添加到已经有一些内容的几个文件中。
我正在使用 file_get_contents 复制特定文件的内容,然后使用 file_put_contents 将变量值与现有内容一起粘贴到该文件中。
问题在于,在第一个实例上它可以正常工作,但在第二个文件中它会将所有已存储在内存中的内容粘贴到第二个文件中。它将第一个文件中的所有内容与第二个文件的内容一起放置。
有什么方法可以在下一个 file_get_contents 执行之前清除内存。或者我的概念在这里是错误的。
这是我的代码...
<?php
if ($_POST["submit"]) {
$ip = $_POST['ip'];
$subnet = $_POST['subnet'];
$gateway = $_POST['gateway'];
$hostname = $_POST['hostname'];
$domain = $_POST['domain'];
$netbios = $_POST['netbios'];
$password = $_POST['password'];
$ipfile = 'one.txt';
$file = fopen($ipfile, "r");
$ipfileContents = fread($file, filesize($ipfile));
$ipcontent = "ip='$ip'\n";
$ipcontent .= "netmask='$subnet'\n";
$ipcontent .= "gw='$gateway'\n";
$conten = $ipcontent . $ipfileContents;
$file = fopen($ipfile, "w");
fwrite($file, $ipfileContents);
fclose($file);
$ipsh = shell_exec('sh path/to/CHANGE_IP.sh');
$hostfile = 'two.txt';
$fileh = fopen($hostfile, "r");
$hostfileContents = fread($fileh, filesize($hostfile));
$hostcontent = "ip='$ip'\n";
$hostcontent .= "m_name='$hostname'\n";
$hostcontent .= "fqdn='$domain'\n";
$conten = $hostcontent . $hostfileContents;
$fileh = fopen($hostfile, "w");
fwrite($fileh, $hostfileContents);
fclose($fileh);
$hostsh = shell_exec('sh path/to/MODIFY_HOSTS.sh');
}
?>
我试过取消设置,但没用
$ipfilecontents->__destruct();
unset($ipfilecontents);
更新:
file_get_contents & file_put_contents 存在一些并发问题。所以我不得不将我的方法更改为fopen/fwrite/fclose,它完美地工作。感谢您的帮助 Jacinto。
【问题讨论】:
-
一般使用
unset -
是的,我尝试过使用 $ipfilecontents->__destruct();未设置($ipfilecontents);但没有工作@MarkBaker
-
您不必担心。还有其他事情发生,但我没听懂……
-
我不知道...对我来说看起来不错@PeterBowers
-
您是否在
echo和$ipfileContents和$hostfileContents之间使用了适当的 === 分隔符?