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

时间:2022-02-07 10:31:50

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。[原始扩展名]。我目前有:

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!

7 个解决方案

#1


30  

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

你需要先找出原来的扩展名是什么;-)

To do that, the pathinfo function 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 valid characters
    • And, BTW, you should use $_POST['lastname'] -- see Why is $foo[bar] wrong?
    • 而且,顺便说一下,你应该使用$ _POST ['lastname'] - 看看为什么$ foo [bar]错了?

  • 在你的情况下,你应该逃避$ _POST [lastname],以确保它只包含有效字符而且,顺便说一句,你应该使用$ _POST ['lastname'] - 请参阅为什么$ foo [bar]错了?

  • You should also check that the file is an image
    • See mime_content_type for PHP < 5.3
    • 请参阅PHP <5.3的mime_content_type

    • And/or finfo_file for PHP >= 5.3
    • 和/或finfo_file for PHP> = 5.3

  • 您还应检查该文件是否为图像请参阅mime_content_type for PHP <5.3和/或finfo_file for PHP> = 5.3

#2


4  

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

.htaccess规则拒绝在某个文件夹中执行php是这样的(为你的设置定制)..

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.

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

#3


4  

You can try:

你可以试试:

move_uploaded_file($_FILES["picture"]["tmp_name"], "peopleimages/" . "$_POST[lastname]" . '&#95;' . "$_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]" . '&#95;' . "$_POST[firstname]".".".$extension;
move_uploaded_file($filename, "peopleimages/" .$newfilename);

#4


3  

this code is insecure

这段代码不安全

move_uploaded_file($_FILES["picture"]["tmp_name"], "peopleimages/" . "$_POST[lastname]" . '&#95;' . "$_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

#5


2  

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

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.

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

With $_FILE uploads, you are also given a type 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:

使用$ _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类型列表。

#6


0  

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

#7


0  

you could always:

你可以永远:

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

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

#1


30  

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

你需要先找出原来的扩展名是什么;-)

To do that, the pathinfo function 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 valid characters
    • And, BTW, you should use $_POST['lastname'] -- see Why is $foo[bar] wrong?
    • 而且,顺便说一下,你应该使用$ _POST ['lastname'] - 看看为什么$ foo [bar]错了?

  • 在你的情况下,你应该逃避$ _POST [lastname],以确保它只包含有效字符而且,顺便说一句,你应该使用$ _POST ['lastname'] - 请参阅为什么$ foo [bar]错了?

  • You should also check that the file is an image
    • See mime_content_type for PHP < 5.3
    • 请参阅PHP <5.3的mime_content_type

    • And/or finfo_file for PHP >= 5.3
    • 和/或finfo_file for PHP> = 5.3

  • 您还应检查该文件是否为图像请参阅mime_content_type for PHP <5.3和/或finfo_file for PHP> = 5.3

#2


4  

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

.htaccess规则拒绝在某个文件夹中执行php是这样的(为你的设置定制)..

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.

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

#3


4  

You can try:

你可以试试:

move_uploaded_file($_FILES["picture"]["tmp_name"], "peopleimages/" . "$_POST[lastname]" . '&#95;' . "$_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]" . '&#95;' . "$_POST[firstname]".".".$extension;
move_uploaded_file($filename, "peopleimages/" .$newfilename);

#4


3  

this code is insecure

这段代码不安全

move_uploaded_file($_FILES["picture"]["tmp_name"], "peopleimages/" . "$_POST[lastname]" . '&#95;' . "$_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

#5


2  

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

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.

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

With $_FILE uploads, you are also given a type 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:

使用$ _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类型列表。

#6


0  

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

#7


0  

you could always:

你可以永远:

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

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