我正在开发一个使用图像的系统,并且图像由 md5-ed 电子邮件命名。如果已经存在具有 md5-ed 电子邮件名称的图像,我想在新上传的图像之后添加 -1 -2 等。这是我的代码:
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
但我不知道出了什么问题,它上传了带有原始名称的图像。即使使用 md5-ed 电子邮件作为名称。