tags:

views:

45

answers:

3

I have tested this on my development computer, but now I have uploaded everything to the production server and I cant read out the value of the cookie.

I think the problem lies in the Serialization and Unserialization.

if (isset($_COOKIE['watched_ads'])){
    $expir = time()+1728000; //20 days
    $ad_arr = unserialize($_COOKIE['watched_ads']); // HERE IS THE PROBLEM
    $arr_elem = count($ad_arr);
    if (in_array($ad_id, $ad_arr) == FALSE){
        if ($arr_elem>10){
        array_shift($ad_arr);
        }
        $ad_arr[]=$ad_id;
        setcookie('watched_ads', serialize($ad_arr), $expir, '/');
    }
}

When I echo this: count($ad_arr) I receive the expected nr, 1 in this case, so there is a value there. But when I echo the value: echo $ad_arr[0]; I get nothing. Completely blank. No text at all.

Anybody have a clue?

if you need more info about something let me know...

A: 

You should understand that count returns 1 for most non-array values, including an empty string.

> php
<?php
echo count("");
^Z
1

So, to debug it, try var_dump'ing the $_COOKIE superglobal itself.

Artefacto
what is var_dumping? In firefox I can see the cookie and its value is there...
Camran
No, use the var_dump() command in php to output the contents of $_COOKIE. http://us2.php.net/var_dump
Eli
I added the link to the answer...
Artefacto
A: 

Turns out it was stripslashes which was needed here.

Did a stripslashes() first and it worked unserializing the cookie.

Camran
A: 

I would guess, that your $ad_arr is no array. You can check this with the "is_array()" function or by calling:

var_dump($ad_arr);

It sould have "array" in the output and not "string" (as Artefacto just already mentioned).

Another little tip:

If you want to store a associative array, you can use an encoded JSON String which use can save using the json_encode() gunction:

setcookie('watched_ads', json_encode($ad_arr), $expir, '/');

And loading the data you can use the opposite function json_decode():

$ad_arr = json_decode($_COOKIE['watched_ads'], true);

Adding true as a second paramter, you will get a associative array and not an object. Using the JSON format is also a good idea saving complex data within a database.

A and a last tip: "!in_array()" works just as fine as "in_array() == FALSE"

Kau-Boy