php - Append a number to a filename if an image with that name already exists -


i wrote php checks if file exists when user uploads new file, , if appends string filename. want number added end of filename , when file same name uploaded tops number 1.

so example: have image uploaded filename image.png , upload 1 same filename. file should renamed image0.png. when try upload image filename image.png should renamed image1.png , on.

i'm not sure how accomplish within code. can me out? code snippet checks duplicates , appends filename.

if(file_exists("/customers/d/8/e/frankkluytmans.nl/httpd.www/testsite/cms/upload/".$_files["image"]["name"])) {     $filename = explode(".",$_files['image']['name']);     $imagename = $filename[0]."hoi.".$filename[1]; } else {     $imagename = $_files['image']['name']; }  $image = mysql_real_escape_string(htmlspecialchars("/upload/".$imagename));  if (move_uploaded_file($_files["image"]["tmp_name"],     "./upload/".$imagename)) {�  mysql_query("insert frankkluytmans set pagid='$pagid', title='$titlename', content='$contentname', image='$image', youtube='$youtube'") or die(mysql_error());   header("location: index.php");   } 

you use recursive function keep checking number:

function checkfile($path, $file, $ext, $number) {     if(file_exists($path.$file.$number.$ext))     {         if($number == "")             $number = 0;          $number ++;         return checkfile($path, $file, $ext, $number);     }      return $path.$file.$number.$ext; }  //run mime type things extension. lets pretend .jpg // , assume stripped extension uploaded file... // also, pass blank last param start file check without number.  $extension = ".jpg"; $filename_minus_extension = "some-image";  $filename = checkfile('path-to-directory/', $filename_minus_extension, $extension, ""); 

this in no way tested, general idea use recursive function. if have specific question, feel free ask , may update.


Comments

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -