Qualche tempo fa, indeciso tra iubenda e altre soluzioni, pensai di crearmi il mio script “cookielaw”. Questo perché, molto semplicemente, tutti questi script sono inevitabilmente “imperfetti”.
Cioè, loro avvisano della presenza dei cookie e chiedono se si accetta oppure no, ma – intanto – banner e altri script vengono già caricati (e quindi anche i cookie). Questo rende inefficace lo script stesso.
Io, pertanto, avevo pensato ad una soluzione decisamente diversa: intercettare la richiesta tramite htraccess e mandare su una pagina provvisoria (senza banner e niente) dove si chiede se accettare o meno la presenza dei cookie”. Così viene impostato il cookie “solo se si accetta”, altrimenti si esce. Il problema è che molti, purtroppo, non continuavano la navigazione (e quindi uscivano). Per questo preferii abbandonare questa soluzione.
Tuttavia, desidero condividerla nel caso in cui qualcuno desiderasse provarla!
htaccess:
RewriteEngine On RewriteBase /_script/coockielawtest/ # Check if cookie exist (cookie landing page): RewriteCond %{HTTP_HOST}@@%{HTTP_COOKIE} !^([^@]*)@@.*__ckl=1.* [NC] # If not one of this script (u can add more...): RewriteCond %{REQUEST_URI} !/(_ckl.php|sitemap.xml)$ [NC] # And not this file extension: RewriteCond %{REQUEST_URI} !.(jpg|png|css|js|ico|txt)$ [NC] # And doen't have this querystring: RewriteCond %{QUERY_STRING} !(rss=1) [NC] # And isn't one of this useragent (allow bot): RewriteCond %{HTTP_USER_AGENT} !(CloudFlare-AlwaysOnline|altavista|validator|googlebot|google|yahoo|aol|bing|crawl|aspseek|icio|robot|spider|nutch|slurp|msnbot) [NC] RewriteCond %{THE_REQUEST} ^[A-Z]+ ([^s]+) RewriteRule .* /_script/coockielawtest/_ckl.php?law=%1 [L,NC,NE]
il rewritebase dipende da dove mettiamo il codice… se nella root (per l’intero sito) sarà solo “/”.
poi abbiamo il ckeck del cookie;
salta se chiedo uno di questi file, o estensioni, o querystring (altrimenti lo script non funzionerebbe, causerebbe errore, non caricherebbe le immagini e renderebbe invalidi anche gli rss e la sitemap);
infine, lascia passare tali useragent (google e simili – così non compromettiamo l’indicizzazione).
_ckl.php:
<?php header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");// Date in the past header("Last-Modified: ". gmdate("D, d M Y H:i:s")." GMT"); header("Cache-Control: private, no-store, max-age=0, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0",false); header("Pragma: no-cache"); /* Do not touch this... */ $host = $_SERVER['HTTP_HOST'];if(isset($_SERVER['HTTP_REFERER'])){ $ref = $_SERVER["HTTP_REFERER"];} $requri = $_SERVER["REQUEST_URI"]; $cleanuri = htmlentities(urldecode($requri)); // Config: $sitename ="L'AltroWeb"; $sitetitle ="CookieLaw: '".$cleanuri."' - ".$sitename." | Web... e tanto altro!"; $sitedescription = $sitename." | Web... e tanto altro! Una community nata per raccogliere e discutere di argomenti di varia natura..."; $keywords ="l'altroweb, php, cms, invision, salvatore, noschese, darkwolf, altervista, informatica, adsl"; $favicon ="https://www.laltroweb.it/favicon.ico?v=2016"; // random background image#$path = "_cookieimg/";#$img = array("_cookie_.png", "_christmas_.jpg");#$bgset = '//'.$host.'/'.$path.$img[rand(0,count($img)-1)].''; // CSS#$body_background = "rgba(0, 0, 0, 0) url('".$bgset."') no-repeat fixed 0 0 !important"; $body_background ="rgba(0, 0, 0, 1) url('//".$host."/_bg_img/matrix_world_map.jpg') no-repeat fixed center center !important"; $page_background_color ="221,221,221"; $page_border_color ="#262e33"; $hr_border_color ="#262E33"; $input_background_color ="#F0F0F0"; $input_hover_background_color ="#CCFFCC"; $span_color ="#3D556C"; $footer_background_color ="95,95,95"; $footer_logo_img ="https://www.laltroweb.it/uploads/monthly_2015_11/laltroweb_logo.png"; // Lang:if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){ $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'],,2);}else{ $lang ="en";}switch($lang){ case"it":// Change or clone... $line1 ="Info: Questo sito o gli strumenti terzi da questo utilizzati si avvalgono di cookie necessari al corretto funzionamento."; $line2 ="Cliccando su "Accetto", acconsenti all'uso dei cookie."; $pagelabel ="Pagina richiesta: "; $ok ="Accetto"; $go ="Vai:"; $exit ="Esci (back)"; break; case"en": default: $line1 ="Notice: This website or its third party tools use cookies which are necessary to its correct functioning."; $line2 ="By clicking "Continue", you agree to the use of cookies."; $pagelabel ="Request page: "; $ok ="Continue"; $go ="Go:"; $exit ="Exit (back)"; break;} // Prevent unuseful loop with back and same host session_start();if(empty($ref)|| strpos($ref, $host)!==false){ $back ="https://www.google.it/";}else{ $_SESSION["origURL"]= $ref; $back = htmlentities($_SESSION["origURL"]);} // Set cookie on submit and go to location $cookiename = str_replace(".","_","__cookielaw__".$host);if(!isset($_REQUEST['law'])){ header("HTTP/1.0 403 Forbidden"); echo " <html> <title>403 Forbidden</title> <body> <h1>Forbidden</h1> <p>You don’t have permission to access ".$_SERVER["REQUEST_URI"]." on this server.</p> <p>Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.</p> </body> </html>"; exit;} elseif (isset($_COOKIE[$cookiename])&& isset($_REQUEST['law'])){ header("location: //".$host.$requri);} elseif (isset($_POST["setck"])&&!empty($_POST["setck"])){ setrawcookie($cookiename,"__ckl=".$host, time()+31556926,'/'); header("location: //".$host.$requri); } // Thumb my link $thumbthis ="https://".$host.$requri;/* remove if no apc */if(!$image = apc_fetch("thumbnail:".$thumbthis )) { /* remove if no apc */ $image = file_get_contents("https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url=$thumbthis&screenshot=true"); $image = json_decode($image,true); $image = $image['screenshot']['data'];/* remove if no apc */ apc_add("thumbnail:".$thumbthis, $image,2400); }/* remove if no apc */ $image = str_replace(array('_','-'),array('/','+'),$image); /* Ok, print code */ echo '<!DOCTYPE html> <html lang="'.$lang.'"> <head> <meta charset="utf-8"> <title>'.$sitetitle.'</title> <script>!function(){window.localStorage&&(localStorage.getItem("firstLoad")?localStorage.removeItem("firstLoad"):(localStorage.firstLoad=!0,window.location.reload()))}();</script> <meta http-equiv="pragma" content="no-cache" /> <meta name="description" content="'.$sitedescription.'" /> <meta name="keywords" content="'.$keywords.'" /> <link rel="shortcut icon" href="'.$favicon.'" /> <style> body { background: '.$body_background.'; text-align: center; margin: 0 auto; padding: 100px 20px; } @media (max-width: 1024px) { body { padding: 10px !important; } } @media only screen and (orientation: landscape) { body { max-width: 1040px; } } @media only screen and (orientation: portrait) { body { max-width: 900px; } } #page { background-color: rgb('.$page_background_color.'); background-color: rgba('.$page_background_color.', 0.9); border: 3px dotted '.$page_border_color.'; padding: 10px; min-width: 350px; } hr { border-top: 1px solid '.$hr_border_color.'; width: 90%; } form { padding-top: 10px; } input { font-size: 18px; height: 40px; width: 250px; color: #394248; cursor: pointer; background-color: '.$input_background_color.'; } input:hover { background-color: '.$input_hover_background_color.'; } p { margin: 5px; } h4 { font-style: italic; } h5 { color: '.$span_color.'; } #page, #fakesandbox, input, footer { border-radius: 10px; } footer { background: rgb('.$footer_background_color.'); background-color: rgba('.$footer_background_color.', 0.6); color: #fff; font-style: italic; padding: 5px; } </style> </head> <body> <div id="page"> <h1>CookieLaw landing page:</h1> <h2>'.$line1.'</h2> <h3>'.$line2.'</h3> <hr /> <form id="cookieform" method="post" action=""> <input type="submit" title="'.$go.' '.'.$cleanuri.''" name="setck" value="'.$ok.' 😊" /> <input type="button" title="Referer: ''.$back.''" name="exit" value="'.$exit.' 😕" onclick="window.location.href=''.$back.''" /> </form> <h4>'.$pagelabel.'</h4> <img src="data:image/jpeg;base64,'.$image.'" style="border: 1px solid #000;" alt="link-thumbnail" title="''.$cleanuri.''" /> <h5>'.'.$cleanuri.''</h5> <hr /> <footer> <p><img src="'.$footer_logo_img.'" title="'.$sitename.' - Logo" alt="thumbnail" /></p> <p>'.$sitedescription.'</p> </footer> </div> </body> </html>';
Lo script è personalizzato, e genera una thumbnail per la pagina di destinazione…
Qui una demo: https://www.laltroweb.it/_script/coockielawtest/index.html
Qui il cookie che viene generato “solo se” si accetta:
Una volta accettato, e attivato il cookie, la landing page non verrà mai più mostrata 😉
PS: Allego i file usati per la demo nell’area download:
< https://www.laltroweb.it/files/file/25-htaccess-cookielaw/? >
Provai ogni variante, e sistemai ogni problema. Dovrebbe essere tutto ok (ad esempio, se si chiama direttamente lo script da un errore “forbidden” senza causare strani loop).
Per dubbi, richieste, o semplicemente per discuterne, commentate pure 🙂