最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

php - Setting a cookie upon specific URL visit

matteradmin9PV0评论

I'm trying to set up, when a specific page/url is visited that a cookie is set and saved.

So far I've tried this:

add_action('init', 'set_cookie', 1);

function set_cookie(){

  if ( $currentURL == '/' ) :

    if ( ! isset( $_COOKIE['opt_in'] ) ) :
        setcookie( 'opt_in', has_opt_in, time()+31556926);

    endif;

  endif;

}

Now, when I visit the specific URL, cookie is detected, but when I move on to another page, cookie is gone.

How can the cookie be saved?

I'm pretty new to this, please help me understand.

Thank you!

I'm trying to set up, when a specific page/url is visited that a cookie is set and saved.

So far I've tried this:

add_action('init', 'set_cookie', 1);

function set_cookie(){

  if ( $currentURL == 'https://25dni.si/delovanje-uma/' ) :

    if ( ! isset( $_COOKIE['opt_in'] ) ) :
        setcookie( 'opt_in', has_opt_in, time()+31556926);

    endif;

  endif;

}

Now, when I visit the specific URL, cookie is detected, but when I move on to another page, cookie is gone.

How can the cookie be saved?

I'm pretty new to this, please help me understand.

Thank you!

Share Improve this question asked Nov 29, 2018 at 15:08 AlexAlex 213 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 1

I've used this and it works:

 add_action('init', 'optin_cookie', 1);

 function optin_cookie(){

   $currentURL = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

   if ( $currentURL == 'https://25dni.si/delovanje-uma/' ) :

    setcookie( 'opt_in', has_opt_in, time()+31556926, '/');

   elseif ( $currentURL != 'https://25dni.si/' ) :

     if ( ! isset( $_COOKIE['opt_in'] ) ) :

     endif;

    endif;

 }

I'm sure there is a much more elegant way to do it, but this got it working for me ...

I'm surprised it works at all since $currentURL is not defined in the function nor declared as a global.

Look at the documentation for setcookie(). You did not declare a path for the cookie so try this:

setcookie('opt_in','opt_in', time()+31556926, '/');

That will set the cookie for the entire domain, if that's what you want to do.

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far