Solved

set cookie with php on index.php

Posted on 2014-02-03
22
745 Views
Last Modified: 2014-02-05
I am using the code below to try and set a cookie with php.  It works fine in every page I try it in except for index.php.   The code is in an include and all of the other code executes fine it just does not set the cookie.  I am also opperating this site with https:// does that have anything to do with why it will not work on index.php?

setcookie( "affiliateCookie", "$affiliateID", $date_of_expiry, "/", ".prizemagnet.com") ;

Open in new window

0
Comment
Question by:Luey
  • 8
  • 8
  • 3
  • +2
22 Comments
 
LVL 17

Expert Comment

by:OmniUnlimited
ID: 39831438
Can I see where in index.php you are including the file that sets the cookie?
0
 
LVL 20

Expert Comment

by:Mark Brady
ID: 39831508
Try changing the include 'filename.php' or whatever the filename is to require_once 'filename.php';

Then after that line echo something out to see if it is finding the file insode your index.php file. But I agree.

Post your index.php code and also tell us what paths these files are in or if they all reside in the same folder?
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39832064
This article shows how it is done.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_3314-How-to-Show-an-Introductory-Web-Page-Once-Using-PHP.html

Cookies can be set for HTTPS-only or for HTTP and HTTPS.  I believe the default is to set the cookie for both.

Cookies can be set for entire domains or only for subdomains.  The same is true for entire directories or only for subdirectories.

Deconstructing your setcookie() we have this.  It looks theoretically fine to me.  So there are some possible things to look for... Do you have error_reporting(E_ALL) set?  If not, turn it on to see if one or more of these variables are undefined.  Have you used browser tools to look for the cookie?  Have you verified that the program logic cannot omit the call to setcookie()?

setcookie
( "affiliateCookie"    // COOKIE NAME
, "$affiliateID"       // COOKIE VALUE
, $date_of_expiry      // COOKIE EXPIRATION
, "/"                  // COOKIE DIRECTORY PATH
, ".prizemagnet.com"   // COOKIE DOMAIN
) 
;

Open in new window

I visited prizemagnet.com which took me to https://www.prizemagnet.com/ and then I looked for cookies using Firefox.  I also visited https://www.prizemagnet.com/index.php with Firefox.  I found the PHPSESSID cookie, so it's obvious that the site can set cookies correctly.  This leads me to believe that there is a logic error in index.php causing it to bypass the setcookie() function.
0
 

Author Comment

by:Luey
ID: 39832988
I am still looking at some of the other stuff you said Ray.  To set this cooking you have to come from an affiliate link.  I have no problem with this on any other page in my site accept index.php.   There is other code in the include that executes just fine on index.php.  The only way the program logic would omit the setcookie is if the url variable was not present.  That is not the case because the other code in that "if" is executed just fine.  

Here is what an example link should look like.

https://prizemagnet.com/Home/AF/21


