cookie base64_decode not working correctly - php

Im trying to set a cookie when the user selects the checkbox to remember his data.
I´m setting cookie and encoding if checkbox is selected:
if($f['save'])
{
$cookiesave = base64_encode($adminEmail).'&'.base64_encode($f['pass']);
setcookie('admin',$cookiesave,time()+60*60*24*30,'/');
}
And then I´m decoding
elseif(!empty($_COOKIE['admin']))
{
$cookie = $_COOKIE['admin'];
$cookie = explode('&',$cookie);
$f['email'] = base64_decode($cookie[0]);
$f['pass'] = base64_decode($cookie[1]);
$f['save'] = 1;
}
But despite being doing the decode, the input appears with encrypted password.
I have reviewed all the code and everything seems to be right ... can see anything wrong?
My full code:
<?php
if(isset($_POST['sendLogin']))
{
$f['email'] = mysql_real_escape_string($_POST['email']);
$f['pass'] = mysql_real_escape_string($_POST['pass']);
$f['save'] = mysql_real_escape_string($_POST['remember']);
$autEmail = $f['email'];
$autSenha = md5($f['pass']);
$readAdmin = read('admins',"WHERE email = '$adminEmail'");
if($readADmin){
foreach($readAdmin as $admin);
if($adminEmail == $admin['email'] && $adminPass == $admin['pass'])
{
if($f['save'])
{
$cookiesave = base64_encode($adminEmail).'&'.base64_encode($f['pass']);
setcookie('admin',$cookiesave,time()+60*60*24*30,'/');
}
else
{
setcookie('admin','',time()+3600,'/');
}
}
else
{
echo 'Wrong Password';
}
}
else
{
echo 'Email dont exist in DB';
}
}
}
elseif(!empty($_COOKIE['admin']))
{
$cookie = $_COOKIE['admin'];
$cookie = explode('&',$cookie);
$f['email'] = base64_decode($cookie[0]);
$f['pass'] = base64_decode($cookie[1]);
$f['save'] = 1;
}
echo '<pre>';
print_r($cookie);
echo
'</pre>';
?>
<?php
if(!isset($_GET['remember']))
{
?>
<form name="login" action="" method="post">
<label>
<span>Email:</span>
<input type="text" class="radius" name="email" value="<?php if(isset($f['email'])) echo $f['email']; ?>" />
</label>
<label>
<span>Password:</span>
<input type="password" class="radius" name="pass" value="<?php if(isset($f['pass'])) echo $f['pass']; ?>" />
</label>
<input type="submit" value="Login" name="sendLogin" class="btn" />
<div class="remember">
<input type="checkbox" name="remember" value="1" <?php if(isset($f['save'])) echo 'checked="checked"' ?> />
Remember Acess data!
</div>
</form>
<?php
}

