0

I've been digging for an answer for days now in how to upload multiple photos into a database without overloading the system, and decided the best way is to upload multiple photos into a newly created directory (created via php) and store the directory link in the database instead. What I'm working on is a form that basically creates a new unique page. This unique page has a unique set of photos, and hence I need to generate a folder each time a page is generated, and upload the path link to the database! How do I do that???

Here is my HTML:

<form method="post" action="test.php" enctype="multipart/form-data">
  <p>File:</p>
  <input type="file" name="file[]" id="file" >
  <input type="submit" value="Upload">
</form>

and here is my PHP so far (should be on the right track I hope :/):

<?php
  //Connect to DB
  $conn = mysql_connect ('localhost', 'root', 'root');
  if (!$conn){
    die("Could Not Connect to MySQL!");
  }
  if(!mysql_select_db("test")){
    die("Could Not Open Database:" . mysql_error());
  }
  echo "<p>Connected</p>";

  //Upload Files
  foreach ($_FILES['file']['name'] as $f => $name) {
    $allowedExts = array("gif", "jpeg", "jpg", "png");
    $temp = explode(".", $name);
    $extension = end($temp);

    if ((($_FILES["file"]["type"][$f] == "image/gif")
    || ($_FILES["file"]["type"][$f] == "image/jpeg")
    || ($_FILES["file"]["type"][$f] == "image/jpg")
    || ($_FILES["file"]["type"][$f] == "image/png"))
    && ($_FILES["file"]["size"][$f] < 2000000)
    && in_array($extension, $allowedExts))
    {
      if ($_FILES["file"]["error"][$f] > 0){
        echo "Return Code: " . $_FILES["file"]["error"][$f] . "<br>";
      } else {
        if (file_exists("uploads/" . $name)){
          echo "<p>File Already Exists</p>";
        } else {
          //create new directory folder within /uploads

          //move the files you upload into the new folder.
          move_uploaded_file($_FILES["file"]["tmp_name"][$f], "upload/" . uniqid() . "_" . $name);
          //send the file path to the database.
          mysql_query("INSERT INTO test (idtest,testing) VALUES (','{$filepath}'");
        }
      }
    } else {
      $error =  "Invalid file";
    }
  }
?>

and for those curious, here is my database collumns:

|| idtest (AI, INT) || testing (varchart(50)) ||

Any help is IMMENSELY appreciated! It's been doing me in! Thank you in advance!

Hayo Friese
  • 83
  • 10
  • this is an obligatory comment reminding you to abandon the `mysql` functions in lieu of the `mysqli` or `PDO` libraries once you fix your current problem. – castis Aug 28 '14 at 18:19
  • yes!! I completely forgot! guess old habits die hard, huh.. :P by the way, mysqli_query = mysql_query, though, right? – Hayo Friese Aug 28 '14 at 18:40
  • the [mysqli library](http://php.net/manual/en/mysqli.quickstart.php) documentation has a wealth of knowledge on the subject. I do not know if simply changing the function names will produce the same output or not. – castis Aug 28 '14 at 20:52

2 Answers2

0

Given that you're generating your random-ish filename on-the-fly in your move_command, there is absolutely NO way to preserve that random/unique name for your database operation. You generate the random name, use it, and then throw it away.

You have to do

$filename = "upload/" . uniqid() . ....
move_uploaded_file(..., $filename);
mysql_query(".... $filename");

If you tried simply replicating the filename generating logic in your query, you'd end up with two totally different random names that have no relationship to each other.

Plus, your file_exist() test is utterly pointless. You're moving the uploaded files to a random name, but testing for the original client-side filename,

e.g.

file_exists('kittens.jpg');
move_uploaded_file(..., 'uploads/kittens-345234523452345.jpg');

In other words, you will NEVER get a "file exists" warning, because your collision checking is fundamentally broken.

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • not necessarily. If the directory link is available in the database and the folder is present within the server, I can always return, call the directory, and recreate it. The checking if the file exists needs to expand first to "if the directory exists then if the file exists" test. – Hayo Friese Aug 28 '14 at 18:42
0

You should add in at the top of your code a manner to which you make a directory, by using mkdir(). This will only be called once, and once it's done you set how you move the files into the directory as such:

<?php
//Create Subdirectory
  //Set the subdirectory name
  $subdir = $_POST['folderName'];

  //set the directory path name
  $dir = ("./uploads/" . $subdir);

  //make the directory
  (mkdir($dir, 0777);

//state your file type arguments
foreach ($_FILES['file']['name'] as $f => $name) {
 $allowedExts = array("gif", "jpeg", "jpg", "png");
 $temp = explode(".", $name);
 $extension = end($temp);
 //Set file type and size
  if ((($_FILES['file']['type'][$f] == "image/gif")
  || ($_FILES['file']['type'][$f] == "image/jpeg")
  || ($_FILES['file']['type'][$f] == "image/jpg")
  || ($_FILES['file']['type'][$f] == "image/png"))
  && ($_FILES['file']['size'][$f] < 1073741824)
  && in_array($extension, $allowedExts))
  {
   if ($_FILES['file']['error'][$f] > 0){
    echo "Return Code: " . $_FILES['file']['error'][$f] . "<br>";
   } else {
    //if the file exists within the directory
     if (file_exists($dir . $name)){
      echo "<p>File Already Exists</p>";
    } else {
      $names = $_FILES['file']['tmp_name'][$f];

      //move the files you upload into the newly generated folder.
      if (move_uploaded_file($names, "$dir/$name")){
        echo "<p>Moved</p>";
      } else {
        echo "<p>not moved</p>";
      }
      //send the file path to the database.

      echo "<meta http-equiv='refresh' content='2;url=test.php'>";
    }
   }
  } else {
   $error =  "Invalid file";
  }
 }
?> 

The part that's reusable is where you keep using the $dir variable. You should really check for security though, but this is the basic method you can do it in. The code with first make the directory, then loop the files through it.

Hayo Friese
  • 83
  • 10