Home » Php » php – Set the date and time for a file

php – Set the date and time for a file

Posted by: admin July 12, 2020 Leave a comment

Questions:

I want to add date and time on an image file that I have uploaded. Which way is the best to accomplish this?

Thanks in advance!

How to&Answers:

You can use the touch function to set the last modified date:

touch("path/to/my-image-file.jpg", $someTimestamp);

To retrieve this in PHP, use filemtime.

Answer:

Any modern operating system records timestamp information when a file is created (and possibly, when modified or accessed).

You can get this information from php using the stat() call. This returns an associative array with several pieces of data. You’d want the ‘atime’, ‘mtime’ or ‘ctime’ elements.

Read here for the official doc with copious examples:

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

If you have a pointer to the file (if you’re currently using it and it’s open for example) you can use fstat instead:

http://www.php.net/manual/en/function.fstat.php

Answer:

Many modern cameras add date and time to EXIF tags in image files. So many photos already have this data.
There are PHP functions to read this data: https://www.php.net/manual/en/ref.exif.php

You can also find some libraries to write this data to image. Here is a discussion on that: writing exif data in php
I think it is the best and standard way to store date and time of image inside image file.
I think most of desktop applications for photo viewing also support exif.

When no exif data is available then OS file creation time can be used. But this could be the time of last file copy.