简体   繁体   English

使用 php 上传后如何重命名文件名?

[英]How do I rename a filename after uploading with php?

How do I rename the file either before or after it gets uploaded?如何在文件上传之前或之后重命名文件? I just want to rename the filename, not the extension.我只想重命名文件名,而不是扩展名。

$changeTXT = $_SESSION['username'];
$uploaderName = strtolower($changeTXT);
$changeTXT = strtolower($changeTXT);
$changeTXT = ucfirst($changeTXT);
$filelocation = $_POST['userfile'];
$filename = $_POST['filename'];
$max_size = $_POST['MAX_FILE_SIZE'];

$file = $_FILES['userfile'];

$allowedExtensions = array("wma", "mp3", "wav");

function isAllowedExtension($fileName) {
  global $allowedExtensions;

  return in_array(end(explode(".", $fileName)), $allowedExtensions);
}

if($file['error'] == UPLOAD_ERR_OK) {
  if(isAllowedExtension($file['name'])) {

$uploaddir = "uploads/".$uploaderName."/";

$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {

    echo "Thank you for uploading your music!<br /><br />";

} else {

    echo "Your file did not upload.<br /><br />";

}

    echo "\n";

    echo "<a href='index.php'>Return</a> to index.<br /><br />$uploaddir";

} else {

    echo "You have tried to upload an invalid file type.<br /><br />";

  }

} else die("Cannot upload");

When using move_uploaded_file you get to pick the filename, so you can pick anything you want.使用move_uploaded_file时,您可以选择文件名,因此您可以选择任何您想要的。

When you upload the file, its put into a temporary directory with a temporary name, move_uploaded_file() allows you to move that file and in that you need to set the name of the file as well.当您上传文件时,将其放入具有临时名称的临时目录中, move_uploaded_file()允许您移动该文件,并且您还需要设置文件的名称。

I'd suggest you to check out Verot's File Upload class.我建议您查看 Verot 的文件上传 class。 It heals a lot of the pain of file uploading via php, and makes your code much more readable / maintainable.它解决了通过 php 上传文件的许多痛苦,并使您的代码更具可读性/可维护性。

Here is the link to the class and documentation.这是class 和文档的链接

As to the precise answer to your question: To give a new name to an uploaded file, put it as second argument to your move_uploaded_file() function.至于您问题的确切答案:要为上传的文件指定一个新名称,请将其作为 move_uploaded_file() function 的第二个参数。

Since you want to keep the extension, store it first in a variable:由于您想保留扩展名,请先将其存储在变量中:

$ext = explode('.',$_FILES['uploaded']['name']);
$extension = $ext[1];

You could use the file root name to generate the new name (here, with a timestamp appended to it):您可以使用文件根名称来生成新名称(此处附加时间戳):

$newname = $ext[0].'_'.time();

Say you uploaded a file, and your form input variable name is "myfile.png" it will become 'myfile_2343544.png';假设您上传了一个文件,并且您的表单输入变量名称为“myfile.png”,它将变为“myfile_2343544.png”;

Now, combine the local path to the target directory, the $newname var and the file's extension to set the function's second argument:现在,结合目标目录的本地路径、$newname 变量和文件扩展名来设置函数的第二个参数:

$full_local_path = 'path/to/your/filefolder/'.$newname.'.'.$extension ;
move_uploaded_file($_FILES['uploaded']['tmp_name'], $full_local_path);

Why not just save it with a different name:为什么不使用不同的名称保存它:

Just change the name of the $uploadfile variable:只需更改 $uploadfile 变量的名称:

$uploadfile = $uploaddir . "somefilename" . end(explode(".", $file['name']));

It wouldn't hurt however if you refactord your code a little.但是,如果您稍微重构一下代码,它不会受到伤害。

You can use the second param in move_uploaded_file to set the filename.您可以使用 move_uploaded_file 中的第二个参数来设置文件名。 The first param is the filename of the file in your /tmp folder and the second param is the file dir and the new filename.第一个参数是 /tmp 文件夹中文件的文件名,第二个参数是文件目录和新文件名。

move_uploaded_file($_FILES['file']['tmp_name'], "/new/file/dir/".[the new file name]);

I know this is an old question but there wasn't a clear answer.我知道这是一个老问题,但没有明确的答案。

When you do当你这样做