Here is all the code in the include.
<?php
if (isset($_GET['affiliate_id'])) { //if they have come from an affiliate link
 
   $affiliateID = $_GET['affiliate_id']; //get the affiliate_id variable
   $affiliate_url = $_SERVER['HTTP_REFERER']; //get the url of the page they came from. this will not always work. Tell affiliates
   $landing_page = $_SERVER['REQUEST_URI']; //gets the file path to the landing page. Does not get complete url.
/*---------------------------------------------------------------------------------------------------------------------------------*/
//here we are tracking if they have already visited from this particular affiliate or not. Not sure we need it but it is here if so.
if (isset($_COOKIE['affiliateCookie'])){
	
	$current_cookie = $_COOKIE['affiliateCookie'];
/*--------------------------------------------------*/
     if ($current_cookie == $affiliateID){
	     $visit_type = 1; //if they already have and affiliate cookie and it is this affiliate's cookie then mark as = 1 return visit
     } //end if $current_cookie == $affiliateID
	 
	 else {
		 $visit_type = 0; //if they already have and affiliate cookie and it is not this affiliate's cookie then mark as = 0 first visit
	 } //end else
/*--------------------------------------------------*/
} //end if isset($_COOKIE['affiliateCookie']

else {   
	$visit_type = 0; //if the do not already have an affiliate cookie then mark as = 0 new visit
}   						  
/*---------------------------------------------------------------------------------------------------------------------------------*/
  $insertSQL = sprintf("INSERT INTO affiliate_tracking (aft_affiliate_id, aft_visit_type, aft_landing_page, aft_page_url) VALUES (%s, %s, %s, %s)",
                      
                       GetSQLValueString($affiliateID, "int"),
					   GetSQLValueString($visit_type, "int"),
					   GetSQLValueString($landing_page, "text"),
                       GetSQLValueString($affiliate_url, "text"));

  mysql_select_db($database_hootdata, $hootdata);  
  $Result1 = mysql_query($insertSQL, $hootdata) or die(mysql_error());	  
/*---------------------------------------------------------------------------------------------------------------------------------*/
//set the cookie for this $affiliateID
      setcookie( "affiliateCookie", "", time()-3600, "/", ".prizemagnet.com") ;  
     
	   
	   $number_of_days = 90 ; //variable for days to set cookie to expire
       $date_of_expiry = time() + 60 * 60 * 24 * $number_of_days ; //does math to put the number of days into seconds
	   
      setcookie( "affiliateCookie", "$affiliateID", $date_of_expiry, "/", ".prizemagnet.com") ;
	  
/*---------------------------------------------------------------------------------------------------------------------------------*/	  
} //end if isset($_GET['affiliate_id'])
/*---------------------------------------------------------------------------------------------------------------------------------*/
?>

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39833026
I just visited that page.  Am I supposed to see a cookie with the name affiliateCookie?  I'm not getting it.  I am getting PHPSESSID and four __utm* cookies, probably Google tracking cookies.

Consider adding error_reporting(E_ALL) to the top of the script to see if there is any reliance on an undefined variable.
0
 

Author Comment

by:Luey
ID: 39833121
Visit this page and see if you get the cookie set. I do when I visit is.  It is all from the same include.   I also added error_reporting(E_ALL); at the top and got no errors.

https://www.prizemagnet.com/AboutUs/AF/2
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39833759
Yes, I got it.Prizemagnet Affiliate Cookie
0
 

Author Comment

by:Luey
ID: 39834017
So that brings us back to square one.  Why will the same include not write the cooking on index.php?
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39834078
I took the code block and removed all of the comments (sometimes they can be confusing) and then I lined up all of the control structures so the program logic would stand out clearly.

The only way the script will get to the setcookie() on line 39 appears to be determined on line 2.  It won't get there unless there is a GET method request that contains 'affiliate_id' in the URL.

<?php
if (isset($_GET['affiliate_id'])) 
{ 
    $affiliateID   = $_GET['affiliate_id']; 
    $affiliate_url = $_SERVER['HTTP_REFERER']; 
    $landing_page  = $_SERVER['REQUEST_URI']; 

    if (isset($_COOKIE['affiliateCookie']))
    {
        $current_cookie = $_COOKIE['affiliateCookie'];
        
        if ($current_cookie == $affiliateID)
        {
            $visit_type = 1; 
        } 
        else 
        {
            $visit_type = 0; 
        }
    } 
    else 
    {
        $visit_type = 0; 
    }

    $insertSQL = sprintf("INSERT INTO affiliate_tracking (aft_affiliate_id, aft_visit_type, aft_landing_page, aft_page_url) VALUES (%s, %s, %s, %s)",
    GetSQLValueString($affiliateID,   "int"),
    GetSQLValueString($visit_type,    "int"),
    GetSQLValueString($landing_page,  "text"),
    GetSQLValueString($affiliate_url, "text")
    );

    mysql_select_db($database_hootdata, $hootdata);  
    $Result1 = mysql_query($insertSQL, $hootdata) or die(mysql_error());
    
    setcookie( "affiliateCookie", "", time()-3600, "/", ".prizemagnet.com") ;  
    $number_of_days = 90 ;
    $date_of_expiry = time() + 60 * 60 * 24 * $number_of_days ; 
    setcookie( "affiliateCookie", "$affiliateID", $date_of_expiry, "/", ".prizemagnet.com");
}

