在上传文件时找到扩展名? [英] finding the extension a file on upload?

查看:180
本文介绍了在上传文件时找到扩展名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在这里做什么,获取当前文件,然后上传它,找到文件的扩展名并重命名!并回应结果!但似乎错了,我不知道哪一部分! :((

what im trying to do here, get the current file and then upload it,find the extension of the file and rename it! and echo the result!! but it seems wrong, and i dnt know which part!! :((

    $fieldname = $_REQUEST['fieldname'];
    $uploaddir = 'uploads/';
    $uploadfile = $uploaddir . basename($_FILES[$fieldname]['name']);


    if (move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadfile)) {

    //find the extension
     $extension= pathinfo($uploadfile);

    //rename the file
      rename ($uploadfile, "newfile.".$extenion['extension']."");
 echo "uploads/newfile.'".$extension['extension']."'"; // "success"

}


推荐答案

我想你应该这样做:

$fieldname = $_POST['fieldname']; // don't use $_REQUEST
$extension = pathinfo($_FILES[$fieldname]['name'], PATHINFO_EXTENSION);

$uploaddir = 'uploads/';
$uploadfile = $uploaddir . 'newfile.'.$extension;

if (move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadfile)) {
    // success
}


$ b $已经重命名该文件,没有必要手动调用重命名 b

move_uploaded_file

您可能还注意到,我已经将 PATHINFO_EXTENSION 通过 pathinfo ,因为您只需要扩展名,而不是完整的路径信息。

You probably also noticed that I've passed PATHINFO_EXTENSION to pathinfo, since you need only the extension and not the complete path information.

最后,我使用 $ _POST 而不是 $ _ REQUEST 。你不应该使用 $ _ REQUEST ,除非你真的知道你在做什么。这可能会导致来自Cookie或会话的意外变量篡改,例如。

Lastly, I used $_POST instead of $_REQUEST. You shouldn't use $_REQUEST unless you really know what you are doing. This could lead to unexpected variables tampering from cookies or session, per example.

这篇关于在上传文件时找到扩展名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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