更改通过表单上传的 tmp 文件的文件名

2024-04-28

就像标题说我想更改用户通过表单上传的文件的文件名。这是代码

HTML

    <form action="editprofile.php" method="POST" enctype="multipart/form-data">
         <p>Upload your image:<p /><input type="file" name="myfile"></p><br />
         <p><input type="radio" name="type" value="defaultDot">Use Default</p>
         <p><input type="submit" name="updateAvatar"></p>
    </form>

这是我的 php 脚本,它将上传的文件移动到正确的目录
PHP

    $name = $_FILES['myfile']['name'];
    $tmp_name = $_FILES['myfile']['tmp_name'];
    $size = getimagesize($_FILES['myfile']['tmp_name']);
    if($name){
        //start upload process
        if($size != FALSE){
            $location = "images/avatars/$name";
            move_uploaded_file($tmp_name, $location);
            $query = mysql_query("UPDATE users SET avatar='$location' WHERE id=$id");
            $avaMessage = '<p><font size=2 color=aqua face=Tahoma>Avatar Updated - Uploaded Image!.</font></p>';
        }else{
            $avaMessage = '<p><font size=2 color=red face=Tahoma>Please only submit image files!</font></p>';
        }
    }

我怎样才能给图像一个自定义名称?例如我有一个名为$用户名它存储用户名的会话变量。如果我想将图像命名为$用户名具有相同文件扩展名的变量?

编辑:编辑:编辑:
添加了您的 if 语句劳伦斯,我交换了 move_upload_files 中的变量,但它仍然不起作用......
Code

