Hi, I'm trying to read a cookie that I've set with php with javascript. The cookie is for storing the username when logging in to a site. If the cookie has been set I want the focus in the inline popup to target the password field so that the user doesn't have to tab down from the username field of the login form.

the php script stores the cookie perfectly:

if (isset($_POST['remember'])){
	$expire = time()+60*60*24*30;
	setcookie("login_username", $username, $expire);
	echo $_COOKIE['login_username'];
}
else {
	if (isset($_COOKIE['login_username']) || isset($_COOKIE['password'])){
		$expire = time()-3600;
		setcookie("login_username", "", $expire);
	}
}

The javascript:

if (targetfocus == 'login_username'){
	alert(readCookie('login_username'));
	if (readCookie('login_username') == 'username'){
		targetfocus = 'password';
	}
}
$("#"+targetfocus).focus();

...

function readCookie(name) {  
    var cookieName = name + "=";
    var cookieArray = document.cookie.split(';'); 
	
    for (var i = 0; i < cookieArray.length; i++){  
        var cookie = cookieArray[i];  
        while (cookie.charAt(0)==' '){ 
		cookie = cookie.substring(1,cookie.length);
	}
        if (cookie.indexOf(cookieName) == 0){
		return cookie.substring(cookieName.length,cookie.length);
	}
	return null;
    }  
}

But when trying to read the cookie in the javascript code I receive null when I put an alert to the code. Why won't the javascript find the cookie? Is it because I'm running the site localhost on my laptop? Does that have an effect on cookies?

Please let me know if you have any tips or corrections to my code. Thank you very much!

Dani AI

Generated

Two separate issues can make a PHP-set cookie appear missing in JavaScript. First, your JS cookie parser returns null too early if the first cookie in the list does not match the requested name. Second, PHP defaults the cookie path to the current directory; if your page runs from a different path, document.cookie will not include it. You should set the cookie path to / and fix the JS lookup.

Example JS cookie helper (robust against multiple cookies and special chars):

function getCookie(name) {
  const m = document.cookie.match(new RegExp('(?:^|; )' + name.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') + '=([^;]*)'));
  return m ? decodeURIComponent(m[1]) : null;
}

// Focus password if username cookie exists
if (getCookie('login_username')) {
  document.getElementById('login_password').focus();
}

Set and delete the cookie in PHP with a consistent path:

$expire = time() + 60*60*24*30;
setcookie('login_username', rawurlencode($username), $expire, '/'); // make it visible site-wide

// Delete (must match path and domain used when setting)
setcookie('login_username', '', time() - 3600, '/');

Notes:

  • PHP and JS are not creating different cookies; the same name can exist at different paths or domains, which makes them look different. Deletion only works when path/domain match exactly. See PHP setcookie docs.
  • Do not rely on $_COOKIE immediately after setcookie; it is only populated on the next request. Use the value you just set if you need to render it now.
  • If you ever set HttpOnly on a cookie, JS cannot read it by design. See MDN on document.cookie and cookie attributes.

Recommended Answers

All 7 Replies

try this

if (targetfocus == 'login_username'){
	alert(readCookie('login_username'));
	if (readCookie('login_username') == 'username'){
		targetfocus = 'password';
	}
}
$("#"+targetfocus).focus();



function readCookie(name) {  
alert('HAHA NIKLAS KAN INTE JAVASCRIPT');
    var cookieName = name + "=";
    var cookieArray = document.cookie.split(';'); 
	
    for (var i = 0; i < cookieArray.length; i++){  
        var cookie = cookieArray[i];  
        while (cookie.charAt(0)==' '){ 
		cookie = cookie.substring(1,cookie.length);
	}
        if (cookie.indexOf(cookieName) == 0){
		return cookie.substring(cookieName.length,cookie.length);
	}
    }
return null;  
}

you'll need to include jquery to use the above code.
it might be that php is setting the cookie path in a particular folder on your site, then the javascript is looking for a cookie with a different path.
So when you set your cookie or get your cookie you prolly wanna specify the path (probably as /) regardless of whether it's php or javascript.
You can debug and see what your cookie's paramaters are by setting the cookie in php and in your javascript have:

document.write(document.cookie);

I couldn't solve it, so I decided to do it this way instead:

var loginFieldContent = document.getElementById("login_username").value;
	if (loginFieldContent != null){
		targetfocus = 'login_password';
	}
$("#"+targetfocus).focus();

I don't really know what I did wrong with the cookie thing, it might have been something done in the php. Still, I believe the way I did it now is much more effective but if anyone can find what I did wrong from the limited code I posted earlier then please let me know.

Thanks for all the help!

I just noticed something. When I delete the cookie named "login_username" with php, the cookie I created with javascript when searching for errors still remains (it was also named "login_username"). Does javascript and php create entirely different cookies? Or is this something that only happens when working on a localhost test server?

it wasn't the cookie path?

So you're saying that the server is saving the cookies in a different location on the users computer than the javascript does?

I tested it.
You can read cookie which created with php.
You only need to add '/' (path)!!

setcookie("login_username", $username, $expire, '/');

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.