开发者

change the image name in php

hi i want to upload image on server and i have done it but the problem is when i upload image with the same name it give me error what i want to do to append something to end of image name so that every image has its own unique name.

$TARGET_PATH =$TARGET_PATH . basename( $_FILES['photo']['name']);
if (file_exists($TARGET_PATH))
{
    // here will be the appended te开发者_如何学Crm
}


You shouldn't get error when a file already exist with the same name. I think your problem should be something else.

but if changing the name just solve your problem also you can use timestamp and adding it to your file name to be unique.

function uniqueName($filename){
    $f = explode('.', $filename);
    $ext = $f[count($f)-1];
    return implode('.', $f).time().'.'.$ext;
}

this function will work for all extensions.


You should do this:

$TARGET_PATH =$TARGET_PATH . basename( $_FILES['photo']['name']);
while (file_exists($TARGET_PATH))
{
    $TARGET_PATH =$TARGET_PATH . basename( $_FILES['photo']['name'],'.jpg') . uniqid() . '.jpg';
}

That way it will always produce a unique file name. note this will work for files with the extension jpg. should you want to use it for other files then i would recommend this:

  $TARGET_PATH =$TARGET_PATH . basename( $_FILES['photo']['name']);
$ext = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);

    while (file_exists($TARGET_PATH))
    {
        $TARGET_PATH =$TARGET_PATH . basename( $_FILES['photo']['name'],'.' .$ext) . uniqid() . '.'.$ext;
    }

supplying an extension to basename will remove the extension from the name. Adding uniqid() will add some unique entropy to the end of the filename. If that's to long for you, you could replace it with rand(0,10);

This method also has the advantage of only executing when it finds that the file does exist, otherwise it won't run at all.


Think about a function which returns a unique name - like (untested and is very improvable):

<?php
// ...
function getUniqueFilename($targetPath = '.', $extension = 'jpg') {
  $uniqueFilename = sha1(time() . mt_rand(1, 150)) . '.'. $extension;

  if(file_exists($targetPath . $uniqueFilename)) {
    getUniqueFilename($targetPath, $extension);
  } else {
    return $uniqueFilename;
  }
}

// and you call it like
$newFilename = getUniqueFilename('.', 'gif');
?>

just as an idea ;-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