Search code examples
phpfiletimecronfile-put-contents

How to write the current time to a new line of a .txt file on php execution


I want to log the execution of a php file on a .txt file.
I want the file to look like this with serial number:

1, (time)
2, (time)
3, (time)
. . . . .
. . . . .

where (time) is the time of execution of the php file.

How to add the serial number to each line and how to put each entry on next line?

$today = date("Y-m-d H:i:s"); 
$file = fopen("log.txt","a+");
fwrite($file,$today);
fclose($file);

Solution

    1. Create your file on your server/computer, in the same place where you put your PHP file. Fore this example we'll call it "log.txt"
    2. Do what you have to do to make the file writable. For this example, you can just right-click it in Filezilla and choose "permissions", then change it to 777, or Google how to use chmod.
    3. In your script, paste the following code:

      $fh = fopen("log.txt","a+");

      fwrite($fh, date("Y-m-d g:i a")."\r\n");

      fclose($fh);

    http://php.net/manual/en/function.fopen.php

    http://php.net/manual/en/function.fwrite.php