Forum Moderators: coopster

Message Too Old, No Replies

login script logs me out with non www version domain

login script log me out based on www and non www version domain

         

neo2sxn

12:41 am on Jun 22, 2012 (gmt 0)

10+ Year Member



Hi guys ,

i need your urgent help. I am using a login script that is redirecting me to login page when i use "www.example.com" , and when i enter "example.com" it keeps me login..
Please help me so that it should keep me login in on "example.com" or "www.example.com" or "subdomain.example.com"


This is coding on my login page -

include 'dbc.php';

$err = array();

foreach($_GET as $key => $value) {
$get[$key] = filter($value); //get variables are filtered.
}

if (@$_POST['doLogin']=='Login')
{

foreach($_POST as $key => $value) {
$data[$key] = filter($value); // post variables are filtered
}


$user_email = $data['usr_email'];
$pass = $data['pwd'];


if (strpos($user_email,'@') === false) {
$user_cond = "user_name='$user_email'";
} else {
$user_cond = "user_email='$user_email'";

}


$result = mysql_query("SELECT `id`,`pwd`,`full_name`,`approved`,`user_level` FROM users WHERE
$user_cond
AND `banned` = '0'
") or die (mysql_error());
$num = mysql_num_rows($result);

// Match row found with more than 1 results - the user is authenticated.
if ( $num > 0 ) {

list($id,$pwd,$full_name,$approved,$user_level) = mysql_fetch_row($result);

if(!$approved) {
//$msg = urlencode("Account not activated. Please check your email for activation code");
$err[] = "Account not activated. Please check your email for activation code";

//header("Location: login.php?msg=$msg");
//exit();
}

//check against salt
if ($pwd === PwdHash($pass,substr($pwd,0,9))) {
if(empty($err)){

// this sets session and logs user in
session_start();
session_regenerate_id (true); //prevent against session fixation attacks.

// this sets variables in the session
$_SESSION['user_id']= $id;
$_SESSION['user_name'] = $full_name;
$_SESSION['user_level'] = $user_level;
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);

//update the timestamp and key for cookie
$stamp = time();
$ckey = GenKey();
mysql_query("update users set `ctime`='$stamp', `ckey` = '$ckey' where id='$id'") or die(mysql_error());

//set a cookie

if(isset($_POST['remember'])){
setcookie("user_id", $_SESSION['user_id'], time()+60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_key", sha1($ckey), time()+60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_name",$_SESSION['user_name'], time()+60*60*24*COOKIE_TIME_OUT, "/");
}
header("Location: myaccount.php");
}
}
else
{
//$msg = urlencode("Invalid Login. Please try again with correct user email and password. ");
$err[] = "Invalid Login. Please try again with correct user email and password.";
//header("Location: login.php?msg=$msg");
}
} else {
$err[] = "Error - Invalid login. No such user exists";
}
}


Thank you

phranque

6:50 am on Jun 22, 2012 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



you need to set the domain for your cookie to example.com so the cookie is valid for all the subdomains of example.com.

g1smd

6:56 am on Jun 22, 2012 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



header("Location: myaccount.php");


The header should include the protocol and domain name, not just the path.

neo2sxn

1:11 pm on Jun 22, 2012 (gmt 0)

10+ Year Member



@phranque

thank you for your reply
can you tell me how to do it on my script ? i mean where to make change ?

@g1smd

Maybe you are little wrong. Header always did not need to include the protocol or domain.
well thank you too for your reply...

rocknbil

3:44 pm on Jun 22, 2012 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



setcookie("user_id", $_SESSION['user_id'], time()+60*60*24*COOKIE_TIME_OUT, "/");


You are missing the domain parameter here, set it to domain=.example.com

setcookie("user_id", $_SESSION['user_id'], time()+60*60*24*COOKIE_TIME_OUT, "/", '.example.com');

which will make the cookie valid for example.com, www.example.com, subdomain.example.com, etc.

Maybe you are little wrong. Header always did not need to include the protocol or domain.


Although it doesn't **need** it and it still "works," this doesn't make it correct. When you do this

header("Location: myaccount.php");

You are redirecting to the page in relation to where you are at this moment. This will fail, and fail horrendously, when you begin to use SEO-friendly URL's with mod_rewrite.

A more "correct" approach is to always use domain root-relative links and redirects:

header("Location: /myaccount.php");

