Avatar of Crazy Horse
Crazy HorseFlag for South Africa

asked on 

undefined index setting cookie

If I check the "remember me" checkbox and login, the cookie is set as it should be. However, if I don't check it I get a "undefined index" error. I am not sure how to resolve this. The error is for the very first line with the if statement.

if($_POST['remember']=="on"){
						
						$cookie_name = 'userID';
						$value = $safe_userID;
						$expire = time() + 60*60*24*7; 
						$path = '/';
						$domain = NULL;
						$secure = FALSE;
						$httponly = TRUE; 

setcookie($cookie_name, $value, $expire, $path, $domain, $secure, $httponly);

Open in new window


P.S. I am not actually using the auto increment user id, I have another one stored in the database which is created with:

 return strtr(
        base64_encode(
            random_bytes(9)
        ),
        '+/',
        '-_'
    );

Open in new window

PHP

Avatar of undefined
Last Comment
Dave Baldwin
Avatar of Crazy Horse
Crazy Horse
Flag of South Africa image

ASKER

I also tried to set the cookie if on and set a session instead if cookie is off. I am still getting undefined index errors though.

      
if($_POST['remember'] === "on"){
						
						$cookie_name = 'userID';
						$value = $userID;
						$expire = time() + 60*60*24*7; 
						$path = '/';
						$domain = NULL;
						$secure = FALSE;
						$httponly = TRUE; 

setcookie($cookie_name, $value, $expire, $path, $domain, $secure, $httponly);
						
					}
							
					elseif($_POST['remember'] == ""){
						
							$_SESSION['userID'] = $userID;
					}	

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Kim Walker
Kim Walker
Flag of United States of America image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

I never heard of setting $domain = NULL;.  Cookies are available ONLY on a specified domain.  The simplest cookie must have name, value and expiration.  Then the domain is set to the current domain shown in the browser address bar.  If you include things after the domain, I'm pretty sure you have to specify the domain.  

It is always good to set the correct domain because you can only read the cookie from the correct domain.  This means that the cookie domain must match exactly the domain shown in the browser address bar.  A cookie set for 'www.mysite.com' will Not match 'mysite.com' unless you have used the ',' syntax for the domain when setting the cookie.  I had one situation where I had to try every variation of the domain name to get rid of an unwanted cookie.

http://php.net/manual/en/function.setcookie.php
Avatar of Crazy Horse
Crazy Horse
Flag of South Africa image

ASKER

@ Dave, setting the domain to NULL was actually an example from Ray Paseur which can be found here:

https://www.experts-exchange.com/articles/2391/PHP-Client-Registration-Login-Logout-and-Easy-Access-Control.html



 // CONSTRUCT A "REMEMBER ME" COOKIE WITH THE UNIQUE USER KEY
    $cookie_name    = 'uuk';
    $cookie_value   = $uuk;
    $cookie_expires = time() + date('Z') + REMEMBER;
    $cookie_path    = '/';
    $cookie_domain  = NULL;
    $cookie_secure  = FALSE;
    $cookie_http    = TRUE; // HIDE COOKIE FROM JAVASCRIPT (PHP 5.2+)

Open in new window

Avatar of Crazy Horse
Crazy Horse
Flag of South Africa image

ASKER

Never mind, ignore the previous comment. I was doing something silly. I can login now if I check the checkbox, if I don't check the box then the page just refreshes. At least I don't get an error anymore so I must almost be there. But I think it is because if the remember me isn't checked, I need to set a session instead, otherwise it still won't work. I tried it but still no luck.

	if(isset($_POST['remember'])) {
						
							if($_POST['remember'] === "on"){
      
						
						$cookie_name = 'userID';
						$value = $userID;
						$expire = time() + 60*60*24*7; 
						$path = '/';
						$domain = NULL;
						$secure = FALSE;
						$httponly = TRUE; 

setcookie($cookie_name, $value, $expire, $path, $domain, $secure, $httponly);
								
								
						
					} elseif($_POST['remember'] !== "on") {
								
								$_SESSION['userID'] = $sessionID;
							}
					
				
					    }	
				

Open in new window


I have noticed though by changing the page redirect on the user area, that it redirects me straight away. So, it is logging me in but the session either isn't set or my condition on the user admin page is wrong?

session_start();
if(isset($_SESSION['userID']) || isset($_COOKIE['userID'])) {
	
	//stuff happens
	
} else {
	
	header("location:login.php");

}

Open in new window

SOLUTION
Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
Avatar of Crazy Horse
Crazy Horse
Flag of South Africa image

ASKER

Hi Dave, makes sense. What should I set it to when using on localhost using mamp? My path looks like:

http://localhost:8888/mysite/auth/

Also, any idea why my session isn't setting if remember me box isn't checked?
Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

You should not be using 'localhost' to start with.  Chrome won't set a cookie at all on 'localhost' and of course, you have no access from other computers.  I have 14 computers with web servers here and all of them use either their machine IP address or the machine 'hostname'.  The only use for 'localhost' is for functions / page that you do not want remote access to.  Still, things like cookies in Chrome simply aren't going to work.
Avatar of Crazy Horse
Crazy Horse
Flag of South Africa image

ASKER

I don't have a live web server at this point in time so I use MAMP for testing locally. I can successfully set the cookie and the login works as it should with the cookie set i.e.: Once logged in I close the browser and reopen, go back to the url and I remain logged in. I haven't created the logout code yet but if I clear the cache of the Chrome browser, close the browser down and try access the page, it takes me back to the login page. So, the cookie is working on my local machine.

But my session still isn't setting if I don't check remember me.
Avatar of Crazy Horse
Crazy Horse
Flag of South Africa image

ASKER

Okay, I think I figured it out using reverse logic:

      
				if(empty($_POST['remember'])) {
								
                                                               // Set session
								$_SESSION['sessionID'] = $userID;
						
					} elseif($_POST['remember'] == "on"){
								
                                               //Set cookie
						$cookie_name = 'userID';
						$value = $userID;
						$expire = time() + 60; 
						$path = '/';
						$domain = www.mysite.com;
						$secure = FALSE;
						$httponly = TRUE; 

setcookie($cookie_name, $value, $expire, $path, $domain, $secure, $httponly);

		}

Open in new window

Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

MAMP includes the Apache web server along with PHP and MySQL.
PHP
PHP

PHP is a widely-used server-side scripting language especially suited for web development, powering tens of millions of sites from Facebook to personal WordPress blogs. PHP is often paired with the MySQL relational database, but includes support for most other mainstream databases. By utilizing different Server APIs, PHP can work on many different web servers as a server-side scripting language.

125K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo