DevWL
DevWL

Reputation: 18840

File upload with SESSION array instead of $_FILES?

The question is: Is there is any way to make it work with SESSION array ?

Because i have assigned $_FILES["file"] to a SESSION array, it would not upload a file. When i use var_dump($_SESSION['test'][1]["tmp_name"]) and var_dump($_FILES["file"]["tmp_name"]) it would show the same value. any idea guys ?

//THIS WONT WORK
    $_SESSION['file'][] = $_FILES["file"];
    $_SESSION['file'][] = $_FILES["file2"];
    foreach($_SESSION['file'] as $index => $name){
       move_uploaded_file($_SESSION['file'][$index]["tmp_name"], "images/" . $rename);
    }
//THIS WORKS OK
    move_uploaded_file($_FILES["file"]["tmp_name"],
    "images/" . $rename);

Ok now few words why i need to use session ... I need to use session because i have multiple files that i want to upload through foreach statement.

// print_r($_SESSION["file"]) would output:

array(1) {
  [0]=>
  array(5) {
    ["name"]=>
    string(8) "face.jpg"
    ["type"]=>
    string(10) "image/jpeg"
    ["tmp_name"]=>
    string(31) "C:\EasyPHP-12.1\tmp\php882C.tmp"
    ["error"]=>
    int(0)
    ["size"]=>
    int(22398)
  }
}

Upvotes: 0

Views: 1588

Answers (2)

Kaivosukeltaja
Kaivosukeltaja

Reputation: 15735

Quote from the manual:

The file will be deleted from the temporary directory at the end of the request if it has not been moved away or renamed.

You must move_uploaded_file() for each new file you add by the end of your AJAX script. If you don't want orphaned files to stick around, you could move them into a temporary directory before your form is submitted and clean up the directory at regular intervals.

Upvotes: 2

Lajos Arpad
Lajos Arpad

Reputation: 76464

  1. You must save your file using move_uploaded file

  2. Check whether $_SESSION["test"] exists. If not, create it, $_SESSION["test"] = array();

  3. $_SESSION["test"][] = "images/" . $rename;

  4. You can reach the last uploaded file with $_SESSION["test"][count($_SESSION["test"] - 1]. If you uploaded a single file, then it is incorrect to reference to it with $_SESSION["test"][1].

Upvotes: 0

Related Questions