Guardian-Mage Posted May 12, 2007 Share Posted May 12, 2007 I have this basic file upload script: <?php if (($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/pjpeg") && ($_FILES["file"]["size"] < 20000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); echo "Stored in: " . "upload/" . $_FILES["file"]["name"] . "<br /> <img scr=\"upload/" . $_FILES["file"]["name"] . "\" alt=\"Hello World\" />" ; } } } else { echo "Invalid file"; } ?> I need to have my script rename the file if it already exists, like add a number to it until it is ok. How do i do this? Quote Link to comment Share on other sites More sharing options...
s0c0 Posted May 12, 2007 Share Posted May 12, 2007 You can try creating a function that gets called if the file exists. The function would then use the rand function to append a random number on the end of the file name. The function would look something like this: function randomName() { $randNum = rand(1,100000); // returns random number between 1 and 100,000 $_FILES["file"]["name"] = $_FILES["file"]["name"].$randNum; return $_FILES["file"]["name"]; Go(); } Ofcourse you would have to put your existing code into a function, so in the end it would look something like this: function Go ($uploadFile) { // your existing code in here // if file exists then call randomFile() } Not sure if that will work and none of that code has been tested, but give it a shot. Quote Link to comment Share on other sites More sharing options...
Guardian-Mage Posted May 12, 2007 Author Share Posted May 12, 2007 Thank you very much, the code works fine. -Brandon Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.