if($_SERVER['REQUEST_METHOD']=='POST' && isset($username) && is_numeric($id)
&& isset($_FILES['myfile']['error']) && $_FILES['myfile']['error']=='UPLOAD_ERR_OK'){
if($_POST['type'] != "defaultDot"){
    //$avaURL = $_POST['url'];
    //$updateURL = mysql_query("UPDATE users SET avatar='$avaURL' WHERE id=$id");
    //$avaMessage = '<p><font size=2 color=aqua face=Tahoma>Avatar Uploaded!</font></p>';
    $name    = basename($_FILES['myfile']['name']);
    $ext     = end(explode('.', $name));
    $move_to = "images/avatars/".preg_replace('/[^a-zA-Z0-9.-]/s', '_',$username).'.'.$ext;
    $info    = getimagesize($_FILES['myfile']['tmp_name']);

    if($name){
        //start upload process
            $allowed = array('image/png','image/jpg','image/gif');
            if($info[0]>0 && $info[1] > 0 && in_array($info['mime'],$allowed)){
                if($info[0]>200 || $info[1] > 200){
                    //File dimensions too large
                    $avaMessage = '<p><font size=2 color=red face=Tahoma>File dimensions too large.</font></p>';
                }else{
                    //File put contents will over write if file exsist
                    move_uploaded_file($_FILES['myfile']['tmp_name'], $move_to);
                    mysql_query("UPDATE users
                                SET avatar='".mysql_real_escape_string($move_to)."' 
                                WHERE id=".$id." AND owner='".$_SESSION['username']."'");
                    $avaMessage = 'Avatar Updated - Uploaded Image!.';
                }
            }else{
                $avaMessage = '<p><font size=2 color=red face=Tahoma>Please only submit image files!</font></p>';
            }   
    }else{
        $avaMessage = '<p><font size=2 color=red face=Tahoma>Please select a file!</font></p>';
    }

}else{
$avaURL = 'images/avatars/default.png';
$updateURL = mysql_query("UPDATE users SET avatar='$avaURL' WHERE id=$id");
$avaMessage = '<p><font size=2 color=aqua face=Tahoma>Avatar Updated - Default.</font></p>';
}
}

即使使用固定的“POST”劳伦斯仍然无法工作......


这是一种安全可靠的方法,发布请求需要检查,只需检查$name是不足够的,$username需要删除任何特殊字符,$id需要检查其设置并且是数字,需要查找文件特定类型扩展名,还允许需要交叉匹配的 mime 类型,加上需要检查的宽度和高度尺寸,需要考虑很多,上传可能非常不安全,更不用说图像可以注入 php到文件注释中,如果处理不正确可能会被执行:

<?php 

if($_SERVER['REQUEST_METHOD']=='POST' && isset($username) && is_numeric($id)
&& isset($_FILES['myfile']['error']) && $_FILES['myfile']['error']=='UPLOAD_ERR_OK'){

    $name    = basename($_FILES['myfile']['name']);
    $ext     = end(explode('.', $name));
    $move_to = "images/avatars/".preg_replace('/[^a-zA-Z0-9.-]/s', '_',$username).'.'.$ext;
    $info    = getimagesize($_FILES['myfile']['tmp_name']);

    //not more then 200px
    if($info[0]>200 || $info[1] > 200){
        //file too large
    }

    $allowed = array('image/png','image/jpg','image/gif');
    if($info[0]>0 && $info[1] > 0 && in_array($info['mime'],$allowed)){
        move_uploaded_file($_FILES['myfile']['tmp_name'],$move_to);
        mysql_query("UPDATE users
                     SET avatar='".mysql_real_escape_string($move_to)."' 
                     WHERE id=".$id." AND owner='".$_SESSION['username']."'");
        $avaMessage = 'Avatar Updated - Uploaded Image!.';
    }else{
        //Not allowed
    }
}
?>

<form action="" method="POST" enctype="multipart/form-data">
     <!--1 MB = 1048576 bytes-->
     <input type="hidden" name="MAX_FILE_SIZE" value="1048576" />

     <p>Upload your image:<p /><input type="file" name="myfile"></p><br />
     <p><input type="radio" name="type" value="defaultDot">Use Default</p>
     <p><input type="submit" name="updateAvatar"></p>
</form>

UPDATE EDIT Here is an OOP version of the upload process, perhaps you will find it interesting, I added all possible errors too ;p
<?php 
Class updateUserAvatar{
    public $upload_path;
    public $full_path;
    public $name;
    public $size;
    public $ext;
    public $output;
    public $input;
    public $prefix;
    private $allowed;

    function upload(){
        if($_SERVER['REQUEST_METHOD'] == 'POST'){
            if(isset($_FILES[$this->input]['error'])){
                if($_FILES[$this->input]['error'] == 0){
                    $this->name      = basename($_FILES[$this->input]['name']);
                    $file_p          = explode('.', $this->name);
                    $this->ext       = end($file_p);
                    $this->full_path = rtrim($this->upload_path,'/').'/'.preg_replace('/[^a-zA-Z0-9.-]/s', '_', $this->prefix).'.'.$this->ext;
                    $info            = getimagesize($_FILES[$this->input]['tmp_name']);
                    $this->size      = filesize($_FILES[$this->input]['tmp_name']);

                    if($info[0]>$this->allowed['dimensions']['width'] || $info[1] > $this->allowed['dimensions']['height']){
                        $this->output = 'File dimensions too large!';
                    }else{
                        if($info[0] > 0 && $info[1] > 0 && in_array($info['mime'],$this->allowed['types'])){
                            move_uploaded_file($_FILES[$this->input]['tmp_name'],$this->full_path);
                            $this->output = 'Upload success!';
                        }else{
                            $this->output = 'File not supported!';
                        }
                    }
                }else{
                    if($_FILES[$this->input]['error']==1){$this->output = 'The uploaded file exceeds the upload_max_filesize directive!';}
                    if($_FILES[$this->input]['error']==2){$this->output = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in our HTML form!';}
                    if($_FILES[$this->input]['error']==3){$this->output = 'The uploaded file was only partially uploaded!';}
                    if($_FILES[$this->input]['error']==4){$this->output = 'No file was uploaded!';}
                    if($_FILES[$this->input]['error']==6){$this->output = 'Missing a temporary folder!';}
                    if($_FILES[$this->input]['error']==7){$this->output = 'Failed to write uploaded file to disk!';}
                    if($_FILES[$this->input]['error']==8){$this->output = 'A PHP extension stopped the file upload!';}
                }
            }
        }
    }

    function setPath($var){
        $this->upload_path = $var;
    }
    function setAllowed($var=array()){
        $this->allowed = $var;
    }
    function setFilePrefix($var){
        $this->prefix = preg_replace('/[^a-zA-Z0-9.-]/s', '_', $var);
    }
    function setFormInput($var){
        $this->input = $var;
    }
}//END CLASS


if($_POST['type'] != "defaultDot"){
    //Setup
    $upload = new updateUserAvatar();
    $upload->setPath('./images/avatars/');
    $upload->setFilePrefix($username);
    $upload->setAllowed(array('dimensions'=>array('width'=>200,'height'=>200),
                              'types'=>array('image/png','image/jpg','image/gif')));
    $upload->setFormInput('myfile');
    $upload->upload();

    if($upload->output == 'Upload success!'){
        //do query
        $updateURL = mysql_query("UPDATE users SET avatar='$upload->full_path' WHERE id=$id");
    }
    //message
    $avaMessage = $upload->output;
}else{
    $avaURL = 'images/avatars/default.png';
    $updateURL = mysql_query("UPDATE users SET avatar='$avaURL' WHERE id=$id");
    $avaMessage = '<p><font size=2 color=aqua face=Tahoma>Avatar Updated - Default.</font></p>';
}
?>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

更改通过表单上传的 tmp 文件的文件名 的相关文章

  • 通过 AJAX jquery 更改表格背景颜色?

    设想 当我的网页加载时 自动搜索单元格已由用户输入并且具有价值 如果已输入 表格背景颜色将为红色 否则为绿色 假设该表尚未输入 桌子背景绿色是这样的 和表的源代码 table width 1023 height 200 border 1 t
  • 无法使用 PHP ftp_connect() 连接 FTP 服务器

    我试图使用 PHP 的 ftp connect 函数连接 ftp 服务器 如下所示 但它返回这个错误 警告 ftp connect function ftp connect php network getaddresses getaddri
  • 在 PHP 中验证约 400MB 的大型 XML 文件

    我有一个很大的 XML 文件 大约 400MB 在开始处理之前我需要确保它的格式正确 我尝试的第一件事是类似于下面的内容 这很棒 因为我可以找出 XML 是否格式不正确以及 XML 的哪些部分 不好 doc simplexml load s
  • 是否可以共享 Symfony2 安装(一台服务器上的多个网站 [域])

    我想在一个根 服务器 下托管多个基于 Symfony2 的网站 是否可以共享 symfony 自己的文件 供应商等 有人知道教程吗 管理起来困难吗 AFAIK Symfony 安装大约有 600MB 我不想以冗余方式保存它 我看起来确实有可
  • Bash - 在 perl 正则表达式中使用变量以及匹配组

    这是我在 stackoverflow 上的第一篇文章 如果我错过了一些重要的内容 请原谅我 我目前遇到以下问题 目标是根据我准备的文件列表动态替换端口号find 这些文件中的所有端口均以数字 4 开头 有 5 位数字 现在是棘手的部分 我只
  • phpunit --debug 仍然只显示点

    我想查看 phpunit 运行期间当前执行的测试 我用 debugparam 但仍然只得到点 phpunit debug PHPUnit 3 7 19 by Sebastian Bergmann Configuration read fro
  • PHP 中两个关联多维数组的值求和

    我正在尝试对两个关联数组的值求和 这是第一个数组 Array Jan 01 2013 gt Array COM gt 100 RES gt 200 Oct 28 2014 gt Array COM gt 300 RES gt 400 这是第
  • 在 while 循环之外使用变量(作用域)

    关于 PHP 范围的小问题 我似乎无法在 while 循环之外调用变量 report 我尝试过各种事情 包括return 这不起作用 这里唯一起作用的两个函数是如果我echo变量 report在循环内 或者如果我print它 我不想这样做
  • Facebook PHP API 登录时抛出异常

    我尝试使用 Facebook Graph API 登录并获取用户信息 我用来获取用户信息的代码以前可以工作 但今天我尝试使用 Facebook 登录 但 Facebook API 抛出此错误 未定义的偏移量 1 home vendor fa
  • PHP mail() 函数发送电子邮件,但需要 10 多分钟才能显示

    因此 我的用户从手机上的 Android 应用程序进行注册 注册成功后 我会触发一封邮件发送到注册的电子邮件地址 其中包含来自我的 PHP 脚本的激活密码 这是我使用的代码行 非常简单 mail to subject message hea
  • 液体字符串中的转义字符

    我正在尝试将包含各种尺寸的标签列表放在一起 在 Shopify 中使用 Liquid 尺寸使用单引号和双引号表示英寸和英尺 因为它同时使用两者 所以会导致字符串正确关闭的问题 我尝试过使用标准转义字符 但这似乎不起作用 是否可以在 Liqu
  • 如何从 jquery .load 获取 php 响应

    例如我给出另一个代码 这是我的 some3 php 代码 第一个文件
  • 迁移时未找到 Laravel 致命错误类

    我已经跑了artisan migrate reset 我删除了一些迁移文件 因为我不再需要这些表 I ran composer dump autoload其次是artisan dump autoload I ran artisan migr
  • Symfony 5.4 Security Bundle,注册后无法登录

    我在 5 4 版本上构建空的新项目 我使用这些命令来构建项目 composer create project symfony skeleton 5 4 testapp54 cd testapp54 composer require weba
  • 从字符串中删除第一个和最后一个字符

    我有这个 dataList one two three list explode dataList echo pre print r list echo pre 其输出 gt Array gt 0 gt gt 1 gt one gt 2 g
  • 使用mysql数据按高低价格排序

    这是我所拥有的以及我想做的 我的 MySql 数据库中有 12 个项目 4 个产品为 4 99 4 个产品为 3 99 4 个产品为 2 99 我意识到我可以像这样查询数据库 它会给我一个该价格的产品列表
  • 如何将事件插入为 - Out Office

    我目前正在使用 Google Calendar API 并尝试在我的谷歌日历中插入新的 外出 事件 我使用以下代码插入事件 client getClient service new Google Service Calendar clien
  • 如何在刀片模板中通过引用 @include 来传递变量?

    在 Laravel 4 2 设置中 我在模板中有一个变量 我希望在多个包含之间共享该变量 主刀 This is the variable include header lt in header blade I often use tabin
  • 为什么使用自动激活文件句柄的三参数开放调用是 Perl 最佳实践?

    我有两个关于 Perl 的问题open功能 1 我好像记得从Perl 最佳实践的 3 参数版本open比两个参数版本更好 例如 open OUT gt gt file vs open OUT gt gt file 这是为什么 前几天我试图告
  • 多个数据库连接

    我有三张桌子 categories content info and content The categories表包含类别的id及其 IDparent类别 The content info包含两列 entry id帖子的 ID 和cat

随机推荐