This article demonstrates how to get the current Unix timestamp in seconds in PHP.

1. Using time() function

You can use the time() function to obtain the current Unix timestamp in seconds. It is equivalent to the number of seconds elapsed since the Unix epoch (January 1, 1970 GMT).

Download  Run Code

 
To get the timestamp of the start of the request instead of the current time, consider using the $_SERVER['REQUEST_TIME'] variable.

Download  Run Code

2. Using gettimeofday() function

Another alternative to getting the current time is using the gettimeofday() function, which returns an array with 'sec', 'usec', 'minuteswest', and 'dsttime' as keys. To get the elapsed seconds since the Unix epoch, you can use the value corresponding to the 'sec' key from the returned array.

Download  Run Code

 
The gettimeofday() function optionally takes the boolean value true, which makes the function return a float value rather than a string. To get the integer timestamp in seconds, you can always round down the value using the floor() function.

Download  Run Code

3. Using DateTime::format() function

Finally, you can use the object-oriented function DateTime::format() for formatting a date according to the given format. To obtain the number of seconds since the Unix epoch, you can format the date using the U parameter.

Download  Run Code

 
Alternatively, you can use the procedural function date_format() to obtain the number of seconds since the Unix epoch with the U format parameter.

Download  Run Code

That’s all there is to getting the current Unix timestamp in seconds in PHP.