0

To build some simple analytics for our site - I am trying to capture the source from where the user lands on our page and if he ends up registering - store the source in the database.

Since this code has to be on all the pages - I thought of adding it to the layout.phtml This is what I have so far (just a rough draft)

$ref_cookie = $_COOKIE["xyzcom-referrer"];
if(!Zend_Auth::getInstance()->hasIdentity() && $ref_cookie==null) {
$ref=null;
$ref=$_GET['ref'];
if($ref==null || strlen($ref)==0)
    $ref= $_SERVER["HTTP_REFERER"];
//set in cookie incase user returns later and registers
setcookie("xyzcom-referrer",$ref);
}

Its pretty self explanatory - if the user is not logged in - I'm trying to get the referrer either thru the ref parameter or thru HTTP_REFERRER. The reason I'm storing it in a cookie is a user might visit the site today but sign up one week later.

So everytime a user registers, I will see if this cookie is set - if it is - I will get the value and insert it in the database as the referring source.

Is this the best way to approach this. Or should I write like a controller plugin - if so how do I go about it. Thanks for your tips.

Gublooo
  • 2,550
  • 8
  • 54
  • 91

1 Answers1

2

The layout is not really the place for this sort of logic, so yes I would suggest moving it to a controller plugin. This should be straightforward, create a plugin class, register it with the front controller, and in the class create a preDispatch method (as explained in the manual) and move your code to that.

There are also a few issues with your code:

  • You are assuming HTTP_REFERER will be set, but it may not be.

  • You are setting a session only cookie (that will be deleted when the user closes his/her browser) without a path (meaning if it is set in a sub-directory on your site it will not be available to your homepage). You'll want to supply the 3rd and 4th parameters to setcookie() to address these problems.

Tim Fountain
  • 33,093
  • 5
  • 41
  • 69
  • Thanks Tim - Regarding 1 - there is really nothing about it that we can do right - I mean I've noticed even gmail removes these headers when you click on any links inside the mail. And yes I will fix the setcookie function - I just wrote that as a quick draft. – Gublooo Jun 23 '12 at 20:00
  • Yup, just use `isset()` to check whether there is a referrer header before setting the cookie and all is good. – Tim Fountain Jun 23 '12 at 20:05
  • Thanks a bunch for the tips - appreciate it. – Gublooo Jun 24 '12 at 08:12