Rename an uploaded file with PHP but keep the extension

后端 未结 7 1344
悲&欢浪女
悲&欢浪女 2020-12-04 20:24

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_upl         


        
7条回答
  •  半阙折子戏
    2020-12-04 21:09

    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?
    • 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

提交回复
热议问题