I'm using PHP to upload an image from a form to the server and want to rename the image lastname_firstname.[original extension]. I currently have:
move_uploaded_file($_FILES["picture"]["tmp_name"], "peopleimages/" . "$_POST[lastname]" . '_' . "$_POST[firstname]")
which, of course, renames the file lastname_firstname without an extension. How do I rename the file but keep the extension?
Thanks!
You need to first find out what the original extension was ;-)
To do that, the
pathinfo
function can do wonders ;-)Quoting the example that's given in the manual :
Will give you :
As a sidenote, don't forget about security :
$_POST[lastname]
, to make sure it only contains valid characters$_POST['lastname']
-- see Why is$foo[bar]
wrong?mime_content_type
for PHP < 5.3finfo_file
for PHP >= 5.3this code is insecure
if
and
this code is vulnerable and result is
for more information check this link:
https://www.owasp.org/index.php/Unrestricted_File_Upload
You can try:
or as Niels Bom suggested
First, find the extension:
Then call your file anyhow you want, and append to the name the extension:
EDIT Thinking of it, none of this is optimal. File extensions most often describe the file type, but this is not always the case. For instance, you could rename a .png file to a .jpg extension, and most applications would still detect it is as a png file. Other than that, certain OSes simply don't use file extensions to determine the type of a file.
With
$_FILE
uploads, you are also given atype
element which represents the MIME type of the file you've received. If you can, I suggest you rely on it instead of on the given extension:You can have a more complete list of MIME types here.
Dont forget if you are allowing people to upload arbitrary files, without checking the, extension, they can perfectly well upload a .php file and execute code on your server ;)
The .htaccess rules to deny php execution inside a certain folder is something like this (tailor for your setup)..
Put this into a .htaccess file into the folder where you are uploading files.
Otherwise, just bear in mind that files may have more than one "." in them, and you should be golden.