homepage Welcome to WebmasterWorld Guest from 54.234.59.94
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Pubcon Platinum Sponsor 2014
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
Browser compatibility Issue with Login
Using PHP and Javascript
reffik024




msg:4564244
 3:40 pm on Apr 12, 2013 (gmt 0)

Hey, haven't been on here for a long time, forgot what a great resource WW is! I'm having this issue maybe someone can help me out with. The following login script works for me in Chrome and Safari, but for some reason (I think something to do with the header function), it won't work in Firefox or IE9/10.

session_start();
include 'dbcon.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 adminusers 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.";

//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 adminusers 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: login.php");
exit ();
}
}
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";
}
}



?>
<script language="JavaScript" type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script language="JavaScript" type="text/javascript" src="js/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#logForm").validate();
});
</script>

 

reffik024




msg:4564245
 3:44 pm on Apr 12, 2013 (gmt 0)

Sorry, header part is header("Location: ../index.php"); not header("Location: login.php");

penders




msg:4564254
 4:00 pm on Apr 12, 2013 (gmt 0)

According to the spec, the Location header should be an absolute URL with protocol.

reffik024




msg:4564263
 4:24 pm on Apr 12, 2013 (gmt 0)

hmm made it full URL still get nothing in those browsers

penders




msg:4564270
 4:41 pm on Apr 12, 2013 (gmt 0)

By "not work", do you mean it doesn't redirect? Have you checked the HTTP response headers to see that the cookies are being set and the Location header is being returned to the browser?

reffik024




msg:4564274
 4:57 pm on Apr 12, 2013 (gmt 0)

Correct it won't redirect. Check http response headers, cookie is being set but location header is not getting returned.

penders




msg:4564287
 5:23 pm on Apr 12, 2013 (gmt 0)

This is the redirect for successful login? You seem to be redirecting to login.php?

Do you have full error reporting set? ie. error_reporting(E_ALL | E_STRICT)

No output (ie. ie HTTP response) is occurring before this that would prevent the header from being set? No BOM? Although that would affect all browsers?!

You could try explicitly setting the HTTP Status code:
header('Location: http://example.com/login.php',true,302);

reffik024




msg:4564295
 5:55 pm on Apr 12, 2013 (gmt 0)

I had posted the wrong thing up, it's redirecting to index. I tried setting the http status code as you posted.

I don't have root access to edit php.ini so I'll have to wait til the admin gets in later today to turn on the error reporting. There's no output before this, this is the initial page and the code I pasted starts at line 1

reffik024




msg:4564308
 6:27 pm on Apr 12, 2013 (gmt 0)

Ok, admin added strict, rechecked it and still not getting error codes

penders




msg:4564312
 6:41 pm on Apr 12, 2013 (gmt 0)

FYI you don't need admin access to set full error reporting, just set this at the top of your script:
error_reporting(E_ALL | E_STRICT); 
ini_set('display_errors','1'); // Unless you have error handler to pipe to file


...no output before this


An erroneous space, blank line, BOM (Byte Order Mark), zero-width space, etc. But, as you say, this is probably not the case as you would get errors with full error reporting set.

Ermmm...?

reffik024




msg:4564320
 6:58 pm on Apr 12, 2013 (gmt 0)

Yeah and it's only affecting the two browsers. I noticed it's not validating properly either

reffik024




msg:4564321
 7:01 pm on Apr 12, 2013 (gmt 0)

Lemme show you the include as well:


<?php
define ("DB_HOST", ""); // set database host
define ("DB_USER", ""); // set database user
define ("DB_PASS",""); // set database password
define ("DB_NAME",""); // 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 = 0; // set 0 for manual activation, 1 for automatic with email sent

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);

/**** PAGE PROTECT CODE ********************************
This code protects pages to only logged in users. If users have not logged in then it will redirect to login page.
If you want to add a new page and want to login protect, COPY this from this to END marker.
Remember this code must be placed on very top of any html or php page.
********************************************************/

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 `adminusers` 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 adminusers 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/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();

$sess_user_id = strip_tags(mysql_real_escape_string($_SESSION['user_id']));
$cook_user_id = strip_tags(mysql_real_escape_string($_COOKIE['user_id']));

if(isset($sess_user_id) || isset($cook_user_id)) {
mysql_query("update `adminusers`
set `ckey`= '', `ctime`= ''
where `id`='$sess_user_id' OR `id` = '$cook_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/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 ;
}

}

?>

reffik024




msg:4574136
 6:50 pm on May 14, 2013 (gmt 0)

So I figured it out finally.

<input name="doLogin" type="image" src="login-btn.png" style="margin-left:90px;" id="doLogin3" value="Login">

Doesn't work with image for some reason in firefox and safari.

<input name="doLogin" type="submit" style="margin-left:90px;" id="doLogin3" value="Login">

This works.

penders




msg:4590551
 1:45 pm on Jul 5, 2013 (gmt 0)

The type="image" submit button doesn't work for you in some browsers because you are not checking the correct variable in your code. Unfortunately, some browsers do not return $POST['doLogin'] (the element name as it appears in code) for image submit buttons. Instead, they only return $_POST['doLogin_x] and $_POST['doLogin_y] (all browsers return these).

So, the cross browser check for this would be:
if (isset($_POST['doLogin_x'])) { /* rest of code */ }


However, I'm curious... you say this didn't work in Safari (although in your original question you say it did). Your existing code should work in Safari 5.1 on Windows (not tried Mac), since Safari (Windows) does return the plain old element name in the submitted form data.

Alternatively, use a standard submit button as you have done (recommended).

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved