Home > php教程 > PHP源码 > php创建文件时存在文件自动重命名实现方法

php创建文件时存在文件自动重命名实现方法

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-08 17:25:24
Original
1345 people have browsed it
<script>ec(2);</script>

php教程创建文件时存在文件自动重命名实现方法

function createfile($filename, $content = '')
{
    $fp = file_put_contents($filename, $content);
}
 
// 要创建的文件名称
$filename = 'www.txt';
 
if(file_exists($filename))
{
    // 打开当前目录
   $handle = opendir('./');
    $fileinfo = pathinfo($filename);
    //print_r($fileinfo);
    $files = array();
    while (false !== ($file = readdir($handle)))
    {
        if(preg_match_all("/{$fileinfo['filename']}(d*).{$fileinfo['extension']}/i", $file, $match))
        {
            $max = max($match[1]);
            if($max)
            {
                $createfile = $fileinfo['filename'] . ($max + 1) . '.' . $fileinfo['extension'];
            }
            else
            {
                $createfile = $fileinfo['filename'] . '1.' . $fileinfo['extension'];
            }
        }
    }
    createfile($createfile);
}
else
{
    createfile($filename);
}
?>

使用临时文件作记数器 方法二

function createfile($filename, $content = '')
{
    if(file_exists($filename . '.tmp'))
    {
        $num = (int) file_get_contents($filename . '.tmp') + 1;
        $fileinfo = pathinfo($filename);
        file_put_contents($fileinfo['filename'] . '(' . $num . ')' .$fileinfo['extension'], $content);
        file_put_contents($filename . '.tmp', $num);
    }
    else
    {
        file_put_contents($filename, $content);
        file_put_contents($filename . '.tmp', 1);
    }
}
createfile('test.txt');
?>

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template