简体   繁体   English

如何在php中将上传的文件重命名为Username?

[英]How to rename uploaded file to Username in php?

How to write code for to upload the file that file should be saved with Username instead of original name. 如何编写代码以上传文件,该文件应使用用户名而不是原始名称保存。

 <?php
    if ($_POST['upload'] )
     {
     $user=$_session['username'];// current username
     //$filename=basename($_FILES["file"]["name"]);



     $tmp=$_FILES["file"]["tmp_name"];
      $extension = explode("/", $_FILES["file"]["type"]);
      $name=$user.".".$extension[1];

    move_uploaded_file($tmp, "upload/" . $user.".".$extension[1]);
     }  

 ?>

Error : 错误:

Notice: Undefined variable: _session in C:\\xampp\\htdocs\\aaa\\upload file.php on line 注意:未定义的变量:_session在C:\\ xampp \\ htdocs \\ aaa \\ upload file.php上线

当用户登录时,您是否在那时启动会话并将其存储在您正在使用的会话变量中,即$ _session ['username']

php SESSION syntax error php SESSION语法错误

$user = $_SESSION['username'];

Try this code, 试试这段代码,

   <?php
    if ($_POST['upload'] )
   {
       $user=$_SESSION['username'];// current username

        $filename = $user."_".$_FILES["file"]["name"];
        $newFilePath = "./upload/".$filename;

        if(move_uploaded_file($_FILES["file"]["tmp_name"],$newFilePath)) 
         {
              return true;
         }
            else
            {
                return false;
            }

  }
 ?>

start the session on very top line and session should be always in upper case ie SESSION . 在最顶层开始会话,会话应始终为大写,SESSION

Please consider the below code :- 请考虑以下代码: -

<?php
session_start();
if ($_POST['upload'] )
 {
 $user=$_SESSION['username'];// current username
 //$filename=basename($_FILES["file"]["name"]);

 $tmp=$_FILES["file"]["tmp_name"];
  $extension = explode("/", $_FILES["file"]["type"]);
  $name=$user.".".$extension[1];

move_uploaded_file($tmp, "upload/" . $name);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM