-2

I have a PHP code. Now, I'm building a WordPress site, instead of a HTML/PHP website. And, I've posted a question on the WordPress forum, someone said:

You cannot set cookies with PHP in HTML head sections. Cookies must be set before any output is sent out to the browser. Adding your code to a callback hooked to “init” should be OK. Alternately, set the cookie with JavaScript.

But, I don't have a very good programming experience with JavaScript. This is my code:

<?php
//DETECT REFERRER
if(empty($_SESSION["referrer"]))
{
    $referrer = $_SERVER["HTTP_REFERER"];
    if(empty($referrer))
        $referrer = $_SERVER["SCRIPT_URI"].((!empty($_SERVER["QUERY_STRING"]))? '?'.$_SERVER["QUERY_STRING"]:'');
    $_SESSION["referrer"] = $referrer;
}
//DETECT AFFILIATE ID 
if(empty($_SESSION["aid"])) 
{ 
    $aid = $_GET["aid"]; 
    if(empty($aid)) 
        $aid = $_COOKIE["aid"]; 
    if(empty($aid)) 
        $aid = 1; 
    setcookie("aid", $aid, strtotime("+10 years"), "/"); 
    $_SESSION["aid"] = $aid; 
} 
\?>

Does someone have any JavaScript experience and can help me with converting this code from PHP to JavaScript? Thanks in advance.
If you have any question, please post a comment.

If someone knows how to insert that code before the html head on every page, that's even better. But, I don't know if it is actually possible.

Regards, Luuk Faasse

Luuk F.
  • 11
  • 4
  • the code with cookies get parameter and header parameter make only sense for the case of a http call to a server. so, it make sense for server side processing (like php) but not for frontend code (like javascript (except nodejs or somethibg but i guess you mean "nornal" js inside the browser; right? – snap Mar 11 '18 at 17:35
  • Why don't you just call your php code before the html head? – Tyler Mar 11 '18 at 17:40
  • @Tyler I'm using wordpress, but I don't now how to insert that code before the HTML head, on every page. I can't find any plugins for that, and, if there's a file, I don't know what file I need to edit. – Luuk F. Mar 11 '18 at 17:50

2 Answers2

0

Don't use cookies, use localStorage/webStorage with JavaScript, that's really easy. If you google it, you will find lots of articles to that. (The articles from w3c schools are very good)

I hope, I hope I could help you, altough I don't answer directly to your question...

Ivo

0

So basically you can use Window.sessionStorage to access a session's data and document.cookie to set cookies.

So I guess you can start like this:

if(!sessionStorage.getItem('referrer')) {
    var referrer = document.referrer;
    ... your code
}

But since I'm not really aware of what you are trying to achieve it's hard to say if this is the right way. There are also other kind of storages you can make use of as provided in one of the previous answers. And not all of what you want to convert can be made within a browser.

Orlandster
  • 4,706
  • 2
  • 30
  • 45