How to generate a temporary file in PHP / WordPress with an extension

When you use tempnam or wp_tempnam it generates something like /private/tmp/FOOp8eRnX or /var/tmp/63c6a7da1e1ed-fKMNGh.tmp

It is standard to want to have an extension in the end of the temporary path. For example if you want to manipulate images with wp_get_image_editor it will not work if the extension is not good.

In this case, just use $tmpfname = wp_tempnam . '.' . $your extension;

To get the extension of a downloaded file, use exif_imagetype, for example :

$imagetype = exif_imagetype($tmpfname);

$extension = '';
if ($imagetype === IMAGETYPE_JPEG) {
  $extension = 'jpg';
} else if ($imagetype === IMAGETYPE_PNG) {
  $extension = 'png';
} else if ($imagetype == IMAGETYPE_WEBP) {
  $extension = 'webp';
}

Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *