Skip to content

Instantly share code, notes, and snippets.

@waimea-cpy
Last active March 20, 2024 06:45
Show Gist options
  • Save waimea-cpy/001efcf4ef4f57920620c708b740757d to your computer and use it in GitHub Desktop.
Save waimea-cpy/001efcf4ef4f57920620c708b740757d to your computer and use it in GitHub Desktop.
PHP Random Filename - PHP function to generate random filename with same extension as given filename, e.g. to avoid filename collisions when uploading
<?php
/*-------------------------------------------------------------
* Generate a random 32 character filename with same extension
* (including no extension) as the filename provided
*-------------------------------------------------------------*/
function randomFilename( $originalFilename ) {
$filenameParts = explode( '.', $originalFilename ); // Break apart the filename
$fileExtension = $filenameParts[sizeof($filenameParts) - 1]; // To get the file extension
$randFilename = md5( $originalFilename.rand( 1, 100000 ) ); // Generate a random 32 char filename
$randFilename = $randFilename.'.'.$fileExtension; // Add on file extension
$randFilename = strtolower( $randFilename ); // Force to lowercase
return $randFilename;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment