SitePoint Sponsor |
|
User Tag List
Results 1 to 12 of 12
Thread: PHP Cookie Problem
-
Jul 28, 2006, 23:47 #1
PHP Cookie Problem
Oki, so I'm currently making a website for my website and graphic design business, and I made a client login system on a test server which worked perfectly.
However I just bought hosting and a domain, and transferred the MySQL databases and php files over exactly the same (except I changed the username, password, and database names needed), and now it does not work.
I looked over the code, and it all seems fine and should work - but I tried the login on both servers, checked my temporary internet files, and it turns out that my client login is no longer creating cookies as it did before. And these cookies, along with the MySQL database, are what allows a user to stay logged in. I checked the database and it seems fine though - all the fields are filled out correctly, etc.
So that leaves me with one question. Why can't I get the cookies to work on this server?
I also checked the variables - domain, path, name, etc. and it all should work.
Anyone have any ideas?
-
Jul 29, 2006, 01:40 #2
Here's the source code btw.
What's happening is the client is logging in with a quick login form at the top of the page, and this PHP is included at the top of all pages. Note that in the error display portion of the code, there are 5 instances where the program knows why the user is logged out, however, there is 1 instance that is undiagnosed - this is the error code that is being produced on my website. It thinks that it should be able to login - however when it tries it can't because the cookie is missing.
PHP Code:<?
/* Settings */
define("COOKIE_NAME","Concord"); //name of the cookie
define("COOKIE_EXPIRY","3600"); //length of cookie life - in seconds - no less than 30 mins (1800 seconds)
define("COOKIE_DOMAIN",$_SERVER["HTTP_HOST"]); //set the domain the cookie answers to
define("COOKIE_PATH","/"); //path that the cookie is valid for - default is "/" (everywhere)
define("MEMBERS_TABLE","clients"); //name of the database to check the username/password against
define("SESSIONS_TABLE","client_sessions"); //name of the sessions table
define("SESSION_EXPIRY","1800"); //life of the session, in seconds
define("LOGIN_PAGE","index.html"); //page that the login form and the session error messages are shown
/* an array of page names that have restricted access. WARNING: do not have the LOGIN_PAGE in
the restricted pages array, you will create an endless loop when an error condition occurs */
$RESTRICTED_PAGES=Array("login.html");
/* Functions */
function manageCookie() {
//if there is no cookieid - then we are going to set a cookie.
if(strlen($_COOKIE[COOKIE_NAME]) < 1) {
/* create a unique value for the database/cookie key
take the current time in miliseconds. */
list($msec,$sec)=explode(" ",microtime());
$cookiekey=ereg_replace("\.","",($msec+$sec));
$cookieexpiry=time()+COOKIE_EXPIRY; //set cookie expiry - X seconds from now
setcookie(COOKIE_NAME,"$cookiekey",$cookieexpiry,COOKIE_PATH,COOKIE_DOMAIN,0); //set the cookie
/*
set the _COOKIE variable so it can be used on this same page if just set, otherwise
the variable is not available on the same page the the cookie is?set
*/
$_COOKIE[COOKIE_NAME]=$cookiekey;
unset($cookiekey,$msec,$sec,$cookieexpiry);//clean up
} else {
//if the cookie has been set then we are just going to adjust the expiry date.
$cookieexpiry=time()+COOKIE_EXPIRY;
setcookie(COOKIE_NAME,$_COOKIE[COOKIE_NAME],$cookieexpiry,COOKIE_PATH,COOKIE_DOMAIN,0); //set the cookie
unset($cookieexpiry); //cleanup
}
}
function site_login() {
global $c,$user,$password;
/* Error Code Listing
80081 - missing username or password
80082 - invalid username
80083 - invalid password
1 - successfull login
*/
foreach($_REQUEST as $x=>$y) { stripslashes($y);$_REQUEST[$x]=mysql_escape_string($y); } //filter out $_REQUEST variables for database query
if($_REQUEST[username] && $_REQUEST[password]) {
$q="select * from ".MEMBERS_TABLE." where binary username='$_REQUEST[username]'"; //query to load by username - using BINARY to ensure a case sensitive match
$res=@mysql_query($q,$c); //load user info from members database based on the unique username
$row=mysql_fetch_array($res);
if($row[username]!=$_REQUEST[username]) {
return 80082;
} //check for valid username
/* when checking password, we md5 the posted password, because in the database
we are assuming the for security reasons the password is md5'd. If it is not, remove
the md5 function from around the $_GET[password] */
if(md5($_REQUEST[password]) != $row[password]) {
return 80083;
} // check for valid password
/* if we are still here, then it is a good login, and we will save the info to the
sessions database. */
$res=@mysql_query("delete from ".SESSIONS_TABLE." where session_id='".$_COOKIE[COOKIE_NAME]."'",$c); //remove any old session that may be in there
/* save the session info - I have saved the basics that I could figure out here,
but you may have to add in the type, gall_level and gall_count since I do not know where
they are coming from - whether they are in the member database or what... */
session_start();
$_SESSION['user'] = $row[username];
$_SESSION['password'] = $row[password];
if(isset($_SESSION['user'])) {
$user = $_SESSION['user'];
}
if(isset($_SESSION['password'])) {
$password = $_SESSION['password'];
}
$q="insert into ".SESSIONS_TABLE." set session_id='".$_COOKIE[COOKIE_NAME]."',login_time='".date("Y-m-d H:i:s")."',last_active='".date("Y-m-d H:i:s")."',username='$row[username]',level='$row[level]'";
$res=@mysql_query($q,$c);
// print $q;
// exit();
if($_REQUEST[remember]) {
$rmid=base64_encode($_REQUEST[username]);
setcookie(RMID,$rmid,time()+60*60*24*365,COOKIE_PATH,COOKIE_DOMAIN,0);
}
return 1; //return the successfull login code
} else {
return 80081; //return the missing variable code
}
}
function site_logout() {
global $c;
/* remove them from the sessions database, and delete their cookie by expiring it
we return the code 80084 so that we can treat it as a pseudo 'error' message on the
login page to notify them that they are logged out. */
$res=@mysql_query("delete from ".SESSIONS_TABLE." where session_id='".$_COOKIE[COOKIE_NAME]."'",$c);
setcookie(COOKIE_NAME,$_COOKIE[COOKIE_NAME],time()-86400,COOKIE_PATH,COOKIE_DOMAIN,0);
return 80084;
}
function checksite_login() {
global $c,$USER_INFO;
/* Error Code Listing
80085 - session expired
80000 - not logged in
*/
if(sizeof($USER_INFO["session_id"]) > 0) {
//if we are here they they have a session logged
if((time()-strtotime($USER_INFO["last_active"])) > SESSION_EXPIRY) {
//we just checked to see if they have been inactive for longer than we want
setcookie(COOKIE_NAME,$_COOKIE[COOKIE_NAME],time()-86400,COOKIE_PATH,COOKIE_DOMAIN,0);
return 80085; //return expired session code
}
//if we are still here, then they are good to go - update the last_active.
$res=@mysql_query("update ".SESSIONS_TABLE." set last_active='".date("Y-m-d H:i:s")."' where session_id='".$_COOKIE[COOKIE_NAME]."'",$c);
return 1; //return code for success
} else {
return 80000; //return code for not being logged in.
}
}
function errorCodeDisplay($code="") {
switch($code) {
case "80081":
return "Enter a Username and Password.";
break;
case "80082":
return "Incorrect Username.";
break;
case "80083":
return "Incorrect Password.";
break;
case "80084":
return "Logged Out.";
break;
case "80085":
return "Session Expired, Login Again.";
break;
case "80086":
return "";
break;
}
}
/* Actions */
//$c=mysql_connect(DB_HOST,DB_USER,DB_PASS) or die("Cannot connect to database");
//mysql_select_db(DB_NAME) or die("Unable to select the database");
manageCookie(); //issue the cookie
//try to load the user record.
$res=mysql_query("select * from ".SESSIONS_TABLE." where session_id='".$_COOKIE[COOKIE_NAME]."'",$c); //load user information
$USER_INFO=mysql_fetch_array($res); //sets session info into the array $USER_INFO
//if the user wants to login, it will trigger this code here when the action 'login' is sent through
if($_REQUEST[action]=="login") {
$result=site_login();
if($result!=1) {
//send them back to the login page with an error code to be looked up and displayed
header("Location: error.html?code=$result");
exit();
} else {
//send them to somewhere we want them to go next.
header("Location: login.html");
exit();
}
}
//if the user wants to logout, it will trigger this code here when the action 'logout' is sent through
if($_REQUEST[action]=="logout") {
header("Location: error.html?code=".site_logout());
exit();
} //log out the user
/* on any other page, we assume that they maybe logged in. if so then we want to update their
want to check to see if they have expired, and if not, update their last active time. */
if($_REQUEST[action] != "login" && $_REQUEST[action]!="logout" && $_REQUEST[code]!=80085) {
$login_check=checksite_login();
if($login_check==80085) {
//send them back to the login page with an error code to be looked up and displayed
header("Location: error.html?code=$login_check");
exit();
}
}
/* the final check that we do is to see if this is a page that they have access to. If we
are here, then either they are not logged in, or they are good to be here. Either way
we need to check to see if this is a restricted page, and if it is, whether they have
permissions to be here or not. I am initially assuming that anyone that is logged in
has access to the restricted page. If it is different that that, then the conditionals
in this function are all that need to be changed. */
//get the name of the current page.
$tmp=explode("/",$_SERVER[PHP_SELF]);
$current_page=$tmp[(sizeof($tmp)-1)];
/* if the current page is in the restricted list,
and the $login_check variable is not 1 (true) then they cannot have access.
The error code returned to the login page is 80086 */
if(in_array($current_page,$RESTRICTED_PAGES) && $login_check!=1) { header("Location: error.html?code=80086"); exit(); }
/* if we are here, then this user has permission to view this page - VIOLA! :)
If you are using actions to display different functions on the page, i.e. an index page that
based on the action displays different things, do not put that pagename in the
restricted pages array, simply do the last conditional check above inside the case for that
action, it will check the restriction only when that case is triggered. */
?>
-
Jul 29, 2006, 11:38 #3
Ok, here's something else weird
The code works in firefox, but will not work in IE or Opera.
So does anyone have an idea what would cause cookies not to be set properly in IE and Opera?
-
Jul 29, 2006, 11:49 #4
- Join Date
- Mar 2006
- Posts
- 6,132
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
whats is the value of $_SERVER["HTTP_HOST"] under the different browsers(any variable prefixed with HTTP_* is a value which came as part of the http headers, meaning the browser sent it.)
is it prefixed with www. or another subdomain?
generally you want to set the cookie with a leading . which is a wildcard for all subdomains.
.example.org
-
Jul 29, 2006, 11:58 #5
the value of $_SERVER["HTTP_HOST"] should be the same, but I switched that line to
define("COOKIE_DOMAIN",".concorddesign.ca"); //set the domain the cookie answers to
is that what you meant?
still no luck in IE and Opera - still works perfectly in Firefox.
-
Jul 29, 2006, 20:39 #6
- Join Date
- Jul 2006
- Posts
- 36
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Have you tested in IE with cookies set to Prompt?
At least this will test and see if the cookie command is at least trying to be set by IE.
If the script tries and sets the cookie, IE will prompt you to allow it first.
Just my 2 cents...
JROX.COM Affiliate Manager
Free Affiliate Management System
-
Jul 29, 2006, 23:10 #7
if it doesnt work out, you might also consider using $_SESSION instead.. its generally easier to use and you dont put any more information on the clients computer
-
Jul 29, 2006, 23:28 #8
Yeah, I've used sessions before as well - but I've heard this way is more effective for security since it needs a cookie with information and as well as a database entry to be able to work.
I'll try the prompt suggestion in a sec.
-
Jul 30, 2006, 01:50 #9
sessions dont require a database.. by default its done on the filesystem and its quite fast..
securitywise its definitly better to just use sessions.. and just the session cookie
-
Jul 30, 2006, 07:54 #10
- Join Date
- Jul 2006
- Posts
- 9
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Dude, I am having exactly the same problems with sessions, although it is a bit simpler code wise:
PHP Code:ini_set('session.use_cookies', 1);
session_name ('Project_Manager');
//session_set_cookie_params (900, '', '');
session_start();
header("Cache-control: private"); /* IE 6 Fix */
PHP Code:$_SESSION['user_id'] = $row[user_id];
$_SESSION['email'] = $row['user_email'];
$_SESSION['name'] = $row['user_name'];
$_SESSION['agent'] = md5($_SERVER['HTTP_USER_AGENT']);
Although the problem in firefox is that logout is not working which is as follows (after including the initial session_start code above):
PHP Code:$_SESSION = array();
session_destroy();
setcookie ('session_name()', '', time()-300,'/','', 0);
Please do it for me if you fix it.
Thanks.
-
Jul 30, 2006, 08:16 #11
- Join Date
- Jul 2006
- Posts
- 9
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Ah sorted the logout, it was one of those problems that make you feel ridiculously silly.
-
Jul 30, 2006, 10:51 #12
- Join Date
- Mar 2006
- Posts
- 6,132
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
i was just about to point it out to you. all of us have done it before
Bookmarks