Cookies visitor counter in PHP

1

I am making a small code in PHP to create a cookie that serves to see if it is the first time you enter a page or what your visit number is. I miss a message that the variable is not declared, I do not know very well how this works of the cookies since they have not explained it properly.

Code:

<?php
    if(isset($_COOKIE['visitas']))
    {
        setcookie('visitas',$visitas+1,time()+3600*24);
        $mensaje = 'Numero de visitas: '.$_COOKIE['visitas'];   
    }
    else
    {
        setcookie('visitas',1,time()+3600*24);
        $mensaje = 'Bienvenido por primera vez a nuesta web';
    }

?>  
<html>
    <head>
        <title>Cookie</title>
    </head>
    <body>
        <p>
            <?php $mensaje;?>
        </p>    
    </body>
</html> 
    
asked by Mario Guiber 08.10.2017 в 12:51
source

1 answer

1

Change variable $visitas to $_COOKIE['visitas'] :

if ( isset( $_COOKIE[ 'visitas' ] ) ) {

    setcookie( 'visitas', $_COOKIE[ 'visitas' ] + 1, time() + 3600 * 24 );
    $mensaje = 'Numero de visitas: '.$_COOKIE[ 'visitas' ];
}
else {

    setcookie( 'visitas', 1, time() + 3600 * 24 );
    $mensaje = 'Bienvenido por primera vez a nuesta web';
}
    
answered by 08.10.2017 / 13:21
source