note 40804 deleted from function.move-uploaded-file by nlopess

From: Date: Mon, 15 Mar 2004 14:07:02 +0000
Subject: note 40804 deleted from function.move-uploaded-file by nlopess
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-66864@lists.php.net to get a copy of this message
Note Submitter: flower@satline.net ---- Sometimes you want the files NOT TO BE overwritten, but kept unique. I use a function which does not overwrite files with same names, but manages uniquity, and saves the files with the name "file.gif" like : file.gif, file~1.gif, file~2.gif etc. The parameters contain the FULL PATHS. The result is only the name of the file (no metter if it is changes or not). function uploadFile($tmpName,$name) { if ($name) { $newName = $name; #move file to the directory if (file_exists($name)) { $ind = 1; preg_match("/(.*)\.([^\.]+)/",$name,$matches); while (file_exists($matches[1]."~".$ind.".".$matches[2])) { $ind++; }; $newName = $matches[1]."~".$ind.".".$matches[2]; }; move_uploaded_file($tmpName, $newName) || $newName = ""; #distribute the new file name $onlyName = split("/",$newName); return $onlyName[sizeof($onlyName)-1]; } } Then you call the function like : $newName = uploadFile($_FILES['myPhoto']['tmp_name'], '/home/~marin/'.$_FILES['myPhoto']['name']); Voila! $newName contains the name of the file, and you are sure it is unique and will not overwrite file with the same name.

« previous php.notes (#66864) next »