Skip to content
Advertisement

How can i save all the variable results from a echo into a txt file using php?

I wrote a php script that generates random tokens, and I want to output these tokens into a .txt file.

Below is the code:

do {

    $token = bin2hex(random_bytes(2));

    echo("token: $token");

    $myfile = fopen("output.txt", "w+") or die("Unable to open file!");
    fwrite($myfile, $token);
    fclose($myfile);

} while ($token != "e3b0");

It echos multiple tokens, until the echo = e3b0, but when I try to write the result on a txt file, it only writes “e3b0”, is that a way to write all the results of the “echo” into a txt file?

Advertisement

Answer

EDIT: Efficiency was never asked in original OP question. This post is being edited to include efficiency, namely no need to reopen and close a file.

Your use of w+ will always place the file pointer at the beginning of the file and truncate the file in the process. So as a result, you always end up with the last value written.

From php.net on fopen w+:

Open for reading and writing; place the file pointer at the beginning of the file
and truncate the file to zero length. If the file does not exist, attempt to create it.

Using your existing code, a solution then would be as follows:

$myfile = fopen(“output.txt”, “a+”) or die(“Unable to open file!”);

do {

$token = bin2hex(random_bytes(2));

echo("token: $token");


fwrite($myfile, $token);


} while ($token != "e3b0");

fclose($myfile);

Where a+ in the same docs says:

Open for reading and writing; place the file pointer at the end of the file. 
If the file does not exist, attempt to create it. In this mode, fseek() 
only affects the reading position, writes are always appended.

Source: https://www.php.net/manual/en/function.fopen.php

Amendments:

As @andreas mentions, opening and closing the file repeatedly inside the loop is not necessary (nor efficient). Since you are appending, you can open it once with a+ before the loop begins; and close it after the loop ends.

In terms of having a separator char between tokens written to the file, a carriage return (line break) is a good choice. In this way you can reduce the amount of parsing you would have to program when programmatically reading the file. For this, your writes could be written as follows:

fwrite($myfile, $token . "n");
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement