gpt4 book ai didi

php - 我如何使用 php 脚本动态编辑和更新我的 etc/hosts 文件

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:21:58 26 4
gpt4 key购买 nike

我正在尝试使用以下 php 代码动态编辑和更新我的/etc/hosts

$string_Data = 'It works success!!';
$file_To_Edit = "/etc/hosts";
exec("sudo chmod 777 /etc/hosts");
$opened_File = file($file_To_Edit) or die("Error. Code:2 - Can not open file $file_To_Edit");
$lines = preg_grep(' /test.com/', $opened_File);
foreach(array_keys($lines) as $key) {
$opened_File[$key] = substr($opened_File[$key], 0, -1) . $string_Data;
}
$f = fopen($file_To_Edit, 'w') or die("Error $file_To_Edit");
fwrite($f, implode("\n", $opened_File));
fclose($f);

谁能告诉我哪里出错了,因为我无法更新/etc/hosts 文件。

最佳答案

//suppose you are in  /var/www/html/website/

$currentdir=getcwd(); // it will save your current directory location

chdir('../../../../etc/'); // it will change your web directory( /var/www/html/website/) to etc directory (/etc/)

$file='hosts';
$current=file_get_contents($file);
$string_Data = 'It works success!!';
$current.=$string_Data;
if(file_put_contents($file, $current))
{
echo "success in writing";
}
else
{
echo "fail in writing";
}

chdir("$currentdir"); // it will change directory (/etc/) to your web directory( /var/www/html/website/ )

//change permission before run php page because if your user don't have permission this code can't do writing

关于php - 我如何使用 php 脚本动态编辑和更新我的 etc/hosts 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20117951/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com