How do I change the file name if it already exists?
I'm uploading images through PHP. I'm using the following segment of code:
What I'd like to do is instead of reporting an error saying the file name already exists, choose a different name for the file that's available. How do I assign a unique name to the file (for example, filename2.jpg, filename3.jpg)? I can do it using what I know about do while loops, but I'm not sure if there's a particularly simple or built-in way.
if (file_exists("photos/" . $_FILES["file"]["name"]))
echo $_FILES["file"]["name"] . " already exists. ";
The answer may depend on whether or not you need the actual file name to me semantically meaningful. If not, you could just use uniqid() to create a unique file name, e.g.:
$fileName = uniqid(true).'.jpg';
Sure, semantics aren't a problem. I'll give this a try. Thanks!
I thought there'd be a built-in way to do this with PHP.
I believe that the $_FILES['field_name']['tmp_name'] value is similarly constructed via a uniqid-like method, so you could probably just use that (filtered through basename() to strip off the directory portion of the path).
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)
Tags for this Thread