php创建文件时存在文件自动重命名实现方法
php创建文件时存在文件自动重命名实现方法,实例代码如下:
- <?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);
- }
- ?>
使用临时文件作记数器,方法二,实例代码如下:
- <?php
- 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');
- ?>