Search code examples
phparraysfilelines

PHP replace specific line in file


I could actually not find any answers online. I have always searched online for answers when it comes to coding. Well..

I'm wondering how to change a specific line in a file with something else in PHP?

I have 4 lines looking like this:

$2y$10$hashedpassword
typewar
typewarMMM36634573323
84.2xx.xxx.xxx

I have recently started looking into cookies and that stuff, and wanted to be able to change the cookie (line 3) whenever the person logs in to the server or goes to index.php

I'm guessing something like this?

$user = 'typewar';
$GeneratedCookie = $user . 'MMM' . date('H', time()) * date('i', time()) * 333;
$lines = file('/path/to/identity/' . $user . '/identity.txt');
str_replace($lines[2], $GeneratedCookie . '/n');

Please help.


Solution

  • I am not so sure about your case. Please find the below idea and check it out.

    $user = 'typewar';
    $GeneratedCookie = $user . 'MMM' . date('H', time()) * date('i', time()) * 333;
    $lines = file('/path/to/identity/' . $user . '/identity.txt');
    print_r($lines); 
    $lines[2] = $GeneratedCookie;
    print_r($lines);