Basically I have the following website which allows account customers to login to the website by filling in the appropriate details:here
I have created a seperate login page which is identical with the login values already filled in: here
and I have basically added in the following code:
$(document).ready(function(){
$('#btn-login').click();
});
This is so it automatically logs in as a guest when you go to the second link. Although it works okay, when you logout as a guest and try to log back in via the second link it redirects to the first link (login.php) and I can't understand why since all the second link is doing is submitting the correct values.
Is there a better way of doing this or is there a way of preventing this from happening?
If I remove the redirect, if you logout then try to go to the automatic login link, it takes you to the page and has all the details filled in but it doesn't log you in automatically.
Any help would be much appreciated.
See below code for the login (session-controller.php)
<?php
require_once("controllers/server.filter.php");
require_once('models/server.php');
require_once("models/useraccount.php");
require_once("models/sql.php");
class SessionController {
private static $login_status;
private static $redirect_url;
public static $form_action;
## Getters ##
private static function get_loginstatus() {return self::$login_status;}
## Setters ##
private static function set_loginstatus($in_str) {self::$login_status = $in_str;}
## Functions ##
public static function validate_user() {
UserAccount::set_username($_REQUEST['txt-username']);
UserAccount::set_password($_REQUEST['txt-password']);
$pdo = new SQL();
$dbh = $pdo->connect(Database::$serverIP, Database::$serverPort, Database::$dbName, Database::$user, Database::$pass);
try {
// Does user exist?
$query = "SELECT COUNT(UserName) FROM tblusers WHERE UserName = :in_username";
$stmt = $dbh->prepare($query);
$param = Filter::san_str_html(UserAccount::get_username());
$stmt->bindParam(':in_username', $param, PDO::PARAM_STR);
$stmt->execute();
$number_of_rows = $stmt->fetchColumn();
$stmt->closeCursor();
if ($number_of_rows <= 0) {
self::set_loginstatus("The user does not exist in our database, please try again.");
$_SESSION['login-status'] = self::get_loginstatus();
self::redirect(false);
} else {
// User verified, check password...
self::verify_password();
}
}
catch (PDOException $pe) {
die("Error: " .$pe->getMessage());
}
$pdo = null;
}
private static function verify_password() {
$pdo = new SQL();
$dbh = $pdo->connect(Database::$serverIP, Database::$serverPort, Database::$dbName, Database::$user, Database::$pass);
try {
// Does the password given match the password held?
$query = "SELECT COUNT(*) FROM tblusers WHERE UserName = :in_username AND Password = :in_password";
$stmt = $dbh->prepare($query);
$param1 = UserAccount::get_password();
$param2 = Filter::san_str_html(UserAccount::get_username());
$stmt->bindParam(':in_username', $param2, PDO::PARAM_STR);
$stmt->bindParam(':in_password', $param1, PDO::PARAM_STR);
$stmt->execute();
$number_of_rows = $stmt->fetchColumn();
}
catch (PDOException $pe) {
die("Error: " .$pe->getMessage());
}
$pdo = null;
if ($number_of_rows == 1) {
$_SESSION['username'] = UserAccount::get_username();
// Begin verification..
self::set_useraccount(true);
} else {
self::set_loginstatus("Verification failed! Password incorrect, please try again.");
$_SESSION['login-status'] = self::get_loginstatus();
self::redirect(false);
}
}
private static function verify_account() {
// Account types: 9 = Disabled, 0 = Normal/Restricted, 1 = Administrative
if (UserAccount::get_accounttype() == 9) {
self::set_loginstatus("Verification failed! This account has been disabled."); ## Account disabled
$_SESSION['login-status'] = self::get_loginstatus();
self::redirect(false);
} else
// User login types: 9 = Disabled, 0 = Normal/Restricted, 1 = Administrative
if (UserAccount::get_usertype() == 9) {
self::set_loginstatus("Verification failed! This login has been disabled."); ## User login disabled
$_SESSION['login-status'] = self::get_loginstatus();
self::redirect(false);
} else {
// Set redirect url here
if (UserAccount::get_accounttype() == 1) {
self::$redirect_url = 'controlpanel.php';
}
if (UserAccount::get_accounttype() == 0 && UserAccount::get_usertype() == 1) {
self::$redirect_url = 'controlpanel.php';
}
if (UserAccount::get_accounttype() == 0 && UserAccount::get_usertype() == 0) {
self::$redirect_url = 'newbooking.php';
}
// All ok, set user and account properties
return true;
}
}
public static function set_useraccount($redirect_bool) {
// If username session is set...
if (isset($_SESSION['username'])) {
UserAccount::set_username($_SESSION['username']);
// Query Database for the rest of the data
$pdo = new SQL();
$dbh = $pdo->connect(Database::$serverIP, Database::$serverPort, Database::$dbName, Database::$user, Database::$pass);
try {
$query = "SELECT AccountName
FROM tblusers
WHERE UserName = :in_username";
$stmt = $dbh->prepare($query);
$param1 = UserAccount::get_username();
$stmt->bindParam(':in_username', $param1, PDO::PARAM_STR);
$stmt->execute();
// Parse
$row = $stmt->fetch(PDO::FETCH_BOTH);
$stmt->closeCursor();
}
catch (PDOException $pe) {
die("Error: " .$pe->getMessage());
}
UserAccount::set_accountname($row['AccountName']);
try {
$query = "SELECT a.Id, a.AccountName, a.AccountNumber, a.AccountEmail, a.AccountTel,
a.AccountContact, a.AccountType, a.PaymentType, u.UserName,
u.FullName, u.UserEmail, u.UserTel, u.UserType
FROM tblaccounts a JOIN tblusers u
ON a.AccountName = u.AccountName
WHERE a.AccountName = :in_accname
AND u.UserName = :in_username";
$stmt = $dbh->prepare($query);
$param2 = UserAccount::get_accountname();
$param3 = UserAccount::get_username();
$stmt->bindParam(':in_accname', $param2, PDO::PARAM_STR);
$stmt->bindParam(':in_username', $param3, PDO::PARAM_STR);
$stmt->execute();
// Parse
$row = $stmt->fetch(PDO::FETCH_BOTH);
}
catch (PDOException $pe) {
die("Error: " .$pe->getMessage());
}
// Set properties and sessions variables
UserAccount::set_id($row['Id']);
UserAccount::set_accountname($row['AccountName']);
UserAccount::set_accountnumber($row['AccountNumber']);
UserAccount::set_accountemail($row['AccountEmail']);
UserAccount::set_fullname($row['FullName']);
UserAccount::set_accounttel($row['AccountTel']);
UserAccount::set_accountcontact($row['AccountContact']);
UserAccount::set_accounttype((int)$row['AccountType']);
UserAccount::set_paymenttype((int)$row['PaymentType']);
UserAccount::set_useremail($row['UserEmail']);
UserAccount::set_usertel($row['UserTel']);
UserAccount::set_usertype((int)$row['UserType']);
if (self::verify_account()) {
switch (UserAccount::get_paymenttype()) {
case 0:
$_SESSION['ua-paymenttype-asstr'] = 'Credit/Debit Card';
self::$form_action = 'addressdetails.php';
break;
case 1:
$_SESSION['ua-paymenttype-asstr'] = 'Account';
self::$form_action = 'makebooking.php';
break;
case 2:
$_SESSION['ua-paymenttype-asstr'] = 'Cash';
self::$form_action = 'makebooking.php';
break;
}
switch (UserAccount::get_usertype()) {
case 9:
$_SESSION['ua-usertype-asstr'] = 'Disabled/Suspended';
break;
case 0:
$_SESSION['ua-usertype-asstr'] = 'Standard';
break;
case 1:
$_SESSION['ua-usertype-asstr'] = 'Account Administrator';
break;
}
switch (UserAccount::get_accounttype()) {
case 9:
$_SESSION['ua-accounttype-asstr'] = 'Disabled/Suspended';
break;
case 0:
$_SESSION['ua-accounttype-asstr'] = ' ';
break;
case 1:
$_SESSION['ua-accounttype-asstr'] = '(SA)';
break;
}
// Redirect
if ($redirect_bool) {
self::redirect(true);
}
}
} else {
self::set_loginstatus("Pre-requisite failure! Browser not supporting cookies!");
$_SESSION['login-status'] = self::get_loginstatus();
self::redirect(false);
}
}
private static function redirect($auth_bool) {
//parent::set_sessionstate(true); ## Set session to active -- persistance to DB
//self::$determine_session_type(); ## Set session type -- persistance to DB
if ($auth_bool == true) {
$doc_root = $_SERVER['DOCUMENT_ROOT'];
self::set_loginstatus('');
$_SESSION['login-status'] = self::get_loginstatus();
header("Location: ".self::$redirect_url);
} else {
header("Location: login.php");
}
}
}
?>
I'm not sure since you're not showing the actual login/logout code, but maybe you're not destroying the session correctly?
session_start();
session_destroy();
EDIT: Nevermind, I think I may have misread your problem.
Related
can you help out a beginner trying to learn PHP? I wrote a code for changing password without any validations yet, just to change it and it does not work. It's been days I've been trying and couldn't figure out what's wrong. Thanks in advance.
id is variable name in database where id is kept.
db connection is done with first line and it definitely works.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
print_r($_SESSION);
function changePSW()
{
//$password = $_POST['currPassword']; // required
$newPassword = $_POST['newPassword']; // required
//$newPassword2 = $_POST['NewPassword2']; // required
$newPasswordH = password_hash($newPassword, PASSWORD_DEFAULT);
echo($newPassword);
$id = $_SESSION['userID'];
echo($id);
// create PDO connection object
$dbConn = new DatabaseConnection();
$pdo = $dbConn->getConnection();
try {
$statement = $pdo->prepare("SELECT * FROM `users` WHERE id = :id LIMIT 1");
$statement->bindParam(':id', $id);
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
echo "SADASDASD";
// no user matching the email
if (empty($result)) {
$_SESSION['error_message'] = 'Couldnt find user';
header('Location: /Online-store/userForm.php');
return;
}
$sql = "UPDATE users SET password=:newPasswordH WHERE id = :id";
// Prepare statement
$stmt = $pdo->prepare($sql);
echo "AFGHANIKO";
// execute the query
$update_status = $stmt->execute(array(':password' => $newPasswordH, ':id' => $id));
echo "IHAAA";
echo($update_status);
if ($update_status === TRUE) {
echo("Record updated successfully" . "\r\n");
echo nl2br("\nPassword: ");
echo ($newPassword);
echo nl2br("\nHashed Password: ");
echo ($newPasswordH);
return true;
} else {
echo "Error updating record";
die();
}
} catch (PDOException $e) {
// usually this error is logged in application log and we should return an error message that's meaninful to user
return $e->getMessage();
}
}
if($_SESSION['isLoggedIn'] == true) {
require_once("database/DatabaseConnection.php");
unset($_SESSION['success_message']);
unset($_SESSION['error_message']);
changePSW();
}
?>
$update_status = $stmt->execute(array(':newPasswordH' => $newPasswordH, ':id' => $id));
This is what I needed to have instead of
$update_status = $stmt->execute(array(':password' => $newPasswordH, ':id' => $id));
here is my code for optverify.php if the input number is wrong its redirect to index.php its not giving error.its should give a error for wrong otp but please help me to solve this issue
<?php
// Create a unique instance of your session variables
session_start();
if(isset($_SESSION['usr_id']))
{
$uid=$_SESSION['usr_id'];
} else {
header("Location:login.php");
}
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
if (isset($_POST['verifyotp'])) {
$otpsms = $_POST['smsotp'];
$otpemail = $_POST['emailotp'];
$user = $db->verifyotp($uid);
if($user){
$user['smsotp'] = $otpsms;
$user['emailotp'] = $otpemail;
header("Location:index.php");
} else {
$errormsg = "Invalid otp";
}
}
?>
and my codes for data base function are below
public function verifyotp($uid){
$stmt = $this->con->prepare("SELECT uid,smsotp,emailotp FROM users WHERE uid = '$uid'");
$stmt->bind_param("i", $uid);
if ($stmt->execute()) {
$stmt->bind_result($uid,$smsotp,$emailotp);
$stmt->fetch();
$user = array();
$user["uid"] = $uid;
$user["smsotp"] = $smsotp;
$user["emailotp"] = $emailotp;
$stmt->close();
return $user;
} else
{
return $stmt;
}
}
Not tested but this should work !! Let me know if this doesn't work. will delete this answer.
Updated
Change this $user = $db->verifyotp($uid); to $user = $db->verifyotp($uid, $otpsms, $otpemail);
then modify your function like below if you are willing to test 3 parameters (1) id (2) smsotp (3) emailotp.
public function verifyotp($uid, $sotp, $eotp){
$stmt = $this->con->prepare("SELECT uid,smsotp,emailotp FROM users WHERE uid = '$uid' And smsotp='$sotp' And emailotp ='$eotp'");
$stmt->bind_param("i", $uid);
if ($stmt->execute()) {
$stmt->bind_result($uid,$smsotp,$emailotp);
$stmt->fetch();
$user = array();
$user["uid"] = $uid;
$user["smsotp"] = $smsotp;
$user["emailotp"] = $emailotp;
$stmt->close();
return $user;
} else
{
return $stmt;
}
}
I want to make a sendmail function on my program. But first, I want to store the information: send_to, subject, and message in a table in another database(mes) where automail is performed. The problem is data fetched from another database(pqap) are not being added on the table(email_queue) in database(mes).
In this code, I have a table where all databases in the server are stored. I made a query to select a specific database.
$sql5 = "SELECT pl.database, pl.name FROM product_line pl WHERE visible = 1 AND name='PQ AP'";
$dbh = db_connect("mes");
$stmt5 = $dbh->prepare($sql5);
$stmt5->execute();
$data = $stmt5->fetchAll(PDO::FETCH_ASSOC);
$dbh=null;
Then after selecting the database,it has a query for selecting the information in the table on the selected database. Here's the code.
foreach ($data as $row5) GenerateEmail($row5['database'], $row5['name']);
Then this is part (I think) is not working. I don't know what's the problem.
function GenerateEmail($database, $line) {
$sql6 = "SELECT * FROM invalid_invoice WHERE ID=:id6";
$dbh = db_connect($database);
$stmt6 = $dbh->prepare($sql6);
$stmt6->bindParam(':id6', $_POST['idtxt'], PDO::PARAM_INT);
$stmt6->execute();
$data = $stmt6->fetchAll(PDO::FETCH_ASSOC);
$dbh=null;
foreach ($data as $row6) {
$invnumb=$row6['Invoice_Number'];
$partnumb=$row6['Part_Number'];
$issue=$row6['Issues'];
$pic=$row6['PIC_Comments'];
$emailadd= $row6['PersoninCharge'];
if($row6['Status']=="Open") {
$message = "<html><b>Invoice Number: {$invnumb}.</b><br><br>";
$message .= "<b>Part Number:</b><br><xmp>{$partnumb}</xmp><br><br>";
$message .= "<b>Issues:</b><br><xmp>{$issue}</xmp><br>";
$message .= "<b>{$pic}<b><br>";
$message .= "</html>";
if(!empty($emailadd)) {
dbInsertEmailMessage($emailadd, "Invoice Number: {$invnumb} - {$issue}.", $message);
$dbh=null;
}
}
}
}
function dbInsertEmailMessage($send_to, $subject, $message) {
$sql7 = "INSERT INTO email_queue (Send_to, Subject, Message) VALUES (:send_to, :subject, :message)";
$dbh = db_connect("mes");
$stmt7 = $dbh->prepare($sql7);
$stmt7->bindParam(':send_to', $send_to, PDO::PARAM_STR);
$stmt7->bindParam(':subject', $subject, PDO::PARAM_STR);
$stmt7->bindParam(':message', $message, PDO::PARAM_STR);
$stmt7->execute();
$dbh=null;
}
Here's my db connection:
function db_connect($DATABASE) {
session_start();
// Connection data (server_address, database, username, password)
$servername = '*****';
//$namedb = '****';
$userdb = '*****';
$passdb = '*****';
// Display message if successfully connect, otherwise retains and outputs the potential error
try {
$dbh = new PDO("mysql:host=$servername; dbname=$DATABASE", $userdb, $passdb, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
return $dbh;
//echo 'Connected to database';
}
catch(PDOException $e) {
echo $e->getMessage();
}
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
There are a couple things that may help with your failed inserts. See if this is what you are looking for, I have notated important points to consider:
<?php
// take session_start() out of your database connection function
// it draws an error when you call it more than once
session_start();
// Create a connection class
class DBConnect
{
public function connect($settings = false)
{
$host = (!empty($settings['host']))? $settings['host'] : false;
$username = (!empty($settings['username']))? $settings['username'] : false;
$password = (!empty($settings['password']))? $settings['password'] : false;
$database = (!empty($settings['database']))? $settings['database'] : false;
try {
$dbh = new PDO("mysql:host=$host; dbname=$database", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
// You return the connection before it hits that setting
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
catch(PDOException $e) {
// Only return the error if an admin is logged in
// you may reveal too much about your database on failure
return false;
//echo $e->getMessage();
}
}
}
// Make a specific connection selector
// Put in your database credentials for all your connections
function use_db($database = false)
{
$con = new DBConnect();
if($database == 'mes')
return $con->connect(array("database"=>"db1","username"=>"u1","password"=>"p1","host"=>"localhost"));
else
return $con->connect(array("database"=>"db2","username"=>"u2","password"=>"p2","host"=>"localhost"));
}
// Create a query class to return selects
function query($con,$sql,$bind=false)
{
if(empty($bind))
$query = $con->query($sql);
else {
foreach($bind as $key => $value) {
$kBind = ":{$key}";
$bindVals[$kBind] = $value;
}
$query = $con->prepare($sql);
$query->execute($bindVals);
}
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
return (!empty($result))? $result:0;
}
// Create a write function that will write to database
function write($con,$sql,$bind=false)
{
if(empty($bind))
$query = $con->query($sql);
else {
foreach($bind as $key => $value) {
$kBind = ":{$key}";
$bindVals[$kBind] = $value;
}
$query = $con->prepare($sql);
$query->execute($bindVals);
}
}
// Do not create connections in your function(s), rather pass them into the functions
// so you can use the same db in and out of functions
// Also do not null the connections out
function GenerateEmail($con,$conMes,$line = false)
{
if(empty($_POST['idtxt']) || (!empty($_POST['idtxt']) && !is_numeric($_POST['idtxt'])))
return false;
$data = query($con,"SELECT * FROM `invalid_invoice` WHERE `ID` = :0", array($_POST['idtxt']));
if($data == 0)
return false;
// Instead of creating a bunch of inserts, instead create an array
// to build multiple rows, then insert only once
$i = 0;
foreach ($data as $row) {
$invnumb = $row['Invoice_Number'];
$partnumb = $row['Part_Number'];
$issue = $row['Issues'];
$pic = $row['PIC_Comments'];
$emailadd = $row['PersoninCharge'];
if($row['Status']=="Open") {
ob_start();
?><html>
<b>Invoice Number: <?php echo $invnumb;?></b><br><br>
<b>Part Number:</b><br><xmp><?php echo $partnumb; ?></xmp><br><br>
<b>Issues:</b><br><xmp><?php echo $issue; ?></xmp><br>
<b><?php echo $pic; ?><b><br>
</html>
<?php
$message = ob_get_contents();
ob_end_clean();
if(!empty($emailadd)) {
$bind["{$i}to"] = $emailadd;
$bind["{$i}subj"] = "Invoice Number: {$invnumb} - {$issue}.";
$bind["{$i}msg"] = htmlspecialchars($message,ENT_QUOTES);
$sql[] = "(:{$i}to, :{$i}subj, :{$i}msg)";
}
}
$i++;
}
if(!empty($sql))
return dbInsertEmailMessage($conMes,$sql,$bind);
return false;
}
function dbInsertEmailMessage($con,$sql_array,$bind)
{
if(!is_array($sql_array))
return false;
write($con,"INSERT INTO `email_queue` (`Send_to`, `Subject`, `Message`) VALUES ".implode(", ",$sql_array),$bind);
return true;
}
// Create connections
$con = use_db();
$conMes = use_db('mes');
GenerateEmail($con,$conMes);
What i'm trying to do is make a function that gets a user permission level as seen here.
function userPermission($level, $conn){
try{
$sql = "SELECT * FROM `users` WHERE username = :Player AND level = :Level ";
$s = $conn->prepare($sql);
$s->bindValue(":Player", $_SESSION['username']);
$s->bindValue(":Level", $level);
$s->execute();
return true;
} catch(PDOException $e) {
error_log("PDOException: " . $e->getMessage());
return false;
}
}
and once I go to the page and input the code that should in-tile the functionality of this function. It doesn't work at all.
Here is the code that I inputted
<?php if (!userPermission('0', $conn) == 2) {
echo '<input type="radio" id="tab-7" name="tab-group-1">
<label for="tab-7">Permissions</label>';
} else {
echo '<input disabled=disabled type="radio" id="tab-7" name="tab-group-1">
<label id="disabled" for="tab-7">Permissions</label>';
}
?>
The 0 is the current level of the user and I was using that as a test, as for the == 3 that's what the rank has to be in order to access the tab
Anyways, I'm either doing this wrong or I don't know what i'm doing. I get no errors at all but the code I inputted seems unreliable.
Your code just execute but does not return the query result.
I modified your code a little bit as an example
function userPermission($username,$level, $conn){
try{
$sql = "SELECT `user_permission`
FROM `users`
WHERE username = :username AND level = :Level ";
$s = $conn->prepare($sql);
$s->bindValue(":username", $username);
$s->bindValue(":level", $level);
$s->execute();
$row = $s->fetch();
return $row['user_permission'];
} catch(PDOException $e) {
error_log("PDOException: " . $e->getMessage());
return -1;
}
}
Make sure the session is set also
session_start();
$usermame = $_SESSION['username'];
if (!userPermission($username,'0', $conn) == 2) {...
This is some PHP code for login on a page.
if ($_POST['submit']=="Log In") {
$query = "SELECT * FROM user WHERE email='".mysqli_real_escape_string($link, $email)."' AND password='$md5' LIMIT 1";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
print_r($row);
}
But when I submit LOGIN it doesn't work.
$userCheck = query("SELECT * FROM users WHERE users_email =?",$_POST['user']);
if(count($userCheck)===1){
//we found a match
$data = $userCheck[0];
//now we compare the encryted password
if(crypt($_POST['password'],$data['users_hash'])===$data['users_hash']){
//the password match... the encrypted password
$logged=1;
//so we set the cookie if the user checked the cookie box
//cookie and session code
echo 1;
}else{
//meaning wrong password
echo 2;
}
}else{
//wrong username
echo 0;
}
I am using a custom function working with PDO... I can post the function here if you need to
custom query function using PDO
function query(/* $sql [, ... ] */){
// SQL statement
$sql = func_get_arg(0);
// parameters, if any
$parameters = array_slice(func_get_args(), 1);
// try to connect to database
static $handle;
if (!isset($handle))
{
try
{
// connect to database
$handle = new PDO("mysql:dbname=" . DATABASE . ";host=" . SERVER, USERNAME, PASSWORD);
// ensure that PDO::prepare returns false when passed invalid SQL
$handle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (Exception $e)
{
// trigger (big, orange) error
trigger_error($e->getMessage(), E_USER_ERROR);
exit;
}
}
// prepare SQL statement
$statement = $handle->prepare($sql);
if ($statement === false)
{
// trigger (big, orange) error
trigger_error($handle->errorInfo()[2], E_USER_ERROR);
exit;
}
// execute SQL statement
$results = $statement->execute($parameters);
// return result set's rows, if any
if ($results !== false)
{
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
else
{
return false;
}
}
to use it, see the synthax on the top
or:
ex:
$check = query("SELECT * FROM table WHERE column=?",$text);