Вопрос

We are trying to create a unique ID for each user that visits our site. I'm relatively new to Zend and to MVC patterns, so i'm unsure as to where the cookies should be set and how.

The php is very straight forward:

if(!isset($_COOKIE['mx_uid'])){
   $expire = time()+60*60*24*30;
   setcookie('mx_uid', uniqid('mx_'), $expire);
}

$lxid = $_COOKIE['mx_uid'];

I tried to place this into the View and ran into the issue that the cookie is regenerated on every new page that is loaded, so if they go to 20 pages on the site then they have 20 cookies.

Additionally, I need to use the "$lxid" variable inline on each page without refreshing, because a javascript snippet will be capturing the cookie contents.

Has anyone used cookies in this way on Zend?

Это было полезно?

Решение

If you need to set cookies once during one session place them in frontController plugin. Add to your app.ini
resources.frontController.plugins.a.class = "YourNamespace_Plugin_Cookies"

And then your plugin will look like

class YourNamespace_Plugin_Cookies extends Zend_Controller_Plugin_Abstract  
{  
  public function preDispatch(Zend_Controller_Request_Abstract $request)  
  { 
      $cookie = $request->getCookie('mx_uid');  
      if(empty($cookie)){  
           setcokkie('mx_uid',$lxid,$expire, '/');  
      }  
  }  
}  

Другие советы

You'll want to set the cookie path as well (4th param):

setcookie('mx_uid', uniqid('mx_'), $expire, '/');

Be aware that you may not be able to access the cookie within the same script in which you are setting it (i.e. it won't work until the next page they visit). So better logic might be:

if (isset($_COOKIE['mx_uid'])){
    $lxid = $_COOKIE['mx_uid'];
} else {
    $lxid = uniqid('mx_');
    $expire = time()+60*60*24*30;
    setcookie('mx_uid', $lxid, $expire, '/');
}

to ensure that $lxid will always contain a value.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top