Cookie不适用于整个网站

I'm having two issues with setting and retrieving cookies.

  1. Cookie gets loaded but can't be called until page is refreshed. Meaning that the cookie shows up in developer tools but not when trying to use its value on the page. The value does seem available to use on page after refreshing.
  2. Cookie is not available across entire domain and subdirectories. For example, if the user enters at http://example.com/sub/ the goes to http://example.com/, the cookie gets destroyed.

Here's my code:

$ad_source = $_GET['source'];
$date_of_expiry = time() + (86400 * 7);
setcookie('ad_source',$ad_source,$date_of_expiry,'/');

if ( $_COOKIE['ad_source'] == 'adwords_campaign_01' ) {
    echo '... do something';
} elseif ( $_COOKIE['ad_source'] == 'adwords_campaign_02' ) {
    echo '... do something else';
}

I'm trying to to show different information throughout entire site by determining what adwords campaign the user clicked in on.

I don't usually use cookies and prefer to set a session, but in this case I want be able to track the source for a longer amount of time.

Everything is working as expected now. A little more insightful information into cookies at this post helped a lot.

PHP cookie set in second refresh page

  1. Redirect user to page after cookie is set. Second request from browser sends cookie, server returns info relative to its value.

  2. Check to see if $ad_source is set before creating cookie.

The updated code:

$ad_source = $_GET['source'];
$date_of_expiry = time() + (86400 * 7);

if ( $ad_source ) {

  setcookie('ad_source',$ad_source,$date_of_expiry,'/','example.com');

  if ( $_COOKIE['ad_source'] == 'adwords_campaign_01' ) {
    header( 'Location: http://example.com/' );
    echo '... do something';
  } elseif ( $_COOKIE['ad_source'] == 'adwords_campaign_02' ) {
    header( 'Location: http://example.com/' );
    echo '... do something else';
  }

}