Why? This makes your code more portable (you can use it on any domain,) it isn't locked into any particular location (it will work as well from /this/directory/deep or from the root,) and as mentioned will work just dandy in mod_rewrite environments.

Or sometimes you want to move between secure and non secure areas, in which case the full protocol

header("Location: https : //www.example.com/myaccount.php"); // spaces added only for this message board
header("Location: http : //www.example.com/myaccount.php");

or non-protocol specific

header("Location://www.example.com/myaccount.php");

may be needed.

neo2sxn

4:39 pm on Jun 22, 2012 (gmt 0)

10+ Year Member



Thank you for your great help rocknbil

But it did not solve my problem , still facing the same problem.


See db file also which i am including in login.php -



<?php
define ("DB_HOST", "localhost"); // set database host
define ("DB_USER", "root"); // set database user
define ("DB_PASS",""); // set database password
define ("DB_NAME","test"); // set database name

$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
$db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database");


$user_registration = 1; // set 0 or 1

define("COOKIE_TIME_OUT", 10); //specify cookie timeout in days (default is 10 days)
define('SALT_LENGTH', 9); // salt for password

//define ("ADMIN_NAME", "admin"); // sp

/* Specify user levels */
define ("ADMIN_LEVEL", 5);
define ("USER_LEVEL", 1);
define ("GUEST_LEVEL", 0);



/*************** reCAPTCHA KEYS****************/
$publickey = "#*$!#*$!#*$!#*$!#*$!#*$!#*$!#*$!#*$!#*$!#*$!";
$privatekey = "#*$!#*$!#*$!#*$!#*$!#*$!#*$!#*$!#*$!#*$!xx";



function page_protect() {
session_start();

global $db;

/* Secure against Session Hijacking by checking user agent */
if (isset($_SESSION['HTTP_USER_AGENT']))
{
if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT']))
{
logout();
exit;
}
}

// before we allow sessions, we need to check authentication key - ckey and ctime stored in database

/* If session not set, check for cookies set by Remember me */
if (!isset($_SESSION['user_id']) && !isset($_SESSION['user_name']) )
{
if(isset($_COOKIE['user_id']) && isset($_COOKIE['user_key'])){
/* we double check cookie expiry time against stored in database */

$cookie_user_id = filter($_COOKIE['user_id']);
$rs_ctime = mysql_query("select `ckey`,`ctime` from `users` where `id` ='$cookie_user_id'") or die(mysql_error());
list($ckey,$ctime) = mysql_fetch_row($rs_ctime);
// coookie expiry
if( (time() - $ctime) > 60*60*24*COOKIE_TIME_OUT) {

logout();
}
/* Security check with untrusted cookies - dont trust value stored in cookie.
/* We also do authentication check of the `ckey` stored in cookie matches that stored in database during login*/

if( !empty($ckey) && is_numeric($_COOKIE['user_id']) && isUserID($_COOKIE['user_name']) && $_COOKIE['user_key'] == sha1($ckey) ) {
session_regenerate_id(); //against session fixation attacks.

$_SESSION['user_id'] = $_COOKIE['user_id'];
$_SESSION['user_name'] = $_COOKIE['user_name'];
/* query user level from database instead of storing in cookies */
list($user_level) = mysql_fetch_row(mysql_query("select user_level from users where id='$_SESSION[user_id]'"));

$_SESSION['user_level'] = $user_level;
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);

} else {
logout();
}

} else {
header("Location: login.php");
exit();
}
}
}



function filter($data) {
$data = trim(htmlentities(strip_tags($data)));

if (get_magic_quotes_gpc())
$data = stripslashes($data);

$data = mysql_real_escape_string($data);

return $data;
}



function EncodeURL($url)
{
$new = strtolower(ereg_replace(' ','_',$url));
return($new);
}

function DecodeURL($url)
{
$new = ucwords(ereg_replace('_',' ',$url));
return($new);
}

function ChopStr($str, $len)
{
if (strlen($str) < $len)
return $str;

$str = substr($str,0,$len);
if ($spc_pos = strrpos($str," "))
$str = substr($str,0,$spc_pos);

return $str . "...";
}

function isEmail($email){
return preg_match('/^\S+@[\w\d.-]{2,}\.[\w]{2,6}$/iU', $email) ? TRUE : FALSE;
}

function isUserID($username)
{
if (preg_match('/^[a-z\d_]{5,20}$/i', $username)) {
return true;
} else {
return false;
}
}

