使用 PHP 重命名上传的文件但保留扩展名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2562851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:57:16  来源:igfitidea点击:

Rename an uploaded file with PHP but keep the extension

phpfile-upload

提问by bsamek

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:

我正在使用 PHP 将图像从表单上传到服务器,并希望重命名图像 lastname_firstname.[original extension]。我目前有:

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?

当然,这会重命名文件 lastname_firstname 而不带扩展名。如何重命名文件但保留扩展名?

Thanks!

谢谢!

回答by Pascal MARTIN

You need to first find out what the original extension was ;-)

您需要首先找出原始扩展名是什么;-)

To do that, the pathinfofunction can do wonders ;-)

为此,该pathinfo函数可以创造奇迹 ;-)


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 validcharacters
  • You should also check that the file is an image
  • 在您的情况下,您应该转义$_POST[lastname],以确保它只包含有效字符
  • 您还应该检查文件是否是图像

回答by kviksilver

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

或者像 Niels Bom 建议的那样

$filename=$_FILES["picture"]["tmp_name"];
$extension=end(explode(".", $filename));
$newfilename="$_POST[lastname]" . '_' . "$_POST[firstname]".".".$extension;
move_uploaded_file($filename, "peopleimages/" .$newfilename);

回答by dmp

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 ;)

不要忘记,如果您允许人们上传任意文件,而无需检查扩展名,他们可以完美地上传 .php 文件并在您的服务器上执行代码;)

The .htaccess rules to deny php execution inside a certain folder is something like this (tailor for your setup)..

拒绝在某个文件夹内执行 php 的 .htaccess 规则是这样的(为您的设置量身定制)。

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.

将其放入 .htaccess 文件中,放入您上传文件的文件夹中。

Otherwise, just bear in mind that files may have more than one "." in them, and you should be golden.

否则,请记住文件可能有多个“.”。在他们,你应该是金色的。

回答by za_al

this code is insecure

此代码不安全

move_uploaded_file($_FILES["picture"]["tmp_name"], "peopleimages/" . "$_POST[lastname]" . '_' . "$_POST[firstname]". $extension);

if

如果

$_POST[firstname] =mypicture.php%00

and

$extension=.jpg;

this code is vulnerable and result is

此代码易受攻击,结果是

test.php%00.jpg //test.php uploaded on server.

for more information check this link:

有关更多信息,请查看此链接:

https://www.owasp.org/index.php/Unrestricted_File_Upload

https://www.owasp.org/index.php/Unrestricted_File_Upload

回答by zneak

First, find the extension:

首先,找到扩展名:

$pos = strrpos($filename, '.');
if ($pos === false) 
{
    // file has no extension; do something special?
    $ext = "";
}
else
{
    // includes the period in the extension; do $pos + 1 if you don't want it
    $ext = substr($filename, $pos);
}

Then call your file anyhow you want, and append to the name the extension:

然后以任何方式调用您的文件,并将扩展名附加到名称中:

$newFilename = "foobar" . $ext;
move_uploaded_file($_FILES['picture']['tmp_name'], 'peopleimages/' . $newFilename);


EDITThinking of it, none of this is optimal. File extensions most oftendescribe 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.

编辑想想看,这些都不是最佳选择。文件扩展名最常描述文件类型,但情况并非总是如此。例如,您可以将 .png 文件重命名为 .jpg 扩展名,大多数应用程序仍会检测到它是 png 文件。除此之外,某些操作系统根本不使用文件扩展名来确定文件的类型。

With $_FILEuploads, you are also given a typeelement 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:

通过$_FILE上传,您还会获得一个type元素,该元素表示您收到的文件的 MIME 类型。如果可以,我建议您依靠它而不是给定的扩展名:

$imagetypes = array(
    'image/png' => '.png',
    'image/gif' => '.gif',
    'image/jpeg' =>?'.jpg',
    'image/bmp' => '.bmp');
$ext = $imagetypes[$_FILES['myfile']['type']];

You can have a more complete list of MIME types here.

您可以在此处获得更完整的 MIME 类型列表

回答by mote

you could always:

你总是可以:

$original = explode('.', $_FILES["picture"]["tmp_name"]);
$extension = array_pop($original);

move_uploaded_file($_FILES["picture"]["tmp_name"], "peopleimages/" . "$_POST[lastname]" . '_' . "$_POST[firstname]". $extension);

回答by Chad Birch

move_uploaded_file($_FILES["picture"]["tmp_name"], "peopleimages/" . "$_POST[lastname]" . '_' . "$_POST[firstname]." . pathinfo($_FILES["picture"]["tmp_name"], PATHINFO_EXTENSION));