简体   繁体   English

如果图像已经存在,请使用PHP重命名图像

[英]Rename Image with PHP if image already exists

I'm working on a system that uses images, and the images are named by a md5-ed email. 我正在使用图像的系统上工作,并且这些图像由md5版本的电子邮件命名。 And I'd like to add a -1 -2 etc after the newly uploaded image if an image with the md5-ed email name already exists. 我想在新上传的图像之后添加-1 -2等,如果已经存在带有md5-ed电子邮件名称的图像。 Here's my code: 这是我的代码:

    public function upload() {  

    global $email;

    $fileName = $_FILES['userfile']['name'];
    $tmpName  = $_FILES['userfile']['tmp_name'];
    $fileSize = $_FILES['userfile']['size'];
    $fileType = $_FILES['userfile']['type'];
    $user     = $_SESSION['user'];

    $fp      = fopen($tmpName, 'r');
    $content = fread($fp, filesize($tmpName));
    $content = addslashes($content);
    fclose($fp);

    if(!get_magic_quotes_gpc()) {
        $fileName = addslashes($fileName);
    }

    $new_file_name = md5($email);


    $fileExists = file_exists("../lib/uploads/" . $new_file_name);

    $query = mysql_query("SELECT * FROM avatars WHERE ( name='$fileName' ) OR ( name='$new_file_name' ) ");

    $num_rows = mysql_num_rows($query);


    if ( $fileExists ) {

        $fileName = $new_file_name; 
        $first = 1;
        $separator = '-';

        while ( file_exists("../lib/uploads/" . $fileName) ) {

            preg_match('/(.+)'.$separator.'([0-9]+)$/', $fileName, $match);     

            $new_file_name = isset($match[2]) ? $match[1].$separator.($match[2] + 1) :$fileName.$separator.$first;

            $first++;   

        }

        $fileName = $new_file_name;

    } elseif ( empty( $fileName ) ) {

        echo '<div class="error">Please Select a file first.</div>';

    } else {

        move_uploaded_file($_FILES["userfile"]["tmp_name"],
          "lib/avatars/" . $fileName);

        echo "<div class='success'>File $fileName Uploaded.</div>";  

    }

} // ends upload() function

But I don't know what's wrong, it uploads the image with it's original name. 但是我不知道出了什么问题,它以原始名称上传了图片。 Not even with the md5-ed email as name. 甚至没有使用md5-ed电子邮件作为名称。

In short 简而言之

You've messed up your if statements . 您搞砸了if语句

In detail 详细

This is very veryu very simple. 这非常非常简单。 In your last else (the one that executes when the file doesnt exist) you have 在您的最后一个文件中(当文件不存在时执行的文件)

move_uploaded_file($_FILES["userfile"]["tmp_name"],
      "lib/avatars/" . $fileName);

But if you trace back, you will see that $fileName is set to 但是,如果回溯,您将看到$fileName设置为

$fileName = $_FILES['userfile']['name'];

and not the md5 of the email. 而不是电子邮件的md5。 You have to remove the final else condition and have its code execute EVERY time. 您必须删除最终的else条件,并让其代码每次执行一次。 Of course as long as the $fileName is not empty. 当然只要$fileName不为空。

So your code should be: 因此,您的代码应为:

if ( $fileExists ) {

    $fileName = $new_file_name; 
    $first = 1;
    $separator = '-';

    while ( file_exists("../lib/uploads/" . $new_file_name ) ) {

        preg_match('/(.+)'.$separator.'([0-9]+)$/', $new_file_name, $match);    

        $new_file_name = isset($match[2]) ? $match[1].$separator.($match[2] + 1) :$new_file_name.$separator.$first;      
        $first++;   

    }
} 

// <----
// Moved this one outside, since it always executes
// ---->
$fileName = $new_file_name;

// <----
// Separated this if, since it has nothing to do with the above
// ---->
if ( empty( $fileName ) ) {

    echo '<div class="error">Please Select a file first.</div>';

} else {

    move_uploaded_file($_FILES["userfile"]["tmp_name"],
      "lib/avatars/" . $fileName);

    echo "<div class='success'>File $fileName Uploaded.</div>";  

}

} // ends upload() function

How you can optimize it 如何优化它

This depends if you are expecting single users to have lot's of images. 这取决于您是否期望单个用户拥有很多图像。 If this is NOT the case, then leave it as is. 如果不是这种情况,则保持原样。

Otherwise, you will quickly end up having to wait for a long time after uploading 10th, 20th photo. 否则,上传第10张,第20张照片后,您将很快不得不等待很长时间。

One way to improve it would be to search for files in a directory that fit a pattern (in this case your md5). 一种改进方法是在适合模式的目录中搜索文件(在本例中为md5)。 For example like this: 例如这样:

foreach (glob($md5 . "*") as $filename) {
    echo "$filename size " . filesize($filename) . "\n";
}

This way you instantly know if there are already files with this md5 and how many of them. 这样,您可以立即知道此md5是否已经存在文件,以及其中有多少文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM