Jump to content

Learning Php Cookies


driz
 Share

Recommended Posts

Hi, I'm testing out this code. The idea is for it to test for a cookie. If the condition is true then run the page as normal, IF NOT then include my warning.php page and EXIT the current page right there!Here is the code for index.php

<?php$warned = isset($_COOKIE['warned']) ? $_COOKIE['warned'] : $_GET['warned'];if($warned != 'true') {	include('warning.php');	exit;}else {		if(!isset($_COOKIE['warned'])) {		setcookie('warned', 'true');	}}?><html>	<head>		<title></title>	</head>	<body>		<h1>If you can see this then you have the cookie!</h1>	</body></html>

and here is the warning.php file that will be shown IF the user has not yet being warned

<html>	<head>		<title></title>	</head>	<body>		<h1>If you can see this then you DON'T have the cookie!</h1>				<p><a href="<?php echo $_SERVER['PHP_SELF']; ?>?warned=true">Click here for the cookie</a></p>			</body></html>

At the moment it does not work. Could you please point me in the right directions on how to get this to work and if need be any enhancements to improve the efficiency of the code thanks.EDIT: Also could you also share how I could easily edit this to use Sessions instead of cookies, so I can learn both ways of doing this. Thanks

Edited by driz
Link to comment
Share on other sites

What is it doing that's not right? If the cookie isn't getting set, check the manual for setcookie, there are other parameters you might want to define for the cookie. Also, some browsers have issues with cookies on localhost, so test this on an online server as well if you haven't.To you use sessions you would basically just replace the $_COOKIE array with the $_SESSION array. To set a value in the session you just assign the value to the array. e.g. $_SESSION['warned'] = true. You also need to use session_start on any page where you're going to use the session.

Link to comment
Share on other sites

Well it doesn't work. If I test it it just says I have the cookie and if I check the cookies then it has been set, so it turns out as soon as you visit the page the cookie is being set regardless of whether of not the user has chosen to set the cookie or not.

Link to comment
Share on other sites

With IE? It's always going to set the cookie if the user agent string does not contain "MSIE".
I've take IE out of the equation. Basically I want to check for the cookie, if no cookie is found then exit the script and show the warning.php file which will then allow the user to set the cookie. If the user DOES have the cookie then the normal page is run as usual.
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...