0

I've already saw this question but it didn't help me.
How do I prepend file to beginning??

I've this script that appends a message to the end of a file:

if ( ! $fp = @fopen($filepath, 'ab'))
{
    return FALSE;
}

$message .= $level.' - '.date($this->_date_fmt).' --> '.print_r($msg, TRUE)."\n";
if($this->_add_location){
    foreach (array_reverse(debug_backtrace()) as $key => $step) {
        $message .= '    # '.($key+1).' Line: '.$step['line'].' File: '.$step['file'];
        if(isset($step['function']) && $step['function']==$this->_func_call) $message .= " ---> Call\n";
        else $message .= "\n";
    }
    $message .= "\n";
}


flock($fp, LOCK_EX);

for ($written = 0, $length = strlen($message); $written < $length; $written += $result)
{
    if (($result = fwrite($fp, substr($message, $written))) === FALSE)
    {
        break;
    }
}

flock($fp, LOCK_UN);
fclose($fp);

What I want to know is if there is a way of prepending information by just changing the writing mode ab to other value or do I have to rewrite the entire script to do that?

Community
  • 1
  • 1
CIRCLE
  • 4,501
  • 5
  • 37
  • 56

1 Answers1

0

I don't know if this solution is the best, but it may be reasonably fast for large files.

  1. Rename the file to a temp name.
  2. Create a new file in its place with the pre-pending content.
  3. Append the original content from the temp file to the replacement.
  4. Delete the temp file.

I wasn't sure this was a good answer, so I searched around and found someone else providing the same solution.

PHP when writing to file, How to prepend and append text to a file with existing text?

Community
  • 1
  • 1
Flosculus
  • 6,880
  • 3
  • 18
  • 42