【问题标题】:How to rename each file before uploading to server to a time-stamp如何在上传到服务器之前将每个文件重命名为时间戳
【发布时间】:2014-06-11 18:27:23
【问题描述】:

我正在使用以下代码上传一些文件,但是由于名称相似,因此有些文件被替换了。我只是想知道如何更改名称,我试过了,但我发现自己弄乱了整个代码。

PHP

if (!empty($_FILES["ambum_art"])) {
    $myFile = $_FILES["ambum_art"];
    if ($myFile["error"] !== UPLOAD_ERR_OK) {
       echo "<p>An error occurred.</p>";
        exit;
    }
    $name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
    $i = 0;
    $parts = pathinfo($name);
    while (file_exists(UPLOAD_DIR . $name)) {
        $i++;
        $name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
    }
     $success = move_uploaded_file($myFile["tmp_name"],UPLOAD_DIR . '/'.$name);
    if (!$success) { 
        echo "<p>Unable to save file.</p>";
        exit;
    } else {
        $Dir = UPLOAD_DIR .'/'. $_FILES["ambum_art"]["name"];
    }
    chmod(UPLOAD_DIR .'/'. $name, 0644);
    unset($_SESSION['video']);
    $_SESSION['album_art'] = $Dir;
    $ambum_art_result = array();
    $ambum_art_result['content'] = $Dir;
    echo json_encode($ambum_art_result);

}

我希望每个文件都有从这个变量中生成的东西。

$rand_name = microtime().microtime().time().microtime();

谢谢。

我不想首先检查文件是否存在,因为这会添加到进程中,我只想使用 time() 和一些随机字符串。只是获得一个唯一的名称。

【问题讨论】:

  • 使用组合time().mt_rand()
  • 我在哪里把它放在代码上?
  • 赞这个$Dir = UPLOAD_DIR .'/'.time().mt_rand().$_FILES["ambum_art"]["name"];

标签: php file random upload timestamp


【解决方案1】:

请参阅this website 以获取文件上传的体面示例和说明。此外,this site 似乎是您从中找到此特定脚本的地方,或者如果没有提供很好的解释。

我已修改您的代码以包含一些 cmets,以便您和其他人可以更好地了解发生了什么。理论上,代码不应该像你说的那样覆盖现有文件,但我已经添加了你需要更改的内容以将文件名设置为随机字符串。

此外,您将原始文件名存储到会话中,而不是修改后的文件名。

define("UPLOAD_DIR", "/path/to/uploads/");

if (!empty($_FILES["ambum_art"])) 
{
    // The file uploaded
    $myFile = $_FILES["ambum_art"];

    // Check there was no errors
    if ($myFile["error"] !== UPLOAD_ERR_OK) {
        echo "<p>An error occurred.</p>";
        exit;
    }

    // Rename the file so it only contains A-Z, 0-9 . _ -
    $name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);

    // Split the name into useful parts
    $parts = pathinfo($name);

    // This part of the code should continue to loop until a filename has been found that does not already exist.
    $i = 0;
    while (file_exists(UPLOAD_DIR . $name)) {
        $i++;
        $name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
    }

    // If you want to set a random unique name for the file then uncomment the following line and remove the above
    // $name = uniqid() . $parts["extension"];

    // Now its time to save the uploaded file in your upload directory with the new name
    $success = move_uploaded_file($myFile["tmp_name"], UPLOAD_DIR . '/'.$name);

    // If saving failed then quit execution
    if (!$success) { 
        echo "<p>Unable to save file.</p>";
        exit;
    }

    // Set file path to the $Dir variable
    $Dir = UPLOAD_DIR .'/'. $name;

    // Set the permissions on the newly uploaded file
    chmod($Dir, 0644);

    // Your application specific session stuff
    unset($_SESSION['video']);
    $_SESSION['album_art'] = $Dir; // Save the file path to the session
    $ambum_art_result = array();
    $ambum_art_result['content'] = $Dir;
    echo json_encode($ambum_art_result);

}

阅读更多关于 PHP 的信息uniqid

我还强烈建议进行一些文件类型检查,因为目前看起来好像可以上传任何文件。上面的第二个链接有一个标题为“安全注意事项”的部分,我建议您仔细阅读。

【讨论】:

  • 是的,我将研究检查标题和限制文件大小。这是最大的事情,因为它在我尝试测试时替换文件。
  • 我编辑了您的答案,您在扩展之前省略了文件部分的句号。当你说 uncomment 和 removew abovem 时,上面是什么被删除了?我在循环中评论了这一行,现在我认为循环没有用,因为重命名在循环之外。
  • 是的,如果您取消注释唯一名称行,则 $i = 0;可以删除 while 循环的右大括号。由于您将文件名设置为唯一的名称,因此不再需要循环。
【解决方案2】:

此代码正在过滤名称,然后检查是否已发送具有完全相同名称的文件。如果是 - 名称用数字更改。

如果您想更改许多站点中的文件名 - 您可以修改此行 $name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);

例如成:$name = time().'_'.preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]); 如果用户发送文件 calle 'hello.jpg',此代码会将其更改为 _hello.jpg,如果已存在同名文件,则将使用名称 _hello-.jpg。

【讨论】:

    【解决方案3】:

    首先,您需要复制要上传的文件,然后您必须重命名该文件。例如。

    //复制

    if (!copy($file, $newfile)) {
        echo "failed to copy $file...\n";
    }
    ?>
    

    //重命名

    rename('picture', 'img506.jpg'); 
    

    Reference Link for copy

    Rename file

    已编辑:

    用这个替换你的代码,然后尝试

    <?php 
    if (!empty($_FILES["ambum_art"])) {
        $myFile = $_FILES["ambum_art"];
        if ($myFile["error"] !== UPLOAD_ERR_OK) {
           echo "<p>An error occurred.</p>";
            exit;
        }
        $name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
        $i = 0;
        $parts = pathinfo($name);
        while (file_exists(UPLOAD_DIR . $name)) {
            $i++;
            $name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
        }
    
         if (file_exists($myFile["name"])) {
             rename($myFile["name"], $myFile["name"].time()); //added content
         }
    
    
         $success = move_uploaded_file($myFile["tmp_name"],UPLOAD_DIR . '/'.$name);
        if (!$success) { 
            echo "<p>Unable to save file.</p>";
            exit;
        } else {
            $Dir = UPLOAD_DIR .'/'. $_FILES["ambum_art"]["name"];
        }
        chmod(UPLOAD_DIR .'/'. $name, 0644);
        unset($_SESSION['video']);
        $_SESSION['album_art'] = $Dir;
        $ambum_art_result = array();
        $ambum_art_result['content'] = $Dir;
        echo json_encode($ambum_art_result);
    
    }
    ?> 
    

    这将重命名您现有的文件,然后复制您的文件

    【讨论】:

    • 您能否在当前问题的示例代码中暗示这一点。
    • 所以您正在重命名临时文件,然后将尝试使用现在不存在的临时文件旧名称。这不是一个很好的例子。无需重命名或复制方法,只需在使用 move_uploaded_file 时设置名称 - 请参阅我的答案。
    • 你是先检查文件是否存在吗?那创建另一个进程,我们不能用 time() 和 mt_rand 创建一个新文件吗?
    • 你试过用 uniqid() 代替 time().mt_rand() 吗?
    猜你喜欢
    • 2014-12-19
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    • 2016-09-21
    • 2017-05-18
    • 1970-01-01
    • 2018-12-22
    相关资源
    最近更新 更多