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.