在上载后重命名文件之前检查文件是否存在

时间:2012-11-19 11:52:12

标签: php upload rename

我需要帮助添加功能,以便在上传时检查文件是否存在。

upload.php代码的上传方式如下:

$file_name = $HTTP_POST_FILES['ljudfil']['name'];
$random_digit=rand(0000,9999);
$mp3 ='.mp3';
$pdf ='.pdf';
$datum = date('Ymd'); 
$new_file_name=$random_digit.$file_name;
$target_path1 = $target_path . $orgnr . '_' . $gsm . $pdf; 

$target_path3 = $target_path . 'AC' . $datum . $new_file_name . $mp3; 
$target_path11 = $target_path4 . $orgnr . '_' . $gsm . $pdf; 

$target_path33 = $target_path4 . 'AC' . $datum . $new_file_name . $mp3;
$targetljudfilftp = 'AC' . $datum . $new_file_name . $mp3;

move_uploaded_file($_FILES['avtalsfil1']['tmp_name'], $target_path1);
move_uploaded_file($_FILES["ljudfil"]["tmp_name"], $target_path3);
$sql = "INSERT INTO affarer (tid, cid, orgnr, ljudfilftp) VALUES 
        (CURDATE(),'$date','$cid','$orgnr', '$targetljudfilftp')";

如您所见,它会重命名上传的文件,包括随机数。

有时,它会将文件重命名为已存在的数字。

当发生这种情况时,它会覆盖我服务器上的上一个文件。

那么,如何在用于重命名之前添加一个函数来检查目标名称是否存在?

6 个答案:

答案 0 :(得分:0)

使用file_exists内置功能。<​​/ p>

答案 1 :(得分:0)

您可以使用(例如)基于时间的方法

来更改随机挖掘者的创建方式

$random_digit = microtime(TRUE);

答案 2 :(得分:0)

您可以使用以下

$ random_digit = time();

答案 3 :(得分:0)

相反,使用'rand'函数可以生成重复的数字,你可以使用'uniqid'php函数,它返回一个唯一的id(http://www.php.net/manual/en/function.uniqid.php)。

如果您仍想使用'rand',您可以使用'file_exists'函数将生成的文件名作为参数(http://www.php.net/manual/en/function.file-exists.php),但如果文件存在则必须重新生成文件名,因此您将每次文件存在时迭代。

最后,考虑使用全日期('Ymdhis')格式代替日期('Ymd'),最好通过调用time()函数(http://www.php.net/manual/en/function.time.php)来使用时间戳

鸭,

答案 4 :(得分:0)

if (file_exists($random_digit)) {
   $random_digit = rand(0000,9999);
}

答案 5 :(得分:0)

您可以使用

if (file_exists($target_path1))

验证文件是否存在。

但是,你会做得更好,改变策略并使用tempnam

$target_path  = tempnam ($target_path, 'AC' . $datum . $file_name . $mp3)

这将创建一个文件,例如“AC_2012_Anacreon.mp3_xTfKxy”,但您可以保证它是唯一的,而即使使用file_exists也会让您面临并发冲突的风险

当然,该文件不再具有.mp3扩展名,因此您必须在扫描目录并提供文件以供下载时将其考虑在内。

仍然不安全,但可能更容易:

for(;;)
{
    $newname = // some strategy to generate newname, including a random
    if (!file_exists($newname))
        touch($newname);
    if (!filesize($newname))
        break;
}

或者您可以使用lock文件来保证不并发(因此,file_exists将返回真相并且保持真相):

$fp = fopen('.flock', 'r+');
if (flock($fp, LOCK_EX))
{
    for(;;)
    {
        $newname = // some strategy to generate newname, including a random
        if (!file_exists($newname))
        {
            // this creates the file uniquely for us.
            // all other writers will find the file already there
            touch($newname);
        }
    }    
    flock($fp, LOCK_UN);
}
else
    die("Locking error");
fclose($fp);
// $newname is now useable.