Php – Problems with replacing text in a text file

PHP

I have the following scenarion.

Everytime my page loads I create a file. Now my file has two tags within. {theme}{/theme} and {layout}{/layout}, now everytime I choose a certain layout or theme it should replace the tags with {layout}layout{/layout} and {theme}theme{/theme}

My issue is that after I run the following code

if(!file_exists($_SESSION['file'])){
        $fh = fopen($_SESSION['file'],"w");
        fwrite($fh,"{theme}{/theme}\n");
        fwrite($fh,"{layout}{/layout}");
        fclose($fh);
    }

    $handle = fopen($_SESSION['file'],'r+');



if ($_REQUEST[theme]) {
        $theme = ($_REQUEST[theme]);
        //Replacing the theme bracket in the cache file for rememberence
        while($line=fgets($handle)){
            $line = preg_replace("/{theme}.*{\/theme}/","{theme}".$theme."{/theme}",$line);
            fwrite($handle, $line);
        }
}

My output looks as follows

{theme}{/theme}
{theme}green{/theme}

And it needs to look like this

{theme}green{/theme}
{layout}layout1{/layout}

Best Answer

I rarely use random-access file operation but like to read it all as text and write ti back so I might be wrong here. BUT as I can see, you read the first line (so the pointer is at the beginning of the second line). Then you write '{theme}green{/theme}' into that file so it replaces the next position text (the second line).

In this case (as your data is small), you better get the hold file. Change it as string and write it back.

Related Topic