function isURL($url)
{
if (preg_match('/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $url)) {
return true;
} else {
return false;
}
}

function checkPwd($x,$y)
{
if(empty($x) || empty($y) ) { return false; }
if (strlen($x) < 4 || strlen($y) < 4) { return false; }

if (strcmp($x,$y) != 0) {
return false;
}
return true;
}

function GenPwd($length = 7)
{
$password = "";
$possible = "0123456789bcdfghjkmnpqrstvwxyz"; //no vowels

$i = 0;

while ($i < $length) {


$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);


if (!strstr($password, $char)) {
$password .= $char;
$i++;
}

}

return $password;

}

function GenKey($length = 7)
{
$password = "";
$possible = "0123456789abcdefghijkmnopqrstuvwxyz";

$i = 0;

while ($i < $length) {


$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);


if (!strstr($password, $char)) {
$password .= $char;
$i++;
}

}

return $password;

}


function logout()
{
global $db;
session_start();

if(isset($_SESSION['user_id']) || isset($_COOKIE['user_id'])) {
mysql_query("update `users`
set `ckey`= '', `ctime`= ''
where `id`='$_SESSION[user_id]' OR `id` = '$_COOKIE[user_id]'") or die(mysql_error());
}

/************ Delete the sessions****************/
unset($_SESSION['user_id']);
unset($_SESSION['user_name']);
unset($_SESSION['user_level']);
unset($_SESSION['HTTP_USER_AGENT']);
session_unset();
session_destroy();

/* Delete the cookies*******************/
setcookie("user_id", '', time()-60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_name", '', time()-60*60*24*COOKIE_TIME_OUT, "/");
setcookie("user_key", '', time()-60*60*24*COOKIE_TIME_OUT, "/");

header("Location: login.php");
}

// Password and salt generation
function PwdHash($pwd, $salt = null)
{
if ($salt === null) {
$salt = substr(md5(uniqid(rand(), true)), 0, SALT_LENGTH);
}
else {
$salt = substr($salt, 0, SALT_LENGTH);
}
return $salt . sha1($pwd . $salt);
}

function checkAdmin() {

if($_SESSION['user_level'] == ADMIN_LEVEL) {
return 1;
} else { return 0 ;
}

}

?>

g1smd

7:35 pm on Jun 22, 2012 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



From the PHP manual [php.net...] see this:
HTTP/1.1 requires an absolute URI as argument to » Location: including the scheme, hostname and absolute path, but some clients accept relative URIs. You can usually use $_SERVER['HTTP_HOST'], $_SERVER['PHP_SELF'] and dirname() to make an absolute URI from a relative one yourself:...

"Some" clients "may" accept a relative URL. That's not good enough. Program it so that the server response satisfies all clients by including all of the elements. In particular, returning a partial URL to search engines is a very bad idea and unwanted interactions with the internal canonical hostname setting can give very odd results.

phranque

11:15 pm on Jun 22, 2012 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



rocknbil gave you the answer and i don't see where you've set the domain for your cookie in that code.

once you get that sorted, make sure you clear your browser cookies before retesting the code.
then use an appropriate developer tool in your browser to view the cookies for your domain and make sure the cookies belong to the root domain rather than a subdomain.

neo2sxn

8:10 am on Jun 23, 2012 (gmt 0)

10+ Year Member



@phranque

First coding is "login.php" , and second coding is "dbc.php".
I made changes according to rocknbil in login.php. But it did not seems to work for me ...

neo2sxn

8:10 am on Jun 23, 2012 (gmt 0)

10+ Year Member



@phranque

First coding is "login.php" , and second coding is "dbc.php".
I made changes according to rocknbil in login.php only. But it did not seems to work for me ...If any part should be change in "login.php" or in "dbc.php" ,then please tell me...

neo2sxn

3:27 pm on Jun 24, 2012 (gmt 0)

10+ Year Member



Is there no one to help me ?

phranque

9:49 pm on Jun 24, 2012 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



You are missing the domain parameter here, set it to domain=.example.com

setcookie("user_id", $_SESSION['user_id'], time()+60*60*24*COOKIE_TIME_OUT, "/", '.example.com');

rocknbil

3:31 pm on Jun 26, 2012 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Well, did you clear existing cookies for your domain, then change it for all three cookies in your original post? And of course .example.com = your .domain.com.

This is a commonly used approach, and yours a fairly common problem, this is the solution. You're missing something, and the code you posted has nothing to do with it - it's where you set the initial cookies, not clear them.