0

PHP newbie here..

I am trying to create an if statement that will change the name of $_FILES["file"]["name"] to something unique if file_exists() comes back true.

My code is given below.. I tried to use tempnam() but I'm not 100% sure as to how to implement it using PHP.

if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      $_FILES["file"]["name"] = "image/tempnam('',newsFeed)";//this is my problem
      $dialog = $_FILES["file"]["name"] . " already exists. ";
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      }

Is there a better way to do this because right now I'm just getting a php error:

Warning: move_uploaded_file(upload/image/tempnam('',newsFeed)) [function.move-uploaded-file]: failed to open stream: No such file or directory

The directory does exist because the upload form works with files that don't have the same name.

Any sort of help or guidance would be appreciated!

Vagabond
  • 877
  • 1
  • 10
  • 23
xno
  • 1,225
  • 1
  • 13
  • 20
  • *Always* give files a unique randomly generated name, not only if it already exists. See http://stackoverflow.com/a/11061577/476 – deceze Apr 13 '14 at 17:37

2 Answers2

1

Replace

  $_FILES["file"]["name"] = "image/tempnam('',newsFeed)";

With

  $_FILES["file"]["name"] = "image/".tempnam('',"newsFeed");

http://www.php.net/manual/en/function.tempnam.php

PlaviZG
  • 79
  • 1
  • 7
  • I replaced it with this instead and it worked. Thanks for the help! $_FILES["file"]["name"] = "".tempnam('upload/',newsFeed); – xno Apr 13 '14 at 18:01
0

Change this

if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      $_FILES["file"]["name"] = "image/tempnam('',newsFeed)";//this is my problem
      $dialog = $_FILES["file"]["name"] . " already exists. ";
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      }

to

if (file_exists("upload/" . $_FILES["file"]["name"])) {
      $dialog = $_FILES["file"]["name"] . " already exists. ";
      move_uploaded_file($_FILES["file"]["tmp_name"], 
                         "upload/image/".tempnam('',newsFeed);
}
Vagabond
  • 877
  • 1
  • 10
  • 23