PHP inserts a string after the penultimate line of a file

I wanted to use PHP to execute Linux sed to insert a document, but php currently doesn"t have permission to execute shell commands.

excuse me, how to implement this requirement with php code?

Apr.03,2021

//a.txt
aaa
bbb
//add text here
ccc
$need_add_text = '1111111xxxxxx';
$text = file_get_contents('a.txt');
$text_new = str_replace('//add text here',"//add text here\n".$need_add_text,$text);
file_put_contents('a.txt',$text_new);

$handle = fopen('log.txt', 'r+');
$i = -1;
$lastLine = '';

while(true){
    fseek($handle, $i, SEEK_END);
    $char = fgetc($handle);
   
    if($char == "\n"){
        fwrite($handle, "new line \n". $lastLine);
        exit();
    }else{
        $lastLine .= $char;
    }

    $i --;
}

Editor: the order of $lastLine should be wrong, but if it is easy to modify, the source code will not be modified, and some verifications have not been done, mainly for a simple example of the needs of the landlord. The key function is: fseek

Menu