如果文件已存在于服务器上,我想在文件名中添加后缀。
例如:如果文件image.jpg存在于服务器上,则要将新文件重命名为image_1.jpg,image_2.jpg等。
非常感谢任何帮助!
$max_file_size = 1024*100000; // 100000kb
$valid_exts = array('jpeg', 'jpg', 'png', 'gif');
// thumbnail sizes
$sizes = array(250 => 150);
if (isset($_FILES["$fileime"])) {
if( $_FILES["$fileime"]['size'] < $max_file_size ){
// get file extension
$ext = strtolower(pathinfo($_FILES["$fileime"]['name'], PATHINFO_EXTENSION));
if (in_array($ext, $valid_exts)) {
/* resize image */
foreach ($sizes as $width => $height) {
/* Get original image x y*/
list($w, $h) = getimagesize($_FILES["$fileime"]["tmp_name"]);
/* calculate new image size with ratio */
$ratio = max($width/$w, $height/$h);
$h = ceil($height / $ratio);
$x = ($w - $width / $ratio) / 2;
$w = ceil($width / $ratio);
/* new file name */
$path = '../thumbs/'.$_FILES["$fileime"]['name'];
/* read binary data from image file */
$imgString = file_get_contents($_FILES["$fileime"]['tmp_name']);
/* create image from string */
$image = imagecreatefromstring($imgString);
$tmp = imagecreatetruecolor($width, $height);
imagecopyresampled($tmp, $image,
0, 0,
$x, 0,
$width, $height,
$w, $h);
答案 0 :(得分:0)
为什么不在文件名末尾添加时间戳?
$max_file_size = 1024*100000; // 100000kb
$valid_exts = array('jpeg', 'jpg', 'png', 'gif');
// thumbnail sizes
$sizes = array(250 => 150);
if (isset($_FILES["$fileime"])) {
if( $_FILES["$fileime"]['size'] < $max_file_size ){
// get file extension
$ext = strtolower(pathinfo($_FILES["$fileime"]['name'], PATHINFO_EXTENSION));
if (in_array($ext, $valid_exts)) {
/* resize image */
foreach ($sizes as $width => $height) {
/* Get original image x y*/
list($w, $h) = getimagesize($_FILES["$fileime"]["tmp_name"]);
/* calculate new image size with ratio */
$ratio = max($width/$w, $height/$h);
$h = ceil($height / $ratio);
$x = ($w - $width / $ratio) / 2;
$w = ceil($width / $ratio);
/* new file name */
$filename_array = explode('.', $_FILES["$fileime"]['name']);
$extension = array_pop($filename_array);
$new_name = implode('.',$filename_array).'_'.time().'.'.$extension;
$path = '../thumbs/'.$new_name;
/* read binary data from image file */
$imgString = file_get_contents($_FILES["$fileime"]['tmp_name']);
/* create image from string */
$image = imagecreatefromstring($imgString);
$tmp = imagecreatetruecolor($width, $height);
imagecopyresampled($tmp, $image,
0, 0,
$x, 0,
$width, $height,
$w, $h);