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 :
$path_parts = pathinfo('/www/htdocs/index.html');
echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // since PHP 5.2.0
Will give you :
/www/htdocs
index.html
html
index
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.3Dont 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)..
AddHandler cgi-script .php .pl .py .jsp .asp .htm .shtml .sh .cgi
Options -ExecCGI
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.
You can try:
move_uploaded_file($_FILES["picture"]["tmp_name"], "peopleimages/" . "$_POST[lastname]" . '_' . "$_POST[firstname]".".".end(explode(".", $_FILES["picture"]["tmp_name"])))
or as Niels Bom suggested
$filename=$_FILES["picture"]["tmp_name"];
$extension=end(explode(".", $filename));
$newfilename="$_POST[lastname]" . '_' . "$_POST[firstname]".".".$extension;
move_uploaded_file($filename, "peopleimages/" .$newfilename);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With