用PHP重命名上传的文件,但保留扩展名 [英] Rename an uploaded file with PHP but keep the extension
问题描述
我使用PHP将图像从表单上传到服务器,并且想要重命名图像lastname_firstname。[original extension]。我目前有:
$ b $ pre $ lt; code> move_uploaded_file($ _ FILES [picture] [tmp_name],peopleimages /。$ _POST [lastname]。'_'。$ _POST [firstname])
当然,其中,没有扩展名重命名文件lastname_firstname。如何重命名文件,但保留扩展名?
感谢!
你需要先找出原来的扩展名是什么; - )
要做到这一点, pathinfo
函数可以创造奇迹; - )
引用手册中给出的例子:
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ path_parts = PATHINFO( '/ WWW / htdocs中/ index.html中');
echo $ path_parts ['dirname'],\\\
;
echo $ path_parts ['basename'],\\\
;
echo $ path_parts ['extension'],\\\
;
echo $ path_parts ['filename'],\\\
; //自PHP 5.2.0开始
会给你:
/ www / htdocs
index.html
html
索引
作为旁注,不要忘记安全性:
$ ul
$ _ POST [lastname]
,以确保它只包含有效的字符- 而且,顺便说一句,您应该使用
$ _ POST ['lastname']
- 参见为什么$ foo [ bar]
错误?
- 请参阅
mime_content_type
5.3 - 和/或 <$对于PHP> = 5.3
code> finfo_file
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 :
- In your case, you should escape
$_POST[lastname]
, to make sure it only contains valid characters- And, BTW, you should use
$_POST['lastname']
-- see Why is$foo[bar]
wrong?
- And, BTW, you should use
- You should also check that the file is an image
- See
mime_content_type
for PHP < 5.3 - And/or
finfo_file
for PHP >= 5.3
- See
这篇关于用PHP重命名上传的文件,但保留扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!