I want to provide a javascript snippet code (kinda like google analytics) to my clients which will use the code on their website and track visit duration on their website. I want to use cookies for this.
My only question is what’s the best way to implement? A few options I have in mind:
- Should I set cookies from PHP (which is going to be sitting on my
domain) and will that be considered as 3rd party cookie? - Or do I have to set a cookie from Javascript since it will be client
side loaded from my site? - Or would be the best way to set cookies with javascript and access
them with PHP?
If you set the cookies in JavaScript the domain of the cookie is going to be the website’s domain and not your domain. So that information is not available when doing something like.
With other words, that won’t work.
Instead you would need to send the clients information to your webservice using AJAX or (how google does it) by loading a blank images.
There are a lot of parameters that are available in JavaScript, but not send to the server (not in
$_SERVER). Google adds that information as GET parameters.However, if you don’t really need that data, the easiest ways is to include your script as image on the client’s website.
$_SERVER['HTTP_REFERRER']will be the URL of the page where the script is included.Be sure to set the
Content-Typeto'image/gif'and output a blank 1px gif.When using AJAX, please be aware that you’ll need to use CORS, which means setting the
Access-Control-Allow-Originresponse header.Note that using AJAX without jQuery can be a pain. Since you don’t care about the response, creating a tracking image (using javascript) is probably your best option. Read this article on the basics how to implement that.