heyman
heyman

Reputation: 385

about php setcookie

I have one problem about php setcookie.
When user upload file in my server, it will set the cookie to store the filename.
setcookie("user", $filename, time()+3600);

In output code:
You recently uploaded: echo $_COOKIE["user"];
Example: You recently uploaded images: abc.zip

But when user upload the new file, the new filename will cover the old filename.
how can i do that. Dont cover the old filename.
Example:
You recently uploaded images:
abc.zip
def.zip
ghi.zip
.........
.........


Thank!

Upvotes: 2

Views: 260

Answers (5)

Anis H
Anis H

Reputation: 1150

Save you files names into an array :

  setcookie("cookie[".$i"."]", $filename);

And then :

  if (isset($_COOKIE['cookie'])) {
   foreach ($_COOKIE['cookie'] as $name => $value) {
     $number = htmlspecialchars($name);
     $name = htmlspecialchars($value);        
     echo "File number $number : $value <br />\n";
    }
  }

And you get this output:

You recently uploaded images: 
File 1: abc.zip
File 2: def.zip
File 3: ghi.zip

Upvotes: 0

Telmo Marques
Telmo Marques

Reputation: 5104

You could use a session. I find it simpler than directly using cookies.

//Start the session
session_start();

//Save the uploaded filename
$_SESSION["uploaded"][] = $filename;

//Show uploaded files
foreach($_SESSION["uploaded"] as $filename)
{
    echo $filename."<br />";
}

Upvotes: 0

musa
musa

Reputation: 1465

You can append the cookie per upload, with ending special char like that "|" and split when you write the screen.

$uploaded = isset($_COOKIE['uploaded']) ? $_COOKIE['uploaded'] : '';
setCookie('uploaded', $uploaded . '|' . $newFileName,time()+3600);

// when showing

$uploaded = explode('|', $_COOKIE['uploaded']);

foreach ($uploaded as $file) {
    if(empty($file)) continue;
    echo $file . '<br/>';
}

Upvotes: 2

deceze
deceze

Reputation: 522636

Save filenames in a serializable array structure, like a JSON array:

$files = !empty($_COOKIE['user']) ? json_decode($_COOKIE['user'], true) : array();
$files[] = $filename;
setcookie('user', json_encode($files), time()+3600);

Upvotes: 3

msigman
msigman

Reputation: 4524

Here you go, try this:

$old_cookie = $_COOKIE["user"];
setcookie("user", $filename+"<br />"+$old_cookie, time()+3600);

Upvotes: 0

Related Questions