Save visit cookie to page

Asked

Viewed 450 times

1

Hello I am using a mysql php code that counts the visits of each page, but whenever the page is updated it adds one more visit, I would like a help with my code so that it saves the cookie for a certain time before counting a new visit.

PS: each page is saved in the BD and has different views

Page code:

<?php 
//Aqui pegamos o id da página
$idDaPagina = $explode[1];

//Busca na tabela o numero de vezes que a página ja foi visitada
$busca = "SELECT * FROM contador WHERE idPagina = '$idDaPagina'";
$exe = mysqli_query($conectar,$busca);

$resultado_vist = (mysqli_fetch_array($exe));

//Pega o numero de visistas que consta na tabela, adiciona mais um e atualiza
$visitantes = $resultado_vist['visitas'] + 1;
$altera = "UPDATE contador SET visitas = '$visitantes' WHERE idPagina = '$idDaPagina'";
$exe1 = mysqli_query($conectar,$altera);

//Faz uma nova busca e retorna o numero de visitas depois da atualização
$exe = mysqli_query($conectar,$busca);
$total = (mysqli_fetch_array($exe));
$visitas = $total['visitas'];

?>

No espaço do conteudo dou um <?php echo $visitas; ?>

From now on Thank you.

1 answer

2

You can work with cookies, set the time needed for it and when it expires, you add +1 to the counter. It would be the following code:

// Define em horas quanto tempo vai durar cada cookie
$hours = 1;

// Comando para setar o cookie
setcookie("contador", true, time() + (3600 * $hours));

// Verificação do cookie
if (isset($_COOKIE["contador"]) && $_COOKIE['contador'] == true ) {
    // Faz nada...
} else {
    // Logica para adicionar mais 1 a visitas de páginas
}
  • there is another problem, I can not use the setcookie on my pages counting the visits individually because use url friendly, my index has the header and footer and only receives the contents that are on the other pages, and how I have to use the cookie before any html it records a single visit.

  • 2

    Just use the cookie string concatenated with your page id. Example "id-counter" . $idDaPagina. So each cookie will be valid for each page in a different way.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.