如何防止Laravel中的文件名重复? - php

这是我在一个控制器中的存储方法中的代码。

    // Get the file object from the user input.
    $file = Request::file('filefield');

    // Get the filename by referring to the input object
    $fileName = $file->getClientOriginalName();

    if (!Storage::exists($fileName))
    {
        Storage::disk('local')->put($fileName, File::get($file));
    } else {
        return 'Hey this file exist already';
    }

它工作正常,但是我遇到的问题是,它允许重复的文件名,并且文件显然不会上传。我尝试用它修复它,到目前为止还不错。

现在,我正在猜测是否要让用户上传与已经具有相同名称的文件名,所以我需要在文件名后附加一个数字。

我的问题是在laravel中解决此问题的最佳方法是什么?

非常感谢您的帮助。

参考方案

您可以做几件事。

如果原始文件名已经存在,则以下代码将在扩展名前查找整数。如果没有,则添加一个。然后,它会递增此数字并检查,直到不存在这样的文件名。

if (Storage::exists($fileName)) {
    // Split filename into parts
    $pathInfo = pathinfo($fileName);
    $extension = isset($pathInfo['extension']) ? ('.' . $pathInfo['extension']) : '';

    // Look for a number before the extension; add one if there isn't already
    if (preg_match('/(.*?)(\d+)$/', $pathInfo['filename'], $match)) {
        // Have a number; get it
        $base = $match[1];
        $number = intVal($match[2]);
    } else {
        // No number; pretend we found a zero
        $base = $pathInfo['filename'];
        $number = 0;
    }

    // Choose a name with an incremented number until a file with that name 
    // doesn't exist
    do {
        $fileName = $pathInfo['dirname'] . DIRECTORY_SEPARATOR . $base . ++$number . $extension;
    } while (Storage::exists($fileName));
}

// Store the file
Storage::disk('local')->put($fileName, File::get($file));

或者,您可以生成一个唯一的字符串(例如,使用uniqid),并将其附加到原始文件名(或单独使用)。如果这样做,您很有可能发生冲突,因此接近零,很多人会说甚至不值得检查具有该名称的文件是否已经存在。

无论哪种方式(在第一个示例中都是如此),另一个进程可能会在此过程之间进行验证,以确保文件不存在,然后再写入文件。如果发生这种情况,您可能会丢失数据。有一些方法可以减轻这种可能性,例如改为使用tempnam

File_exists但不包含 - php

我正在尝试包含一个文件,但它似乎无法正常工作-这是整个代码:if (file_exists('config/categories.php')) { include ('config/categories.php'); } foreach ($categories as $cat_sef => $cat_name)…

PHP strtotime困境 - php

有人可以解释为什么这在我的服务器上输出为true吗?date_default_timezone_set('Europe/Bucharest'); var_dump( strtotime('29.03.2015 03:00', time()) === strtotime('29.03.2015 04:00�…

PHP-全局变量的性能和内存问题 - php

假设情况:我在php中运行一个复杂的站点,并且我使用了很多全局变量。我可以将变量存储在现有的全局范围内,例如$_REQUEST['userInfo'],$_REQUEST['foo']和$_REQUEST['bar']等,然后将许多不同的内容放入请求范围内(这将是适当的用法,因为这些数据指的是要求自…

如何在PHP中设置get_file_contents的时间限制? - php

有时get_file_contents花费的时间太长,这会挂起整个脚本。有什么方法可以设置get_file_contents的超时限制,而无需修改脚本的最大执行时间?编辑:由于该文件不存在,因此花费了很长时间。我收到“无法打开流:HTTP请求失败!”错误。但这需要永远。 参考方案 通过使用timeout option创建上下文,似乎在PHP> 5.2.…

php-casperjs获取内部文本 - php

我正在为casperjs使用php包装器-https://github.com/alwex/php-casperjs我正在网上自动化一些重复的工作,我需要访问一个项目的innerText,但是我尚不清楚如何从casperjs浏览器访问dom。我认为在js中我会var arr = document.querySelector('label.input…