$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {

Just set $uploadfile to the whole path of the desired filename;只需将 $uploadfile 设置为所需文件名的整个路径; ie "uploads/mynewfilename.jpg"即“上传/mynewfilename.jpg”

    <?php

  /*
     Just change the $path variable to your uploads path
     and dont forget the  / at the end of the  path.

     The way this function works is .When the user submits the form
     the uniqueFilename() function checks to see if there is a filename
     in your uploads folder, that has the same name as the one you intend
     to upload. If it finds a filename that has the same name as the one you want to
     upload it goes through the next steps


        Step 1

    strrpos($arg1,$arg2) - we use it to find the location where upload path ends and where the filename begins

    $arg1 = the filepath including the filename ex. uploads/myFile.jpg
    $arg2 = basename($filename); what this does is it  strips the path from the string and returns only the filename.

    When we use strrpos($arg1,$arg2) we basically tell the function to find the position of the path and exclude the filename

    Step 2

    substr($arg1,$arg2,$arg3) - looks in a string and extrats only the parts from the string that you want. We use it now to extract the uploads path.

    $arg1 = the full path of the uploaded file. ex. uploads/myFile.jpg
    $arg2 = 0  because we want to start from the begginning of the string
    $arg3 = $pathlocation which is the location of where the uploadpath ends and the file beggins

    when we use substr() here we intend to extract the uploads path.

    Step 3

    basename($arg1) strips out a path and returns the filename

    - we use this to save the original filename

    Notice that so far we have the path to the files saved and also
    the filename with its extension. We also have the file extension (.jpg|.png) or whatever


    Step 4

    pathinfo() - extracts the extension from the filename

    Step 5

    we us strrpos() to find the location of the last dot ( . ) in the filename because in step 6
    we use this location to cut the string where the dot ( . ) is

    Step 6

    substr() gets the file without the extension

    Step 7
    substr() takes the filename without extension and clips out the last charcter
    so if the filename is myFile this function would return myFil

    Step 8
    substr() again we use it to save the last character of the file so
                if our file is called myFile it would return e.

    Step 9
    Here we check to see if the last character of our file is numeric.
    Why do this? Because if the last character of a file is numeric we can just add a number to the
    file and end up with a new file with an added number so our file is
    myFile1 the 1 is numeric so our intention is to add to it
    so my myFile1 would end up being myFile2. But what happens if our last character is not numeric?

    then we just add -1 to the file so that myFile would end up being myFile-1

    Step 10
    Since our filename exists in the database we must call the function uniqueFilename() again so that we can
    check and see if the new name exists in the database.

    This function basically keeps calling itself until it finds a filename that does not exists.
   */





    if(isset($_POST['submit'])){

    $path = "uploads/";

    $fullPath = $path.$_FILES['uploadFile']['name'];
    $full_local_path = $path.uniqueFilename($fullPath) ;
    move_uploaded_file($_FILES['uploadFile']['tmp_name'], $full_local_path);
    }
          /*
             * Function returns a unique filename
             * Param 1 is the path of the filename and the filename
             * returns filename with no path
             */
            function uniqueFilename($filepathAndFilename){

                // check to see if file exists
                if (file_exists($filepathAndFilename))
                {
                        /* step 1 */

                    //Get the path location without the basename
                  $filePathWithoutFilenameLocationInString = strrpos($filepathAndFilename,basename($filepathAndFilename));

                        /* step 2 */

                    //Get the path and cut the basename
                    $path = substr($filepathAndFilename,0,$filePathWithoutFilenameLocationInString);

                        /* Step 3*/
                    //Get the base filename
                    $filename = basename($filepathAndFilename);

                       /* Step 4 */
                       // get the extension
                    $fileExtension = pathinfo($filename, PATHINFO_EXTENSION);

                        /* Step 5 */
                    // find the position of the last dot
                    $dotLocation = strrpos($filename,'.');

                        /* Step 6 */
                    // Get the filename without the dot
                    $fileWithNoExtension = substr($filename,0,$dotLocation);

                        /* Step 7 */
                    //Get the name without the last character
                    $filenameMinusLastCharacter = substr($fileWithNoExtension,0,-1);

                       /* Step 8 */
                    //save the last character
                    $lastFilenameCharacter = substr($fileWithNoExtension,-1);

                        /* Step 9*/
                    //if the last character is numeric add 1
                    if (is_numeric($lastFilenameCharacter))
                    {
                        $newFilename = $path.$filenameMinusLastCharacter.($lastFilenameCharacter+1).'.'.$fileExtension;
                        //recursively call itself

                         /* Step 10*/
                        $results = uniqueFilename($newFilename);
                        return basename($results);
                    }else{

                        // if the last character is not numeric then add 1
                        $newFilename = $path.$fileWithNoExtension.'-1'.'.'.$fileExtension;

                            /* Step 10*/
                        //recursively call itself
                        $results = uniqueFilename($newFilename);
                        return basename($results);
                    }

                }
                return basename($filepathAndFilename);

            }
    ?>

    <!doctype html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Untitled Document</title>
    </head>

    <body>

    <form method="post" enctype="multipart/form-data"/>
    <label>Upload File</label>
    <input type="file" name="uploadFile"/>
    <input type="submit" name="submit" value="submit"/>
    </form>

    </body>
    </html>`enter code here`

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

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