How to rename uploaded file before saving it into a directory?

前端 未结 5 882
清酒与你
清酒与你 2020-11-22 03:20

Below is the code I used in order to upload files into a directory. It works fine. My main question is:

move_uploaded_file() is the one that saves t

相关标签:
5条回答
  • 2020-11-22 03:56

    You guess correctly. Read the manual page for move_uploaded_file. Set the second parameter to whereever your want to save the file.

    If it doesn't work, there is something wrong with your $fileName. Please post your most recent code.

    0 讨论(0)
  • 2020-11-22 03:58

    You can Try this,

    $newfilename= date('dmYHis').str_replace(" ", "", basename($_FILES["file"]["name"]));
    
    move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);
    
    0 讨论(0)
  • 2020-11-22 04:04

    The move_uploaded_file will return false if the file was not successfully moved you can put something into your code to alert you in a log if that happens, that should help you figure out why your having trouble renaming the file

    0 讨论(0)
  • 2020-11-22 04:12
    /* create new name file */
    $filename   = uniqid() . "-" . time(); // 5dab1961e93a7-1571494241
    $extension  = pathinfo( $_FILES["file"]["name"], PATHINFO_EXTENSION ); // jpg
    $basename   = $filename . "." . $extension; // 5dab1961e93a7_1571494241.jpg
    
    $source       = $_FILES["file"]["tmp_name"];
    $destination  = "../img/imageDirectory/{$basename}";
    
    /* move the file */
    move_uploaded_file( $source, $destination );
    
    echo "Stored in: {$destination}";
    
    0 讨论(0)
  • 2020-11-22 04:13

    You can simply change the name of the file by changing the name of the file in the second parameter of move_uploaded_file.

    Instead of

    move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $_FILES["file"]["name"]);
    

    Use

    $temp = explode(".", $_FILES["file"]["name"]);
    $newfilename = round(microtime(true)) . '.' . end($temp);
    move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);
    

    Changed to reflect your question, will product a random number based on the current time and append the extension from the originally uploaded file.

    0 讨论(0)
提交回复
热议问题