Open in new window

0
 

Author Comment

by:Luey
ID: 39834419
Hey Ray, I really appreciate your continued effort.
I put this code in the body of my page and it echos the url variable just fine.

<?php if (isset($_GET['affiliate_id'])){
	echo $_GET['affiliate_id'];
}?>

Open in new window


Here is what my mod re-write looks like for this.  Maybe there is something wrong there.

RewriteRule ^/?Home/AF/(.*)$ /index.php?affiliate_id=$1  [QSA,NC,L]
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 33

Expert Comment

by:Slick812
ID: 39836213
greetings Luey, , I have a small idea of what you may be doing with your cookie, as far as me using cookies, I usually test for a cookie wid -
if (isset($_COOKIE["affiliateCookie"])) {
    //some cookie code
    } else
    setcookie( "affiliateCookie", "$affiliateID", $date_of_expiry, "/", ".prizemagnet.com") ;

I almost never set cookies unless there is not a cookie, or the cookie value is no longer valid. As far as your problem, I seems to me you absolutely need an ELSE for the IF when there is no $_GET['affiliate_id']) as in -


 $date_of_expiry = time() + 60 * 60 * 24 * $number_of_days ;
if (isset($_GET['affiliate_id'])) {

    } else
    setcookie( "affiliateCookie", "Default Value", $date_of_expiry, "/", ".prizemagnet.com") ;

Or I beleive you can also test for cookie After the code as -

if (isset($_GET['affiliate_id'])) {
    /// your code work here
    }
if (!isset($_COOKIE["affiliateCookie"])) {
    //set your Default "affiliateCookie" cookie here
    }
0
 

Author Comment

by:Luey
ID: 39836308
Thanks for your comments Slick.  I will have to test around to see if I can make something work from that.

The problem with what you are saying is it does not work with my logic.  
The logic is if the url variable affiliate_id is present do all the code in the include.  The else would be to do nothing at all.
Also I am destroying the cookie first so there is not cookie by this name.  The reason I am doing that is to give the last affiliate that drove the traffic the credit for making the sell.  So basically if the url variable is there destroy the old cookie and set a new one.  
This works on every page in my website except index.php.  Every bit of the code works except for the setcookie().

I just now removed everything in the include but the code below and it still will not work on index.php but will work on every other page in the site.

$affiliateID = 555;

setcookie( "affiliateCookie", "", time()-3600, "/", ".prizemagnet.com") ;  //destroy any cookies first see dc
	   
	   $number_of_days = 90 ; //variable for days to set cookie to expire
       $date_of_expiry = time() + 60 * 60 * 24 * $number_of_days ; //does math to put the number of days into seconds
	   
      setcookie( "affiliateCookie", "$affiliateID", $date_of_expiry, "/", ".prizemagnet.com") ;

Open in new window

0
 
LVL 33

Expert Comment

by:Slick812
ID: 39836352
can you test for the cookie in the index.php with
if (!isset($_COOKIE["affiliateCookie"])) {
    //set your Default "affiliateCookie" cookie here
    }


Not in the includes? ? As all here, I can not see any code malfunction
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39836355
Please make a backup of index.php, then install this script in place of index.php, run it without any URL parameters and post the output back here, thanks.  As soon as you have run it, put your own index.php back.  Make sure you do not leave a copy of this script on your server since it would create a potential security exposure.

<?php // RAY_dump_superglobals.php
error_reporting(E_ALL);
session_start();

// MAKE THE OUTPUT EASY TO READ
echo '<pre>';

// OPEN AN OUTPUT BUFFER
ob_start();

// SHOW THE SUPERGLOBALS
echo PHP_EOL . "GET ";     var_dump($_GET);
echo PHP_EOL . "POST ";    var_dump($_POST);
echo PHP_EOL . "FILES ";   var_dump($_FILES);
echo PHP_EOL . "COOKIE ";  var_dump($_COOKIE);
echo PHP_EOL . "SESSION "; var_dump($_SESSION);

