note 40804 added to function.move-uploaded-file

From: Date: Mon, 15 Mar 2004 13:55:47 +0000
Subject: note 40804 added to function.move-uploaded-file
Groups: php.notes 
Request: Send a blank email to php-notes+get-66862@lists.php.net to get a copy of this message
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. ---- Manual Page -- http://www.php.net/manual/en/function.move-uploaded-file.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+40804 Delete -- http://master.php.net/manage/user-notes.php?action=delete+40804&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+40804&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#66862) next »