This is a tested login form (PHP 5.3.18). The comments at the start of the script explains how it works and how to use it.
<?php
/*
* Q22459571
*
* a Login script:
*
* There are three actions it will do:
*
* 1) Display a login screen and process the results
*
* 2) Logout a user who has been 'remembered' or 'saved' see 'admin' cookie.
*
* 3) Automatically login a user from the details in the admin' cookie.
*
* The script action is controlled by a parameter in the URL called 'action'.
*
* The 'action' values and results are as follows:
*
* 1) action='login' : will clear any cookies and force the login screen to be shown
*
* 2) action='logout' : will clear any cookies and exit the script
*
* 3) missing 'action' parameter : a) try and login using the 'admin' cookie.
* b) show the login screen if not
* able to login.
*
* The result of the script will be saved in a '$userAuth' array as follows:
*
* 1) 'email' => user email address as stored on the db.
* 2) 'passhash' => MD5 hash as stored on the database
* 3) 'remember' => boolean to indicate that the user can be logged in
* via the 'admin' cookie
* 4) 'loginMethod' => '', 'cookie', 'form'
* 5) 'loginSuccess'=> true | false
*
*/
/*
* We will use 'mysqli' functions, prepared queries and 'bind' variables/values
*/
/*
* User table:
*
* store password as a 'salted' hash
*
* Columns: 1) email -- unique id for an admin
* 2) passhash -- password as a MD5 hash
* 3) salt -- random string that we will use as a prefix to the plaintext password
* before we take the md5 hash.
*/
// database connection...
$mysqlDb = mysqli_connect('localhost', 'test', 'test', 'testmysql');
// User Authorization details will always be in here...
$userAuth = array( 'email' => '', 'passhash' => '', 'remember' => false,
'loginMethod' => '', 'loginSuccess' => false);
// set the login action so we can use it later
$loginAction = isset($_GET['action']) ? $_GET['action'] : '';
/*
* see what the URL action is
*/
if ($loginAction == 'logout')
{
setcookie('admin', '' , 0, '/'); // delete cookie
echo 'user logged out'; // do what you wish here
exit; // leave the script
}
if ($loginAction == 'login')
{
if (!empty($_COOKIE['admin'])) // clear the cookie to force login
{
setcookie('admin', '' , time() + 3600, '/'); // will be empty next time
}
}
elseif (!empty($_COOKIE['admin'])) // The cookie should be encrypted -- not in this version.
{
$cookie = $_COOKIE['admin'];
$emailLen = substr($cookie, 0, 3); // get the length
$b64 = substr($cookie, 3); // get b64 encoded string
$b64decoded = base64_decode($b64); // convert back to original string
// split it up...
$userAuth['email'] = substr($b64decoded, 0, $emailLen);
$userAuth['passhash'] = substr($b64decoded, $emailLen);
$userAuth['remember' ] = 1;
// ensure user is in the database and the details match...
$sql = 'SELECT email, salt from admins WHERE email = ? and passhash = ? limit 1';
$query = mysqli_prepare($mysqlDb, $sql);
$allOk = mysqli_stmt_bind_param($query, 'ss', $userAuth['email'], $userAuth['passhash']);
$allOk = mysqli_execute($query);
$queryResult = mysqli_stmt_get_result($query);
$admin = mysqli_fetch_array($queryResult);
$userAuth['loginMethod'] = 'cookie';
$userAuth['loginSuccess'] = !empty($admin['email'])
&& $admin['email'] === $userAuth['email'];
if ($userAuth['loginSuccess'])
{
echo 'user: ', $userAuth['email'], ' was logged in via the cookie...';
exit;
}
else
{
echo 'user: ', $userAuth['email'], ' cookie details are wrong!!';
exit;
}
}
/*
* We may have a login request that we need to check...
*/
if (isset($_POST['sendLogin'])) // new login attempt
{
$userAuth['loginMethod'] = 'form';
$userAuth['loginSuccess'] = false;
$userAuth['email'] = mysqli_real_escape_string($mysqlDb, $_POST['email']);
$userPass = mysqli_real_escape_string($mysqlDb, $_POST['pass']);
$userAuth['remember'] = mysqli_real_escape_string($mysqlDb, $_POST['remember']);
// will use prepared queries and bind parameters as required
$sql = 'SELECT email, passhash, salt from admins WHERE email = ? limit 1';
$query = mysqli_prepare($mysqlDb, $sql);
$allOk = mysqli_stmt_bind_param($query, 's', $userAuth['email']);
$allOk = mysqli_execute($query);
$queryResult = mysqli_stmt_get_result($query);
$admin = mysqli_fetch_array($queryResult); // admin details
if ( !empty($userAuth['email']) && $userAuth['email'] == $admin['email']
&& !empty($userPass))
{
// calculate the MD5 hash and assume it is ok
$userAuth['passhash'] = md5($admin['salt'] . $userPass);
}
if (!empty($userAuth['passhash']) && $userAuth['passhash'] === $admin['passhash']) // passwords must have matched
{
$userAuth['loginSuccess'] = true;
if ($userAuth['remember' ])
{
$emailLen = sprintf('%03u', strlen($userAuth['email']));
$cookiesave = $emailLen . base64_encode($userAuth['email'] . $userAuth['passhash']);
setcookie('admin', $cookiesave, time() + 60 * 60 * 24 * 30, '/');
}
else
{
setcookie('admin', '' , 0, '/'); // delete cookie
}
}
else
{
setcookie('admin', '' , 0, '/'); // delete cookie if unsuccessful login
echo 'Wrong Email / Password or both';
}
} // end of form login
// if successful login
if ($userAuth['loginSuccess'])
{
echo 'user: ', $userAuth['email'], ' is logged in via: ', $userAuth['loginMethod'];
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Enter Login Details</title>
</head>
<body>
<form name="login" action="/testmysql/Q22459571_cookie_base64.php
" method="post">
<label>
<span>Email:</span>
<input type="text" class="radius" name="email" value="<?php echo $userAuth['email']; ?>" />
</label>
<label>
<span>Password:</span>
<input type="password" class="radius" name="pass" value="" />
</label>
<div class="remember">
<input type="checkbox" id="remember" name="remember" value="1" <?php echo 'checked="checked"' ?> />
<label for="remember">Remember Me!</label>
</div>
<input type="submit" value="Login" name="sendLogin" class="btn" />
</form>
</body>
</html>

Related

Fatal error: Call to a member function real_escape_string() on a non-object

After having converted this code from mysql to mysqli, there appears an error while executing through the login page with the error: Fatal error: Call to a member function real_escape_string() on a non-object in dbc.php on line 127. Unfortunately I can't help myself to correct it....Any help would be highly appreciated.
dbc.php (given below)
<?php
/******************** MAIN SETTINGS - PHP LOGIN SCRIPT V2.1 **********************
Please complete wherever marked xxxxxxxxx
/************* MYSQL DATABASE SETTINGS *****************
1. Specify Database name in $dbname
2. MySQL host (localhost or remotehost)
3. MySQL user name with ALL previleges assigned.
4. MySQL password
Note: If you use cpanel, the name will be like account_database
*************************************************************/
define ("DB_HOST", "89.46.111.48"); // set database host
define ("DB_USER", "Sql1120771"); // set database user
define ("DB_PASS","l226266154"); // set database password
define ("DB_NAME","Sql1120771_3"); // set database name
$link = new mysqli(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
$db = $link->select_db(DB_NAME) or die("Couldn't select database");
/* Registration Type (Automatic or Manual)
1 -> Automatic Registration (Users will receive activation code and they will be automatically approved after clicking activation link)
0 -> Manual Approval (Users will not receive activation code and you will need to approve every user manually)
*/
$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 = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$privatekey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
/**** 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 = $link->query("select `ckey`,`ctime` from `users` where `id` ='$cookie_user_id'") or die($link->error);
list($ckey,$ctime) = $rs_ctime->fetch_row();
// 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_query("select user_level from users where id='$_SESSION[user_id]'")->fetch_row();
$_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 = $link->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($link->real_escape_string($_SESSION['user_id']));
$cook_user_id = strip_tags($link->real_escape_string($_COOKIE['user_id']));
if(isset($sess_user_id) || isset($cook_user_id)) {
$link->query("update `users`
set `ckey`= '', `ctime`= ''
where `id`='$sess_user_id' OR `id` = '$cook_user_id'") or die($link->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 ;
}
}
?>
LOGIN PAGE
<?php
***********************************************************/
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 = $mysqli->query("SELECT `id`,`pwd`,`full_name`,`approved`,`user_level` FROM users WHERE
$user_cond
AND `banned` = '0'
") or die ($mysqli->error);
$num = $result->num_rows;
// Match row found with more than 1 results - the user is authenticated.
if ( $num > 0 ) {
list($id,$pwd,$full_name,$approved,$user_level) = $result->fetch_row();
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();
$mysqli->query("update users set `ctime`='$stamp', `ckey` = '$ckey' where id='$id'") or die($mysqli->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";
}
}
?>
<html>
<head>
<title>Members Login</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<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>
<link href="styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="5" class="main">
<tr>
<td colspan="3"> </td>
</tr>
<tr>
<td width="160" valign="top"><p> </p>
<p> </p>
<p> </p>
<p> </p>
<p> </p></td>
<td width="732" valign="top"><p> </p>
<h3 class="titlehdr">Login Users
</h3>
<p>
<?php
/******************** ERROR MESSAGES*************************************************
This code is to show error messages
**************************************************************************/
if(!empty($err)) {
echo "<div class=\"msg\">";
foreach ($err as $e) {
echo "$e <br>";
}
echo "</div>";
}
/******************************* END ********************************/
?></p>
<form action="login.php" method="post" name="logForm" id="logForm" >
<table width="65%" border="0" cellpadding="4" cellspacing="4" class="loginform">
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<td width="28%">Username / Email</td>
<td width="72%"><input name="usr_email" type="text" class="required" id="txtbox" size="25"></td>
</tr>
<tr>
<td>Password</td>
<td><input name="pwd" type="password" class="required password" id="txtbox" size="25"></td>
</tr>
<tr>
<td colspan="2"><div align="center">
<input name="remember" type="checkbox" id="remember" value="1">
Remember me</div></td>
</tr>
<tr>
<td colspan="2"> <div align="center">
<p>
<input name="doLogin" type="submit" id="doLogin3" value="Login">
</p>
<p>Register Free<font color="#FF6600">
|</font> Forgot Password <font color="#FF6600">
</font></p>
<p><span style="font: normal 9px verdana">Powered by <a href="http://php-login-script.com">PHP
Login Script v2.3</a></span></p>
</div></td>
</tr>
</table>
<div align="center"></div>
<p align="center"> </p>
</form>
<p> </p>
</td>
<td width="196" valign="top"> </td>
</tr>
<tr>
<td colspan="3"> </td>
</tr>
</table>
</body>
</html>
Your $link variable is not being passed into your functions, so you need to take a look at variable scoping. So you need to pass $link into your functions, e.g. function filter($link, $data) { and then calling it like $cookie_user_id = filter($link, $_COOKIE['user_id']);. Same thing with the logout() function and any other functions using $link.
You're using
global $db;
in some of your database functions. But earlier in the code, you did this:
$link = new mysqli(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
$db = $link->select_db(DB_NAME) or die("Couldn't select database");
select_db() returns a boolean. $link is your database connection, not $db.
The filter() function uses $link but does not declare it as global or accept it as an argument. You should not use that function, though. You should be using prepared statements rather than escaping strings and using them directly in queries like this:
"select `ckey`,`ctime` from `users` where `id` ='$cookie_user_id'"
You can check out How can I prevent SQL injection in PHP? for more information on that.

PHP code being reported as malware

I have been working on a website on a localhost and have just tried to upload it to a free webserver so I can get some testers, for some reason my code is being reported as malware and is being blocked by my antivirus, this means I can't see anything when visiting it apart from the ERR_CONNECTION_RESET. Have you guys got any ideas as to why this code is being detected as malware?
LOGIN.php
<?php
include('classes/db.php');
if (db::maintenance()) {
die('This site is currently going under maintenance, please check back again shortly.');
}
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (db::query('SELECT username FROM users WHERE username=:username', array(':username'=>$username))) {
if (password_verify($password, db::query('SELECT password FROM users WHERE username=:username', array(':username'=>$username))[0]['password'])) {
echo "Logged in!";
$cstrong = True;
$token = bin2hex(openssl_random_pseudo_bytes(64, $cstrong));
$user_id = db::query('SELECT id FROM users WHERE username=:username', array(':username'=>$username))[0]['id'];
db::query('INSERT INTO login_tokens VALUES (NULL, :token, :user_id)', array(':token'=>sha1($token), ':user_id'=>$user_id));
setcookie("SNID", $token, time() + 60 * 60 * 24 * 7, '/', NULL, NULL, TRUE);
setcookie('SNID_', '1', time() + 60 + 60 * 24 * 3, '/', NULL, NULL, TRUE);
header('Location: index.php');
} else {
echo "Incorrect password";
}
} else {
echo "User not registered!";
}
}
?>
<h1>Login to your account</h1>
<form action="login.php" method="post">
<input type="text" name="username" value="" placeholder="Username"><p />
<input type="password" name="password" value="" placeholder="Password"><p />
<input type="submit" name="submit" placeholder="Login"><p />
</form>
DB.php
(I have changed the connection to false data, and changed it to the correct data when uploading it to the host.)
<?php
class db {
private static function connect () {
$conn = new PDO('mysql:host=localhost;dbname=users;,charset=utf8', 'root', '');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
}
public static function query ($sql, $params = array()) {
$statement = self::connect()->prepare($sql);
$statement->execute($params);
if (explode(' ', $sql)[0] == 'SELECT') {
$result = $statement->fetchAll();
return $result;
}
}
public static function notify ($userid) {
$notifications = db::query('SELECT forum_members.forum_id, notifications.user_id, notifications.post_id, notifications.forum_id, notifications.post_body, notifications.creation, notifications.type FROM forum_members, notifications WHERE (notifications.forum_id=forum_members.forum_id OR notifications.forum_id=0) AND notifications.user_id=forum_members.user_id ORDER BY notifications.post_id DESC');
return $notifications;
}
public static function maintenance () {
return false;
}
}
?>
Which type of address do you use to enter the website? PHP source doesn't display to browsers, so PHP isn't the problem.
If you enter in with a hostname (Ex. .....2cc.brad....net) Then it'll automatically get detected as a "malware" for beginner safety, if ur accessing it from localhost/127.0.0.1 it should be fine, but if ur accessing it from a host that's marked as malware, than yep.

$_POST isn't getting values from the form

$_POST is not getting any values and i have tried a lot of procedure already mentioned on stack overflow but they are not working for me. I have tried printing the $_POST it is empty. i need some suggestions on it..please help
It was previously working when it was in mysql database but i tried to change the database to sqlserver and now its not working but i am not understanding i have not made any changes to this particular code and i have seen this also that it is not being affected by some other file.
there is no mistake in empty condition i wrote it myself to check whether it was empty or not and it was always showing empty whether i submit data or not
i am attaching some codes which are related to this.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<?php
ob_start();
session_start();
require_once 'config.php';
?>
<?php
if(empty($_POST)){
echo "hello";
try {
$user_obj = new Cl_User();
$data = $user_obj->registration( $_POST );
if($data){
$_SESSION['success'] = USER_REGISTRATION_SUCCESS;
header('Location: index.php');exit;
}
} catch (Exception $e) {
$_SESSION['error'] = $e->getMessage();
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="php quiz script, php quiz code, php quiz application, quiz php code, php quiz system, online quiz using php, quiz using php, how to make quiz in php, quiz system in php, php programming quiz, online quiz using php and sqlsrv, create online quiz using php and sqlsrv, create quiz using php sqlsrv, php quiz script free">
<meta name="keywords" content="php quiz script, php quiz code, php quiz application, quiz php code, php quiz system, online quiz using php, quiz using php, how to make quiz in php, quiz system in php, php programming quiz, online quiz using php and sqlsrv, create online quiz using php and sqlsrv, create quiz using php sqlsrv, php quiz script free">
<title>PHP Quiz Script</title>
<link href='http://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/font-awesome.min.css" rel="stylesheet">
<link href="css/login.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="js/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="login-form">
<?php require_once 'templates/message.php';?>
<h1 class="text-center">PHP Quiz Application</h1>
<div class="form-header">
<i class="fa fa-user"></i>
</div>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="form-register" role="form" id="register-form">
<div>
<input name="name" id="name" type="text" class="form-control" placeholder="Name">
<span class="help-block"></span>
</div>
<div>
<input name="email" id="email" type="email" class="form-control" placeholder="Email address" >
<span class="help-block"></span>
</div>
<div>
<input name="password" id="password" type="password" class="form-control" placeholder="Password">
<span class="help-block"></span>
</div>
<div>
<input name="confirm_password" id="confirm_password" type="password" class="form-control" placeholder="Confirm Password">
<span class="help-block"></span>
</div>
<button class="btn btn-block bt-login" type="submit" id="submit" name="submit">Sign Up</button>
</form>
<div class="form-footer">
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<i class="fa fa-lock"></i>
Forgot password?
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<i class="fa fa-check"></i>
Sign In
</div>
</div>
</div>
</div>
</div>
<!-- /container -->
<script src="js/jquery.validate.min.js"></script>
<script src="js/register.js"></script>
</body>
</html>
<?php unset($_SESSION['success'] ); unset($_SESSION['error']); ?>
<?php
$server="NIKUNJ";
$ci = array("Database" => "My database","UID"=>"sa", "PWD"=>"sql#123","Characterset"=>"UTF-8") or die( "check db connect1" );
$conn = sqlsrv_connect($server,$ci) or die ( "check db connect2" ) ;
function mssql_escape($str)
{
if(get_magic_quotes_gpc())
{
$str= stripslashes($str);
}
return str_replace("'", "''", $str);
}
function mssql_insert_id() {
$id = 0;
$res = sqlsrv_query("SELECT ##identity AS id");
if ($row = sqlsrv_fetch_array($res, MSSQL_ASSOC)) {
$id = $row["id"];
}
return $id;
}
class Cl_User
{
/**
* #var will going contain database connection
*/
protected $_con;
/**
* it will initalize DBclass
*/
public function __construct()
{
$db = new Cl_DBclass();
$this->_con = $db->con;
}
/**
* this will handles user registration process
* #param array $data
* #return boolean true or false based success
*/
public function registration( array $data )
{
echo "hello";
if( !empty( $data ) ){
// Trim all the incoming data:
$trimmed_data = array_map('trim', $data);
// escape variables for security
$name = mssql_escape( $trimmed_data['name'] );
$password = mssql_escape( $trimmed_data['password'] );
$cpassword = mssql_escape( $trimmed_data['confirm_password'] );
// Check for an email address:
if (filter_var( $trimmed_data['email'], FILTER_VALIDATE_EMAIL)) {
$email = mssql_escape( $trimmed_data['email']);
} else {
throw new Exception( "Please enter a valid email address!" );
}
if((!$name) || (!$email) || (!$password) || (!$cpassword) ) {
throw new Exception( FIELDS_MISSING );
}
if ($password !== $cpassword) {
throw new Exception( PASSWORD_NOT_MATCH );
}
$password = md5( $password );
$query = "INSERT INTO users (id, name, email, password, created) VALUES (NULL, '$name', '$email', '$password', CURRENT_TIMESTAMP)";
if(sqlsrv_query($this->_con, $query)){
sqlsrv_close($this->_con);
return true;
};
} else{
throw new Exception( USER_REGISTRATION_FAIL );
}
}
/**
* This method will handle user login process
* #param array $data
* #return boolean true or false based on success or failure
*/
public function login( array $data )
{
$_SESSION['logged_in'] = false;
if( !empty( $data ) ){
// Trim all the incoming data:
$trimmed_data = array_map('trim', $data);
// escape variables for security
$email = mssql_escape( $this->_con, $trimmed_data['email'] );
$password = mssql_escape( $this->_con, $trimmed_data['password'] );
if((!$email) || (!$password) ) {
throw new Exception( LOGIN_FIELDS_MISSING );
}
$password = md5( $password );
$query = "SELECT id, name, email, created FROM users where email = '$email' and password = '$password' ";
$result = sqlsrv_query($this->_con, $query);
$data = sqlsrv_fetch_array($result,SQLSRV_FETCH_ASSOC);
$count = SQLSRV_num_rows($result);
echo $count;
sqlsrv_close($this->_con);
if( $count == 1){
$_SESSION = $data;
$_SESSION['logged_in'] = true;
return true;
}else{
throw new Exception( LOGIN_FAIL );
}
} else{
throw new Exception( LOGIN_FIELDS_MISSING );
}
}
/**
* This will shows account information and handles password change
* #param array $data
* #throws Exception
* #return boolean
*/
public function account( array $data )
{
if( !empty( $data ) ){
// Trim all the incoming data:
$trimmed_data = array_map('trim', $data);
// escape variables for security
$password = mssql_escape( $this->_con, $trimmed_data['password'] );
$cpassword = $trimmed_data['confirm_password'];
$user_id = $_SESSION['id'];
if((!$password) || (!$cpassword) ) {
throw new Exception( FIELDS_MISSING );
}
if ($password !== $cpassword) {
throw new Exception( PASSWORD_NOT_MATCH );
}
$password = md5( $password );
$query = "UPDATE users SET password = '$password' WHERE id = '$user_id'";
if(sqlsrv_query($this->_con, $query)){
sqlsrv_close($this->_con);
return true;
}
} else{
throw new Exception( FIELDS_MISSING );
}
}
/**
* This handle sign out process
*/
public function logout()
{
session_unset();
session_destroy();
session_start();
$_SESSION['success'] = LOGOUT_SUCCESS;
header('Location: index.php');
}
/**
* This reset the current password and send new password to mail
* #param array $data
* #throws Exception
* #return boolean
*/
public function forgetPassword( array $data )
{
if( !empty( $data ) ){
// escape variables for security
$email = mssql_escape( $this->_con, trim( $data['email'] ) );
if((!$email) ) {
throw new Exception( FIELDS_MISSING );
}
$password = $this->randomPassword();
$password1 = md5( $password );
$query = "UPDATE users SET password = '$password1' WHERE email = '$email'";
if(sqlsrv_query($this->_con, $query)){
sqlsrv_close($this->_con);
$to = $email;
$subject = "New Password Request";
$txt = "Your New Password ".$password;
$headers = "From: rahul.ranjan72#hotmail.com" . "\r\n" .
"CC:rahul.ranjan72#hotmail.com";
mail($to,$subject,$txt,$headers);
return true;
}
} else{
throw new Exception( FIELDS_MISSING );
}
}
/**
* This will generate random password
* #return string
*/
private function randomPassword()
{
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
for ($i = 0; $i < 8; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
return implode($pass); //turn the array into a string
}
public function pr($data = '' )
{
echo "<pre>"; print_r($data); echo "</pre>";
}
public function getCategory()
{
$query = "SELECT * FROM categories";
$results = sqlsrv_query($conn, $query) or die(SQLSRV_errors());
$categories = array();
while ( $result = sqlsrv_fetch_array($result,SQLSRV_FETCH_ASSOC) ) {
echo $result['id'];
$categories[$result['id']] = $result['category_name'];
}
return $categories;
}
public function getQuestions(array $data)
{
if( !empty( $data ) ){
// escape variables for security
$category_id = mssql_escape( $this->_con, trim( $data['category'] ) );
if((!$category_id) ) {
throw new Exception( FIELDS_MISSING );
}
$user_id = $_SESSION['id'];
$query = "INSERT INTO scores ( user_id,right_answer,category_id)VALUES ( '$user_id',0,'$category_id')";
sqlsrv_query( $this->_con, $query);
$_SESSION['score_id'] = mssql_insert_id();
$results = array();
$number_question = $_POST['num_questions'];
$total_question = $_POST['total_num_questions'];
$row = sqlsrv_query( $this->_con, "select * from questions where category_id=$category_id ORDER BY RAND()");
$check=SQLSRV_num_rows($row);
if($check<$total_question)
$rowcount=$check;
else
$rowcount = $total_question;
$remainder = $rowcount/$number_question;
$results['number_question'] = $number_question;
$results['remainder'] = $remainder;
$results['rowcount'] = $rowcount;
while ( $result = SQLSRV_FETCH_ASSOC($row) ) {
$results['questions'][] = $result;
}
sqlsrv_close($this->_con);
return $results;
} else{
throw new Exception( FIELDS_MISSING );
}
}
public function getAnswers(array $data)
{
if( !empty( $data ) ){
$right_answer=0;
$wrong_answer=0;
$unanswered=0;
$total_question = $_POST['total_num_questions'];
$keys=array_keys($data);
$order=join(",",$keys);
$query = "select id,answer from questions where id IN($order) ORDER BY FIELD(id,$order)";
$response=sqlsrv_query( $this->_con, $query) or die(SQLSRV_errors());
$user_id = $_SESSION['id'];
$score_id = $_SESSION['score_id'];
while($result=sqlsrv_fetch_array($response)){
if($result['answer']==$_POST[$result['id']]){
$right_answer++;
}else if($data[$result['id']]=='smart_quiz'){
$unanswered++;
}
else{
$wrong_answer++;
}
}
$results = array();
$results['right_answer'] = $right_answer;
$results['wrong_answer'] = $wrong_answer;
$results['unanswered'] = $unanswered;
$update_query = "update scores set right_answer='$right_answer', wrong_answer = '$wrong_answer', unanswered = '$unanswered' where user_id='$user_id' and id ='$score_id' ";
sqlsrv_query( $this->_con, $update_query) or die(SQLSRV_errors());
sqlsrv_close($this->_con);
return $results;
}
}
}
<?php
/**
#author vetripandi
#copyright http:www.vetbossel.in
*/
require_once 'messages.php';
//site specific configuration declartion
define( 'DB_HOST', 'NIKUNJ' );
define( 'DB_USERNAME', 'sa');
define( 'DB_PASSWORD', 'sql#123');
define( 'DB_NAME', 'user_login');
function __autoload($class)
{
$parts = explode('_', $class);
$path = implode(DIRECTORY_SEPARATOR,$parts);
require_once $path . '.php';
}
its the image of the data i am sending but $_POST is not getting any values and nothing happens after signup button is pressed
Your code is only running if the $_POST array is empty.
Change your code to the following.
if(!empty($_POST))
Other than that, I see no problems.
It's better practice to take the submit button as a centre of attention for the execution of the server side coding executing.
Therefore check if the $_POST data has been sent using isset:
if (isset($_POST['submit']))
{
// the data has successfully been sent
}
are you sure is's ok ?
if(empty($_POST))
you always execute code in if if $_POST is empty
if(!empty($_POST))
execute when $_POST NOT empty
This may not be your problem, but generally the submit button is
<input type="submit" value="submit">
rather than
<button type="submit">Submit</button>
From: W3schools.com
I got my mistake. I dont know how but the value of the forms were not only transferred to this php file but also in another php file names check-email.php which was part of my project which was not mentioned anywhere in register.php.
I got to know the problem by seeing some post related to this kind of problem on stack overflow where he said to check you PHP_error_log and Apache error log. The error was clearly stated there. By doing some changes to check-email.php it is working fine now. Thank you everybody for your help anyway

Registration page using PHP/MySQL not storing user values to database

I am developing a website with User registration and login ,after completing the page configuration ,i tried to register it worked perfectly and later next day i tried to register but the page is not loading ,after filling in the data and if i click submit ,it reloads the same register page with no effect ,how to solve this problem
SQL Query Processing code:
<?php
class User
{
public $user_active = 0;
private $clean_email;
public $status = false;
private $clean_password;
private $clean_username;
private $unclean_username;
public $sql_failure = false;
public $mail_failure = false;
public $email_taken = false;
public $username_taken = false;
public $activation_token = 0;
function __construct($user, $pass, $email)
{
// Used for display only
$this->unclean_username = $user;
// Sanitize
$this->clean_email = sanitize($email);
$this->clean_password = trim($pass);
$this->clean_username = sanitize($user);
if (usernameExists($this->clean_username)) {
$this->username_taken = true;
}
else if (emailExists($this->clean_email)) {
$this->email_taken = true;
}
else {
// No problems have been found.
$this->status = true;
}
}
public function userPieAddUser()
{
global $db, $emailActivation, $websiteUrl, $db_table_prefix;
// Prevent this function being called if there were construction errors
if ($this->status) {
// Construct a secure hash for the plain text password
$secure_pass = generateHash($this->clean_password);
// Construct a unique activation token
$this->activation_token = generateactivationtoken();
// Do we need to send out an activation email?
if ($emailActivation) {
// User must activate their account first
$this->user_active = 0;
$mail = new userPieMail();
// Build the activation message
$activation_message = lang("ACTIVATION_MESSAGE", array(
"{$websiteUrl}/",
$this->activation_token
));
// Define more if you want to build larger structures
$hooks = array(
"searchStrs" => array(
"#ACTIVATION-MESSAGE",
"#ACTIVATION-KEY",
"#USERNAME#"
) ,
"subjectStrs" => array(
$activation_message,
$this->activation_token,
$this->unclean_username
)
);
/* Build the template - Optional, you can just use the sendMail function
Instead to pass a message. */
if (!$mail->newTemplateMsg("new-registration.txt", $hooks)) {
$this->mail_failure = true;
}
else {
// Send the mail. Specify users email here and subject.
// SendMail can have a third parementer for message if you do not wish to build a template.
if (!$mail->sendMail($this->clean_email, "New User")) {
$this->mail_failure = true;
}
}
}
else {
// Instant account activation
$this->user_active = 1;
}
if (!$this->mail_failure) {
// Insert the user into the database providing no errors have been found.
$sql = "INSERT INTO `" . $db_table_prefix . "users` (
`username`,
`username_clean`,
`password`,
`email`,
`activationtoken`,
`last_activation_request`,
`LostpasswordRequest`,
`active`,
`group_id`,
`sign_up_date`,
`last_sign_in`
)
VALUES (
'" . $db->sql_escape($this->unclean_username) . "',
'" . $db->sql_escape($this->clean_username) . "',
'" . $secure_pass . "',
'" . $db->sql_escape($this->clean_email) . "',
'" . $this->activation_token . "',
'" . time() . "',
'0',
'" . $this->user_active . "',
'1',
'" . time() . "',
'0'
)";
return $db->sql_query($sql);
}
}
}
}
?>
Config.php file for Register Processing
<?php
if (is_dir("install/")) {
header("Location: install/");
die();
}
require_once ("settings.php");
// Dbal Support - Thanks phpBB ; )
require_once ("db/" . $dbtype . ".php");
// Construct a db instance
$db = new $sql_db();
if (is_array($db->sql_connect($db_host, $db_user, $db_pass, $db_name, $db_port, false, false))) {
die("Unable to connect to the database");
}
if (!isset($language)) $langauge = "en";
require_once ("lang/" . $langauge . ".php");
require_once ("class.user.php");
require_once ("class.mail.php");
require_once ("funcs.user.php");
require_once ("funcs.general.php");
require_once ("class.newuser.php");
session_start();
// Global User Object Var
// loggedInUser can be used globally if constructed
if (isset($_SESSION["userPieUser"]) && is_object($_SESSION["userPieUser"])) $loggedInUser = $_SESSION["userPieUser"];
else if (isset($_COOKIE["userPieUser"])) {
$db->sql_query("SELECT session_data FROM " . $db_table_prefix . "sessions WHERE session_id = '" . $_COOKIE['userPieUser'] . "'");
$dbRes = $db->sql_fetchrowset();
if (empty($dbRes)) {
$loggedInUser = NULL;
setcookie("userPieUser", "", -parseLength($remember_me_length));
}
else {
$obj = $dbRes[0];
$loggedInUser = unserialize($obj["session_data"]);
}
}
else {
$db->sql_query("DELETE FROM " . $db_table_prefix . "sessions WHERE " . time() . " >= (session_start+" . parseLength($remember_me_length) . ")");
$loggedInUser = NULL;
}
?>
Register Page PHP Code
<?php
require_once ("models/config.php");
// Prevent the user visiting the logged in page if he/she is already logged in
if (isUserLoggedIn()) {
header("Location: index.php");
die();
}
/*
Below is a very simple example of how to process a new user.
Some simple validation (ideally more is needed).
The first goal is to check for empty / null data, to reduce workload here we let the user class perform it's own internal checks, just in case they are missed.
*/
// Forms posted
if (!empty($_POST)) {
$errors = array();
$email = trim($_POST["email"]);
$username = trim($_POST["username"]);
$password = trim($_POST["password"]);
$confirm_pass = trim($_POST["passwordc"]);
// Perform some validation
// Feel free to edit / change as required
if (minMaxRange(5, 25, $username)) {
$errors[] = lang("ACCOUNT_USER_CHAR_LIMIT", array(
5,
25
));
}
if (minMaxRange(8, 50, $password) && minMaxRange(8, 50, $confirm_pass)) {
$errors[] = lang("ACCOUNT_PASS_CHAR_LIMIT", array(
8,
50
));
}
else if ($password != $confirm_pass) {
$errors[] = lang("ACCOUNT_PASS_MISMATCH");
}
if (!isValidemail($email)) {
$errors[] = lang("ACCOUNT_INVALID_EMAIL");
}
// End data validation
if (count($errors) == 0) {
// Construct a user object
$user = new User($username, $password, $email);
// Checking this flag tells us whether there were any errors such as possible data duplication occured
if (!$user->status) {
if ($user->username_taken) $errors[] = lang("ACCOUNT_USERNAME_IN_USE", array(
$username
));
if ($user->email_taken) $errors[] = lang("ACCOUNT_EMAIL_IN_USE", array(
$email
));
}
else {
// Attempt to add the user to the database, carry out finishing tasks like emailing the user (if required)
if (!$user->userPieAddUser()) {
if ($user->mail_failure) $errors[] = lang("MAIL_ERROR");
if ($user->sql_failure) $errors[] = lang("SQL_ERROR");
}
}
}
if (count($errors) == 0) {
if ($emailActivation) {
$message = lang("ACCOUNT_REGISTRATION_COMPLETE_TYPE2");
}
else {
$message = lang("ACCOUNT_REGISTRATION_COMPLETE_TYPE1");
}
}
}
?>
HTML Register Form
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>
Registration |
<?php echo $websiteName; ?>
</title>
<?php require_once("head_inc.php"); ?>
</head>
<body>
<div class="modal-ish">
<div class="modal-header">
<h2>
Sign Up
</h2>
</div>
<div class="modal-body">
<div id="success">
<p>
<?php echo $message ?>
</p>
</div>
<div id="regbox">
<form name="newUser" action="
<?php echo $_SERVER['PHP_SELF'] ?>
" method="post">
<p>
<label>
Username:
</label>
<input type="text" name="username" />
</p>
<p>
<label>
Password:
</label>
<input type="password" name="password" />
</p>
<p>
<label>
Re-type Password:
</label>
<input type="password" name="passwordc" />
</p>
<p>
<label>
Email:
</label>
<input type="text" name="email" />
</p>
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary" name="new" id="newfeedform" value="Register" />
</div>
</form>
</div>
<div class="clear">
</div>
<p style="margin-top:30px; text-align:center;">
<a href="login.php">
Login
</a>
/
<a href="forgot-password.php">
Forgot Password?
</a>
/
<a href="
<?php echo $websiteUrl; ?>
">
Home Page
</a>
</p>
</body>
</html>
In your html file remove the action attribute of tag form or use action = "". Donot use $_SERVER[PHP_SELF] as it is prone to extra scripts being run from your page.
Other than that, will check the code. Try using echo or print_r wherever possible to check what part is causing problem. Use try-catch for checking if the db returns errors in SQL.

PHP session variable clearing unexpectedly, db value check empty despite obvious match

I have been struggling with this one for hours and hours and just cannot figure out what I'm missing.
I'm trying to build a cookie-less login form that also has no information in session variables that would harm the app if an attacker would be able to modify them.
All of my pages have the below code included.
I have 2 issues:
Every time I click on another page it acts like $_SESSION['token'] was empty and goes to the login page like if it was the first visit.
It returns $tokenid and $tokentype empty however I'm calling them both every time a page is loading (aiming to avoid having to put them into a session variable).
This is my current code:
<?php
define('TIMEOUTMIN', 15);
define('LOCKOUTMIN', 10);
define('LOCKOUTNUM', 3);
include("includes/pp/pbkdf2.php"); // this is basically calling the validate_password function
include ("includes/vars/vars_dbconn.php"); // this contains the db data and $pdo
$userid = $_POST['userid'];
$userpw = $_POST['password'];
$deltoq = "UPDATE LoginUser SET token = ?, online = ? WHERE online < ?";
$prepdeltoq = $pdo->prepare($deltoq);
$prepdeltoq->execute(array(NULL,NULL,time()));
$loginq = "SELECT * FROM LoginUser WHERE ID = ?";
$preplq = $pdo->prepare($loginq);
$preplq->execute(array($userid));
$getuser = $preplq->fetch(PDO::FETCH_ASSOC);
$dbid = $getuser['ID'];
$dbpass = $getuser['hash'];
$dbbp = $getuser['bp'];
$dbltime = $getuser['ltimeout'];
$logintoq = "SELECT * FROM LoginUser WHERE token = ?";
$prepltq = $pdo->prepare($logintoq);
$prepltq->execute(array($_SESSION['token']));
$getoken = $prepltq->fetch(PDO::FETCH_ASSOC);
$tokenid = $getoken['ID'];
$tokentype = $getoken['type'];
$totoken = $getoken['token'];
$prolonglock = $pdo->prepare("UPDATE LoginUser SET ltimeout = ? WHERE ID = ?");
$addbp = $pdo->prepare("UPDATE LoginUser SET bp = ? WHERE ID = ?");
$loginwhen = $pdo->prepare("UPDATE LoginUser SET lastlogin = ? WHERE ID = ?");
$loginlogq = $pdo->prepare("INSERT INTO LoginUserLog (ID, action)
VALUES(:ID, :action)");
$logintokenid = $pdo->prepare("UPDATE LoginUser SET token = ? WHERE ID = ?");
$loginonid = $pdo->prepare("UPDATE LoginUser SET online = ? WHERE ID = ?");
$loginontok = $pdo->prepare("UPDATE LoginUser SET online = ? WHERE token = ?");
if(!function_exists('LoginUser')) {
function LoginUser($pwmessage) {
if (session_name() <> 'MyWebApp') session_name('WesoftskyLogin');
if (!session_id()) session_start();
$_SESSION['token'] = '';
include ("includes/header.php"); ?>
<meta name="description" content="Login - MyWebApp"/>
<title>Login - MyWebApp</title>
<script type="text/javascript">
event.keyCode == '';
function enterTab() {
if (event.keyCode == 13) {
var passInput = document.getElementById("password");
passInput.focus();
}
}
</script>
</head>
<body onkeyup="enterTab()">
<div id="homewrap">
<div id="hometitle">MyWebApp</div>
</div>
<div id="id_formwrap">
<form action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING']); ?>" method="post">
<?php if (empty($pwmessage)) echo '<div>Please enter your login details</div>'; else echo '<div style="color:red">'.$pwmessage.'</div>'; ?><br />
Login ID<br />
<input type="text" name="userid" id="id" onKeyPress="return noenter(event)" /><br /><br />
<script>document.getElementById("id").focus()</script>
Password<br />
<input type="password" name="password" id="password" /><br /><br />
<input type="submit" name="login" id="Submit" value="Login" />
</form>
</div>
</body>
</html>
<?php exit();
}
}
if(!function_exists('ProlongTime')) {
function ProlongTime() {
global $userid;
global $logintokenid;
global $loginonid;
global $loginontok;
$timeoutodb = (time () + TIMEOUTMIN*60);
if (!empty($userid)) {
$_SESSION['token'] = bin2hex(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM));
$logintokenid->execute(array($_SESSION['token'], $userid));
$loginonid->execute(array($timeoutodb, $userid));
} else {
$loginontok->execute(array($timeoutodb, $_SESSION['token']));
}
}
}
if ($dbltime > time()) {
$lockcheck = time() + LOCKOUTMIN*60;
$prolonglock->execute(array($lockcheck,$userid));
LoginUser('Your account is currently locked');
}
if(isset($_POST['logout'])) {
$action = "Logged OUT";
$loginlogq->execute(array(':ID' => $tokenid, ':action' => $action));
LoginUser('Logged out');
}
if (isset($_POST['login'])) {
if ($dbid AND validate_password($userpw, $dbpass)) { // Good login info
//session_regenerate_id(true);
$action = "Logged IN";
$loginlogq->execute(array(':ID' => $userid, ':action' => $action));
$loginwhen->execute(array(time(), $userid));
$addbp->execute(array(NULL, $userid));
ProlongTime();
} else { // Bad login info
if ($dbbp >= LOCKOUTNUM-1) {
$lockbp = time() + LOCKOUTMIN*60;
$prolonglock->execute(array($lockbp,$userid));
$action = "Locked (wrong password)";
$loginlogq->execute(array(':ID' => $userid, ':action' => $action));
LoginUser('Your account has been locked');
}
$addbp->execute(array($dbbp+1, $userid));
$action = "Failed login";
$loginlogq->execute(array(':ID' => $userid, ':action' => $action));
LoginUser('Username or password is incorrect');
}
} elseif (empty($_SESSION['token'])) { // Loading the page first time (new session)
LoginUser('');
} elseif ($_SESSION['token'] <> $totoken) { // Session timeout
$action = "Logged OUT (expired)";
$loginlogq->execute(array(':ID' => $tokenid, ':action' => $action));
echo 'tokenid: '.$tokenid;
} else ProlongTime(); // While using the app and still within time
$pdo = null;
?>
You need to put
session_start()
in the starting of the page.

Categories