Quantcast
Channel: Free Tutorials » Development
Viewing all articles
Browse latest Browse all 10

Timestamp in PHP

$
0
0

In this tutorial I will give you example how to add timestamp to file name in PHP .
This is useful when you create similar files like database backups, regular reports, or whatever you are saving in PHP with timestamp in the file name.

Bellow is an example that creates one CSV file with timestamp in the file name:

  1. <?php
  2. $timestamp = date('d-m-Y'); //$timestamp takes the current time
  3. $myFile = "testFile.".$timestamp.".csv"; // add timestamp to the file name
  4. $fh = fopen($myFile, 'w') // the rest is only for filling
  5.        or                  // and may be modified as needed
  6.        die("can't open file");
  7.  $stringData = "one, two, three, four";              
  8.  fwrite($fh, $stringData);
  9.  fclose($fh);
  10. ?>

The part that sets the timestamp in PHP is:

  1. $timestamp = date('d-m-Y'); as
  2. $myFile = "testFile.".$timestamp.".csv";

The file created using this method will be like this: testFile.04-10-2011.csv – certainly with different date.
You can modify the PHP date function and use different formats. For example if you need only the current time for timestamp use:

  1. $timestamp = date("H:i:s");

The file name with this timestamp will be like: testFile.06:18:08.csv

For full timestamp including year-month-day-hour-minute-seconds change the code to:

  1. $timestamp = date("Y-m-d_H:i:s");

My file appeared with timestamp: testFile.2011-10-04_06:18:08.csv

Certainly you can use different separators for the timestamp, also there are more options available which can be found at PHP date function page.


Viewing all articles
Browse latest Browse all 10

Trending Articles