用PHP重命名上传的文件,但保留扩展名 [英] Rename an uploaded file with PHP but keep the extension

查看:107
本文介绍了用PHP重命名上传的文件,但保留扩展名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用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] 错误?


    • 您应该检查文件是图片


      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
      • You should also check that the file is an image

      这篇关于用PHP重命名上传的文件,但保留扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