Need single popup for each session

I want the popup ad to appear once only for any visitor no matter how many pages are visited. So I was using this code but I find that this code is popping up a new ad for each page visited. How can I correct it?:

<?php if(!isset($_COOKIE['ad_zedo'])) {

 setcookie('ad_zedo',1);
?>
<script language="JavaScript">
var zflag_nid="1185"; var zflag_cid="3307"; var zflag_sid="823"; var zflag_width="1"; var zflag_height="1"; var zflag_sz="15";
</script>
<script language="JavaScript" src="http://d8.zedo.com/jsc/d8/fo.js"></script>

<?php
}
?>

Answers


The cookie is expiring because you haven't set an expiry time. Set an expiry like:

setcookie('ad_zedo',1, time()+60*60*24*30); // 30 days

From the Manual:

Expire

If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes).

Also, don't forget that setting a cookie is sending a HTTP header so you can't have any output before using setcookie().


You could also store the flag in the PHP session instead of a cookie. Doing it that way would mean the popup would show when a new PHP session is started (the expiry of which is defined by your server config).

<?php if(!isset($_SESSION['ad_zedo'])) {

 $_SESSION['ad_zedo'] = true;
?>

You'll need session_start() on each page.


OK as MrCode already said: You should work with Sessions as for example with your code would be following - not tested but should do the thing...

<?php 
session_start();
if(!isset($_SESSION['ad_zedo'])) {
$_SESSION['ad_zedo'] = true;
?>
<script language="JavaScript">
var zflag_nid="1185"; var zflag_cid="3307"; var zflag_sid="823"; var zflag_width="1";      var zflag_height="1"; var zflag_sz="15";
</script>
<script language="JavaScript" src="http://d8.zedo.com/jsc/d8/fo.js"></script>

<?php
}
?>

K this should do the magic ;).


Call setcookie at the beginning of the page, before any output or headers are sent to the server, otherwise the cookie is never set:

<?php 
    $showadzedo = false;
    if(!isset($_COOKIE['ad_zedo'])) { $showadzedo = true; setcookie('ad_zedo',1); } 
?>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>

[...]

<?php if($showadzedo) { ?>
    <script language="JavaScript">
    var zflag_nid="1185"; var zflag_cid="3307"; var zflag_sid="823"; var zflag_width="1"; var zflag_height="1"; var zflag_sz="15";
    </script>
    <script language="JavaScript" src="http://d8.zedo.com/jsc/d8/fo.js"></script>
<?php } ?>

Need Your Help

Database design - How much data to store, performance vs quality

mysql sql database database-design

There is some value, x, which I am recording every 30 seconds, currently into a database with three fields:

Convert mysql query logic to Laravel query builder

php mysql laravel laravel-4 query-builder

I am trying to convert my mysql query logic to Laravel query builder. I I have no Idea how to convert it as laravel query.