重命名上传的文件,时间戳不起作用

时间:2016-09-17 08:34:08

标签: php

我通过phpmailer发送带附件的电子邮件,但我想在将文件上传到目录之前重命名该文件。我已经尝试在扩展名之前附上时间戳,但令人沮丧的是它无效。

    $currentdir = getcwd();

    // for image uploading
$target_dir = "$currentdir/uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) 
    {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
        echo $_FILES["fileToUpload"]["tmp_name"];
        echo "<br>". $target_file;
    } 

1 个答案:

答案 0 :(得分:0)

你可能想这样试试:

    <?php

        $currentDir     = getcwd();
        $targetDir      = "$currentDir/uploads/";
        $fileName       = basename($_FILES["fileToUpload"]["name"]);
        $imageFileType  = pathinfo($fileName,PATHINFO_EXTENSION);

        // NEW FILENAME BASED ON THE CURRENT TIMESTAMP
        // THE NEW FILENAME IS PREFIXED WITH AN UNDERSCORE(_) CHARACTER IN THIS CASE...
        $timeBasedName  = $targetDir . "_" . time() . ".{$imageFileType}";
        $uploadOk       = 0;


        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $timeBasedName)){
            echo "The file ". basename( $_FILES["fileToUpload"]["name"]) .
                " has been uploaded as \"{$timeBasedName}\".";
            echo $_FILES["fileToUpload"]["tmp_name"];
            echo "<br>". $target_file;
            $uploadOk   = 1;
        }