// CAPTURE THE BUFFER
$vardump = ob_get_clean();

// SEND THE RESULTS
mail('Ray.Paseur@GMail.com', 'VARDUMPS', "$vardump");

// SHOW THE RESULTS
echo htmlentities($vardump);

Open in new window

0
 

Author Comment

by:Luey
ID: 39836487
GET array(0) {
}

POST array(0) {
}

FILES array(0) {
}

COOKIE array(12) {
  ["__utma"]=>
  string(57) "259582539.2061385319.1385494279.1391621079.1391624343.209"
  ["__utmz"]=>
  string(101) "259582539.1391478629.202.30.utmcsr=thecowboyshoponline.com|utmccn=(referral)|utmcmd=referral|utmcct=/"
  ["admin1Cookie"]=>
  string(11) "Mag_Admin_1"
  ["admin2Cookie"]=>
  string(11) "Mag_Admin_2"
  ["userCookie"]=>
  string(4) "1338"
  ["groupCookie"]=>
  string(1) "M"
  ["prizemag_sell"]=>
  string(1) "1"
  ["prizemag_email"]=>
  string(20) "test@prizemagnet.com"
  ["prizemag_zip"]=>
  string(5) "30170"
  ["PHPSESSID"]=>
  string(32) "27cd798355030fd9f39489ac71b3bad1"
  ["__utmc"]=>
  string(9) "259582539"
  ["__utmb"]=>
  string(25) "259582539.3.10.1391624343"
}
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39836494
Yes, that's kind of what I expected.  There is nothing in $_GET, so there will never be a signal that will tell the script to set the cookie.

Let's try it from a little bit different perspective.  Instead of trying to debug this design, please tell us in plain language what you want the design to achieve.  Maybe we can suggest a different logical approach to the problem.

How familiar are you with the operation of online shopping carts?  For example, could you be confident of your ability to write one from scratch?
0
 

Author Comment

by:Luey
ID: 39836583
Ray,  there may be a little confusion going on.  Because this is an example url we would be trying to make work on the home page.  

Vist https://www.prizemagnet.com/Home/AF/888

I placed this code at the bottom of the page so you can see that it indeed picks up the url parameter.

<?php 
echo PHP_EOL . "GET ";     var_dump($_GET);
?>

Open in new window


Yes very confident in building a shopping cart from scratch.  I actually have my own design that I have implemented on several sites.  Here is an example of one of my sites with my shopping cart.
http://thecowboyshoponline.com/
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39836848
There is something else wrong with the logic that I cannot see immediately.  Please refer back to this:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28355616.html#a39833759

When I visit https://www.prizemagnet.com/Home there is no GET request and no cookie gets set.

When I visit https://www.prizemagnet.com/Home/AF/123 There is a GET request:
GET array(1) { ["affiliate_id"]=> string(3) "123" } but no cookie gets set.

We have the PHP session cookie, so I expect the cookie mechanism is working OK.  I'd like to see if the setcookie() script is getting run at all.  Please add this right before the end of the final control brace.

trigger_error('COOKIE DONE', E_USER_WARNING);
0
 
LVL 33

Accepted Solution

by:
Slick812 earned 500 total points
ID: 39836916
You say - "This works on every page in my website except index.php", and yet PHPSESID cookie is set at the https://www.prizemagnet.com/Home/AF/888

I do not believe that cookie can be set if there is any String output from the index.php page before the call to setcookie( ), this can be any space or linefeed, OR any php system warning or error. That is what I would look at, page output before the call for setcookie( ) , I do not think that just because it is the index.php page that cookies are disabled or not working, if the PHP system is not allowing cookies, it would likely issue a warning,

as I have already said, you might try and set a cookie on the index.php script page, to see if being in the includes code have a bearing here, but from your code experience, you have already thought of these things.

you may extend the last output to -

