用PHP操作PHP文件


Manipulate PHP file with PHP

我想通过调用函数来替换php文件中的特定字符串。我现在只知道:

function change_data($data1, $data2)
{
    //Read php file in $result
    $result= str_replace("tag1", $data1, $result);
    $result= str_replace("tag2", $data2, $result);
    //Save php file
}

你能帮我吗?它是保存的,所以没有其他人可以访问文件?

编辑:我尝试了以下内容:

function change_data($data1, $data2)
{
    $file = 'test.php';
$result = file_get_contents($file);
    //Replace initial with test
$result = str_replace("intial", "test", $result);
file_put_contents($file, $result);
}

看一下file_get_contents()用于读取文件和file_put_contents()用于向文件系统写入文件的函数

保存以便其他人无法访问该文件?

这是一种非常有效的保护目录的方法。public_html中的任何其他目录都可以以同样的方式进行保护。此方法仅适用于为您分配了静态IP地址的情况。任何试图使用其他IP地址浏览这些目录的人都会得到一个403 Forbidden错误。

    在您希望保护的目录中,打开(或创建)一个名为.htaccess的文件。(注意文件名开头的点)在此文件中添加以下代码,将本例中的100.100.100.100替换为您计划允许的静态IP地址:

订单否认,允许的拒绝一切Allow from 100.100.100.100

function change_data($data1, $data2)
{
    $file = 'change_this_with_filename';
    $result = file_get_contents($file);
    $result = str_replace(array("tag1", "tag2"), array($data1, $data2), $result);
    file_put_contents($file, $result);
}