Function with cookies in PHP

Asked

Viewed 312 times

0

I need a php function that checks if the user has already accessed such a file, if yes, opens X javascript file, if not accessed, opens another javascript file.

Example: 1° access = open test.js 2° or more accesses = open ola.js

  • You can post some code that you’ve tried to do ??

1 answer

2


You can add a cookie to the user’s browser when they first access, and then check whether they already have such a cookie.

//Primeiro, verificamos se o usuário já possui o cookie
if(isset($_COOKIE['acesso'])) {

   //Se o usuário possuir o cookie no navegador, significa que já acessou a pagina
   //Então carregaremos o js ola
   echo '<script type="text/javascript" src="ola.js"></script>';

} else {

    //Se o usuário não possuir o cookie significa que nunca acessou a pagina
    //Então vamos setar o cookie, e carregar o js teste
    setcookie("acesso", 1, (time() + 100000));
    echo '<script type="text/javascript" src="teste.js"></script>'

}
  • Exactly what I wanted, thanks man! You can explain to me why this team and "1" after access?

  • 1 is because the cookie needs a value, so I put 1, and also because 1 is the same as true in some languages. Time() is a PHP method that returns the Unix timestamp from the exact moment the code was executed, so I used it to set the cookie expiration time, which would be 100000 seconds from the moment the cookie was placed (Team value)

  • Got it, thanks!

Browser other questions tagged

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