<?php
echo PHP_EOL . "check test  ";     var_dump($_GET, $date_of_expiry);
?>
if the $date_of_expiry is empty, without a date number, then the include code is NOT running.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39837327
@slick: Even with default reporting levels, the failure of header(), setcookie() or session_start() will raise a warning.  I think for some reason on the home page this setcookie() code is not getting run at all.

To clarify, here is the original script with the recommended modification:

<?php
if (isset($_GET['affiliate_id'])) { //if they have come from an affiliate link
 
   $affiliateID = $_GET['affiliate_id']; //get the affiliate_id variable
   $affiliate_url = $_SERVER['HTTP_REFERER']; //get the url of the page they came from. this will not always work. Tell affiliates
   $landing_page = $_SERVER['REQUEST_URI']; //gets the file path to the landing page. Does not get complete url.
/*---------------------------------------------------------------------------------------------------------------------------------*/
//here we are tracking if they have already visited from this particular affiliate or not. Not sure we need it but it is here if so.
if (isset($_COOKIE['affiliateCookie'])){
	
	$current_cookie = $_COOKIE['affiliateCookie'];
/*--------------------------------------------------*/
     if ($current_cookie == $affiliateID){
	     $visit_type = 1; //if they already have and affiliate cookie and it is this affiliate's cookie then mark as = 1 return visit
     } //end if $current_cookie == $affiliateID
	 
	 else {
		 $visit_type = 0; //if they already have and affiliate cookie and it is not this affiliate's cookie then mark as = 0 first visit
	 } //end else
/*--------------------------------------------------*/
} //end if isset($_COOKIE['affiliateCookie']

else {   
	$visit_type = 0; //if the do not already have an affiliate cookie then mark as = 0 new visit
}   						  
/*---------------------------------------------------------------------------------------------------------------------------------*/
  $insertSQL = sprintf("INSERT INTO affiliate_tracking (aft_affiliate_id, aft_visit_type, aft_landing_page, aft_page_url) VALUES (%s, %s, %s, %s)",
                      
                       GetSQLValueString($affiliateID, "int"),
					   GetSQLValueString($visit_type, "int"),
					   GetSQLValueString($landing_page, "text"),
                       GetSQLValueString($affiliate_url, "text"));

  mysql_select_db($database_hootdata, $hootdata);  
  $Result1 = mysql_query($insertSQL, $hootdata) or die(mysql_error());	  
/*---------------------------------------------------------------------------------------------------------------------------------*/
//set the cookie for this $affiliateID
      setcookie( "affiliateCookie", "", time()-3600, "/", ".prizemagnet.com") ;  
     
	   
	   $number_of_days = 90 ; //variable for days to set cookie to expire
       $date_of_expiry = time() + 60 * 60 * 24 * $number_of_days ; //does math to put the number of days into seconds
	   
      setcookie( "affiliateCookie", "$affiliateID", $date_of_expiry, "/", ".prizemagnet.com") ;
	  
/*---------------------------------------------------------------------------------------------------------------------------------*/
/**
 * SOUND OFF
 */
trigger_error('COOKIE DONE', E_USER_WARNING); 	  
} //end if isset($_GET['affiliate_id'])
/*---------------------------------------------------------------------------------------------------------------------------------*/
?>

Open in new window

0
 

Author Closing Comment

by:Luey
ID: 39837581
I am so mad at myself for putting you guys through this.  There was a space being output just below the session_start().  It is entirely my fault for not already checking for that.  I have learned that lesson before the hard way and I apologize for dragging you guys through that silly mistake. Thanks for reminding me Slick and thank you Ray for your diligence. I have learned a lot from you Ray in the past and probably in the future.
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Suggested Solutions

I. Introduction There's an interesting discussion going on now in an Experts Exchange Group — Attachments with no extension (http://www.experts-exchange.com/discussions/210281/Attachments-with-no-extension.html). This reminded me of questions tha…
Styling your websites can become very complex. Here I'll show how SASS can help you better organize, maintain and reuse your CSS code.
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
HTML5 has deprecated a few of the older ways of showing media as well as offering up a new way to create games and animations. Audio, video, and canvas are just a few of the adjustments made between XHTML and HTML5. As we learned in our last micr…

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now