The answer by @drew010 is correct in that this cannot be done without an external library or other program. However, that answer is quite old and there are now at least two good ways of doing it. @Thiago Barcala gave one answer, using PEL.
Here is a completely different one using a different one, the PERL-script exiftool by Paul Harvey. I prefer this solution because exiftool has a longer history of development and use, is better documented, and seems more stable and reliable to me. PEL is newer by nearly 10 years, has an unstable API, a history of the project changing hands, and has yet to reach version 1.0. I tried setting it up and ran into some roadblocks, and found no documentation for overcoming them, whereas setting up exiftool worked out-of-the-box.
Install exiftool, then, after saving the old image to a new path run:
exec('exiftool -TagsFromFile /full/path/to/original_image.jpg /full/path/to/newly_saved_image.jpg');
You must leave both files in existence for this to work; if you overwrite the file as your original code does, the EXIF data will be lost.
Make sure your php.ini
allows for the exec() call; sometimes it is disallowed for security reasons. Also, take great care that you do not allow any user-generated input in any parameters you pass to that call because it could allow an attacker to execute an arbitrary command under the privileges of the web server. The exec call is most secure if your script generates the filenames according to some formula, such as alphanumeric characters only, with a fixed directory path, and then feed them into the exec call.
If you don't want to install exiftool globally, you can just replace exiftool
by the full path to it. If you are using SELinux, make sure to set the context on the file for the exiftool script to httpd_exec_t
to allow it to be executed by the web server, and make sure the directory the whole script is in has context httpd_sys_content_t
or some other context that allows access by the webserver.