Hello, I have this code to upload files and if the file is already exist then renamed it by addting a counter next to it i.e file.doc is exist. If I upload the same file again, it shouldn’t replace the old one but add a counter file-1.doc. Looking for help
So, what is not working with the code you already have to add the counter and keep checking for the file existence until you find a new name? Do you need to initialise $file_name before the loop the same way you create it within the loop to make it work as you need?
Actually, it just replaces the original file. I made few tweaking to the code but still it’s just replacing and not adding. I just want to make a directory, if not exist and save file in that directory. It’s working fine. Now, when i add the same file, it replaces the previous one instead making a copy of it with a counter.
you just keep checking for the existence of the original filename and extension. You add the counter to $file_name, but you don’t check using that variable. Maybe
Need some more information then. What’s in $file_name after the while() loop finishes? Does the while() loop ever run? What’s in $file_destination before you move the uploaded file?
I believe it’s not running.Otherwise, it would have replaced the file. $file_destination is mentioned in above code. I did use this code before and it was working fine. I took it from here
Then later on, I decided to add the directory as well. My bad, I haven’t saved the code and replaced it with all three files and now its giving me bit tough time.
What I mean is, add some echo() statements and post the actual values out of your code, as it runs. Then we can narrow it down to which part isn’t doing what it should.
I didn’t get that actually. One thing i noticed is changing the file name to lowercase after submission and the usage of preg_replace.As we are using while loop before, and the file name would never match and that is why it is creating problem. You say on this?
Seems reasonable, but only if it actually changes anything. As I read it, that regular expression swaps spaces in the filename for underscores, so test it with a file that doesn’t include spaces - if it works, then that’s your problem. Changing case would only matter if you’re on a case-sensitive file system.