简体   繁体   中英

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 ['username']

php SESSION syntax error

$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 .

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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