I've got a login script that does not close the session when the user goes to another site or returns to the login page. My question is, how do I destroy the session when they navigate away from the site or outside of the directory? Would I need to add a timeout argument when the user starts the session? Would I need to use cookies instead of session?
login.php
require("../includes/header.php");
if($_SERVER["REQUEST_METHOD"] == "POST"){
$p_num = $_POST["username"];
$pwd = $_POST["password"];
$query = "SELECT * FROM $user_table";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_assoc($result)){
$user_id = "{$row['user_id']}";
$user_name = "{$row['user_name']}";
$password = "{$row['password']}";
$image = "{$row['image']}";
$email = "{$row['email']}";
$program = "{$row['program']}";
$role = "{$row['role']}";
if(($user_id == $p_num) && ($pwd == $password)){
$_SESSION["id"] = $user_id;
$_SESSION["user"] = $user_name;
$_SESSION["program"] = $program;
$_SESSION["pass"] = $password;
$_SESSION["image"] = $image;
$_SESSION["email"] = $email;
$_SESSION["role"] = $role;
header("Location: ../pages/instructor.php");
}
else{
header("Refresh: 1; URL=../index.php");
}
}
}
instructor.php
<?php require("../includes/header.php"); ?>
<title></title>
<link href="../css/style.css" rel="stylesheet/less" type="text/css">
<script src="../js/jquery.2.0.3.js"></script>
<script src="../js/script.js"></script>
<script src="../js/less-1.7.4.min.js"></script>
</head>
<body>
<div id="page">
<header>
<div id="logo" class="logo_bg"></div>
<div id="fsi_logo" class="logo_bg"></div>
</header>
<div id="main">
<div id="instructor">
<?php
echo "<img id=instructor_image src=" .$_SESSION["image"] .">";
echo "<h1>" .$_SESSION["user"] ."</h1>";
echo "<span><p>" .$_SESSION["program"] ."</p> - <h2>" .$_SESSION["role"] ."</h2></span>";
echo "" .$_SESSION["email"] ."";
?>
</div>
<div id="bleg">
<h1>BUILD SCENARIO</h1>
<h1>SEARCH SCENARIOS</h1>
<h1>VIEW SCENARIOS</h1>
</div>
<?php require("../includes/footer.html"); ?>
logout.php
session_start();
session_unset();
session_destroy();
script.js
$(window).on('beforeunload', function(e){
e.preventDefault();
ajax = new XMLHttpRequest();
ajax.open("../php/logout.php", "POST", true);
ajax.send();
})
Do it with javascript
window.onbeforeunload = function (e) {
e.preventDefault(); //Not even sure what the default action does, but oh well
ajax = new XMLHttpRequest();
ajax.open("killsession.php","POST",true);
ajax.send();
}
killsession.php will of course be where the session is killed
Write a jquery/JS event handler for unload doc and send a request to ExpireSession.php expiring the session
As said "It depends on what constitutes "leaving""
$count = $_SESSION['count'];
if($count === 1) {
unset ($_SESSION['count']);
}
else (empty($_SESSION['count'])) {
$_SESSION['count'] = 1;
}
Related
This question already has answers here:
PHP Session variable not getting set
(9 answers)
Closed 1 year ago.
I've been following Dani Krossings Login System It's a great tutorial and is just what I am looking for, there is just one thing I'm struggling with.
After logging in, the header doesn't refresh. Following login, the header should change to ...Profile Page, Logout. The code I have stays as Sign Up, Login. It is as is the $_SESSION variable has not come through to the header. However, if after login, I select the Sign up or login link, the header changes to what it should be.
Function code
function uidExists($conn, $username) {
$sql = "SELECT * FROM users WHERE usersUid = ? OR usersEmail = ?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("location: ../signup.php?error=stmtfailed");
exit();
}
mysqli_stmt_bind_param($stmt, "ss", $username, $username);
mysqli_stmt_execute($stmt);
// "Get result" returns the results from a prepared statement
$resultData = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($resultData)) {
return $row;
}
else {
$result = false;
return $result;
}
mysqli_stmt_close($stmt);
}
function loginUser($conn, $username, $pwd) {
$uidExists = uidExists($conn, $username);
if ($uidExists === false) {
header("location: ../login.php?error=wronglogin");
exit();
}
$pwdHashed = $uidExists["usersPwd"];
$checkPwd = password_verify($pwd, $pwdHashed);
if ($checkPwd === false) {
header("location: ../login.php?error=wronglogin");
exit();
}
elseif ($checkPwd === true) {
session_start();
$_SESSION["userid"] = $uidExists["usersId"];
$_SESSION["useruid"] = $uidExists["usersUid"];
header("location: ../index.php?error=none");
exit();
}
}
header.php
<?php
session_start();
include_once 'includes/functions.inc.php';
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>PHP Project 01</title>
<!--I won't do more than barebone HTML, since this isn't an HTML tutorial.-->
<link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght#0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<!--A quick navigation-->
<nav>
<div class="wrapper">
<img src="img/logo-white.png" alt="Blogs logo">
<ul>
<li>Home</li>
<li>About Us</li>
<li>Find Blogs</li>
<?php
if (isset($_SESSION["useruid"])) {
echo "<li><a href='profile.php'>Profile Page</a></li>";
echo "<li><a href='logout.php'>Logout</a></li>";
}
else {
echo "<li><a href='signup.php'>Sign up</a></li>";
echo "<li><a href='login.php'>Log in</a></li>";
}
?>
</ul>
</div>
</nav>
<!--A quick wrapper to align the content (ends in footer.php)-->
<div class="wrapper">
Login.php
<?php
include_once 'header.php';
?>
<section class="signup-form">
<h2>Log In</h2>
<div class="signup-form-form">
<form action="includes/login.inc.php" method="post">
<input type="text" name="uid" placeholder="Username/Email...">
<input type="password" name="pwd" placeholder="Password...">
<button type="submit" name="submit">Sign up</button>
</form>
</div>
<?php
// Error messages
if (isset($_GET["error"])) {
if ($_GET["error"] == "emptyinput") {
echo "<p>Fill in all fields!</p>";
}
else if ($_GET["error"] == "wronglogin") {
echo "<p>Wrong login!</p>";
}
}
?>
</section>
<?php
include_once 'footer.php';
?>
login.inc.php
<?php
if (isset($_POST["submit"])) {
// First we get the form data from the URL
$username = $_POST["uid"];
$pwd = $_POST["pwd"];
// Then we run a bunch of error handlers to catch any user mistakes we can (you can add more than I did)
// These functions can be found in functions.inc.php
require_once 'dbh.inc.php';
require_once 'functions.inc.php';
// Left inputs empty
if (emptyInputLogin($username, $pwd) === true) {
header("location: ../login.php?error=emptyinput");
exit();
}
// If we get to here, it means there are no user errors
// Now we insert the user into the database
loginUser($conn, $username, $pwd);
} else {
header("location: ../login.php");
exit();
}
Anyone have any thoughts on how I can get the header to refresh on submission of a successful login form?
Since Sometimes Some Content Is Left On The Page After Reloading The Header, We Need To Use die() after Changing Location From Header.
TBH, Redirecting Using PHP Is Not Recommended, I Suggest You To Redirect The User Using An Inbuilt JavaScript Function, window.location.replace(path)
You Can Call It Inside A PHP Script Using
?>
<script>
window.location.replace(path)
</script>
<?php
Or Simply Just Create Your Own Function:
function redirect($path) {
?>
<script>
window.location.replace('<?php echo $path ?>')
</script>
<?php
}
And Use It: redirect("profile.php")
Always put a session_start() into every page I want to use $_SESSION variables.
Fixed.
Thanks for all your help!
UPDATED: I have a variable in PHP mailuid that I want to show in my HTML. It displays the error the value of mailuid is undefined on the webpage. How can I show the value of height to html page?
index.php
<?php
require "header.php";
?>
<main>
<link rel="stylesheet" type="text/css" href="styl.css">
<div class="wrapper-main">
<section class="section-default">
<h2><?php echo "$mailuid" ?></h2>
<?php
?>
</section>
</div>
</main>
<?php
require "footer.php";
?>
loginbackend.php
<?php
if(isset($_POST['login-submit'])) {
require 'db.php';
$mailuid = $_POST['mailuid'];
$password = $_POST['pwd'];
if (empty($mailuid) || empty($password)) {
header("Location: ./index.php?error=emptyfields");
exit();
} else {
$sql = "SELECT * FROM users WHERE uidUsers=? OR emailUsers=?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ./index.php?error=sqlerror");
exit();
} else {
mysqli_stmt_bind_param($stmt, "ss", $mailuid, $mailuid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)) {
$pwdCheck = password_verify($password, $row['pwdUsers']);
if($pwdCheck == false) {
header("Location: ./index.php?error=wrongpwd");
exit();
} else if ($pwdCheck == true) {
session_start();
$_SESSION['userId'] = $row['idUsers'];
$_SESSION['userUid'] = $row['uidUsers'];
$username = substr($mailuid, 0, strpos($mailuid, "#"));
header("Location: ./index.php?login=success".$username);
exit();
} else {
header("Location: ./index.php?error=wrongpwd");
exit();
}
} else {
header("Location: ./index.php?error=nouser");
exit();
}
}
}
} else {
header("Location: ./signup.php");
exit();
}
As per your latest comment:
To get the mailuid from the URL (GET parameters) add the following code to your index.php
<?PHP
require "header.php";
$mailuid = !empty($_GET['mailuid']) ? $_GET['mailuid'] : null;
// You can also specify the default value to be used instead of `null` if the `mailuid` is not specified in the URL.
?>
<main>
<link rel="stylesheet" type="text/css" href="styl.css">
<div class="wrapper-main">
<section class="section-default">
<h2><?php echo "$mailuid"?></h2>
</section>
</div>
</main>
<?php
require "footer.php";
?>
From PHP7 you can use
$mailuid = $_GET['mailuid'] ?? null;
instead of
$mailuid = !empty($_GET['mailuid']) ? $_GET['mailuid'] : null;
The mistake you've made:
I think you're confusing forms and file including with how post works.
Let me explain:
A form sends data to the server, which is then pushed into the $_POST global variable. You can read this data and use this data easily by echoing or dumping it.
This is what you should do:
In this case, your data value will be empty as you're not passing anything to it.
You can solve this by creating a form and passing it to your PHP file.
You can also just require your php script.
Normally you would put data.php in your action, but since you wish to use the variable before you entered the form, you have to include it first.
index.html
<?php require 'data.php'; ?>
<form method="POST" action="">
<h1>Height: <?=$height?></h1>
<input type="text" placeholder="Enter the height..." name="height">
<input type="submit" name="submit" value="Submit">
</form>
data.php
<?php
if (!empty($_POST)) {
$height = $_POST['height'];
} else {
$height = 0; //Default height
}
My apologies if i didn't get your question properly.
===========================================
Option B, if this is what you mean, is just doing this:
index.html
<body>
<div class="container">
<?php
require 'data.php'; //Get the data.php file so we can use the contents
?>
<h1><?php echo $height; ?></h1>
</div>
</body>
data.php
<?php
$height = 100; //Height variable
Edit: Forgot to mention none of the SQL works at all when it fails.
I seriously need help figuring this out. It has been about a month since the issue has arrived. I have rewrote the page a couple times and have tried removing some unneeded items in case it was a speed issue (had sidebar that auto scrolled and loaded in two social media widgets which was kinda slow on bad internet) and so far nothing. I really do not know why this happens at all.
Here is the kicker. It only happens to random people. Never breaks for me but breaks nearly every time for a customer on certain pc's. Another issue that person is running into is the cart cookie won't clear for that person either(just them).
I am Using Auth.net's DPM method which takes them offsite momentarily then to my Order_receipt page(the one in question). When arriving at that page you are given 2 $_GET properties example (order_receipt.php?response_code=1&transaction_id=136434353) which is coming in properly even when it fails.
Customer that has issue is using win 10, and has tried it with both chrome and edge running kaspersky antivirus (no issues on my end from either browser)
I'm going to include all code loaded and included in that page below, starting with the order_receipt itself.
** = redacted info
Order_receipt.php:
<?php
require_once 'system/init.php';
include 'includes/head.php';
include 'includes/navigation.php';
include 'includes/headerpartial.php';
?>
<div id="maincontent" class="col-md-12">
<?php
ini_set('error_reporting', -1); ini_set('display_errors', 'on');
ini_set('log_errors', 1);
ini_set('error_log', 'system/error_logs.log');
$error_code = uniqid(mt_rand(), true);
if ($_GET['response_code'] == 1)
{
$trans_id = $_GET['transaction_id'];
if (isset($cart_id)){
$db->query("UPDATE transactions SET charge_id = '$trans_id' WHERE cart_id = '$cart_id'");
$tsql = $db->query("SELECT * FROM transactions WHERE cart_id = '$cart_id' ");
$tran = mysqli_fetch_assoc($tsql);
?>
<h1 id="reciept">Thank you for your support!</h1><hr>
<p id="reciept">
On behalf of ** <?=$tran['full_name']?> we thank you for your purchase and hope you enjoy it!
</p>
<p id="reciept">
You have selected <b>"<?=$tran['pickup-location']?>"</b> as your pickup point.
</p>
<table id="nav-button" class="table table-bordered table-auto">
<tbody>
<tr>
<td>Transaction ID : <?=$tran['charge_id']?></td>
</tr>
<?php
$a = 1;
$it = 1;
$string = $tran['items'];
$itemar = explode(',', $string);
$num = 1;
$istr = $tran['inventory'];
$stri = explode(',', $istr);
if ($tran['status'] != "Complete") {
foreach (array_slice($stri, $num) as $inve ){
$exploded = explode('.', $inve);
$itname = $exploded['0'];
$itquan = $exploded['1'];
$db->query("UPDATE products SET `quantity` = `quantity` - '$itquan' WHERE title = '$itname'");
$db->query("UPDATE products SET `Sold` = `Sold` + '$itquan' WHERE title = '$itname'");
$it++;
}
$compl = "Complete";
$db->query("UPDATE transactions SET `status` = '$compl' WHERE cart_id = '$cart_id'");
}
foreach (array_slice($itemar, $num) as $itemr ){
?>
<tr>
<td><?=$itemr?></td>
</tr>
<?php
$a++;
} ?>
<tr>
<td>
Total: <?=money($tran['grand_total']);?>
</td>
</tr>
</tbody>
</table>
<?php
$domain = '.'.$_SERVER['HTTP_HOST'];
setcookie(CART_COOKIE,'',1,"/",$domain,false);
}else{echo "Cart Id not Set";}
}else
{
echo "Sorry, an error occurred: ".htmlentities($_GET['response_reason_text']);
}?>
</div>
<?php
include 'includes/footer.php';
?>
Init.php:
<?php
$db = mysqli_connect("**","**","**","**");
if(mysqli_connect_errno()){
echo 'Database connection failed with following errors: '. mysqli_connect_error();
die();
}
session_start();
require_once $_SERVER['DOCUMENT_ROOT'].'/config.php';
require_once BASEURL.'helpers/helpers.php';
$cart_id = '';
if(isset($_COOKIE[CART_COOKIE])){
$cart_id = sanitize($_COOKIE[CART_COOKIE]);
}
if (isset($_SESSION['LHUser'])) {
$user_id = $_SESSION['LHUser'];
$query = $db->query("SELECT * FROM users WHERE id = '$user_id'");
$user_data = mysqli_fetch_assoc($query);
$fn = explode(' ', $user_data['full_name']);
$user_data['first'] = $fn[0];
$user_data['last'] = $fn[1];
}
if (isset($_SESSION['success_flash'])) {
echo '<div class="bg-success"><p class="text-success text-center">'.$_SESSION['success_flash'].'</p></div>';
unset($_SESSION['success_flash']);
}
if (isset($_SESSION['error_flash'])) {
echo '<div class="bg-danger"><p class="text-danger text-center">'.$_SESSION['error_flash'].'</p></div>';
unset($_SESSION['error_flash']);
}
?>
config.php:
<?php
define('BASEURL', $_SERVER['DOCUMENT_ROOT'].'/');
define('CART_COOKIE','Sd4CqdgRt6J3gd3F7');
define('CART_COOKIE_EXPIRE', time() + (86400 * 30));
?>
helpers.php:
<?php
ob_start();
function display_errors($errors){
$display = '<ul class="bg-danger">';
foreach ($errors as $error) {
$display .= '<li class="text-danger">'.$error.'</li>';
}
$display .= '</ul>';
return $display;
}
function sanitize($dirty){
return htmlentities($dirty,ENT_QUOTES,"UTF-8");
}
function money($number){
return '$'.number_format($number,2);
}
function login($user_id){
$_SESSION['LHUser'] = $user_id;
global $db;
$date = date("Y-m-d H:i:s");
$db->query("UPDATE users SET last_login = '$date' WHERE id = '$user_id'");
$_SESSION['success_flash'] = 'You are now logged in!';
header('Location: index.php');
}
function is_logged_in(){
if (isset($_SESSION['LHUser']) && $_SESSION['LHUser'] > 0) {
return true;
}
return false;
}
function login_error_redirect($url = 'login.php'){
$_SESSION['error_flash'] = 'You must be logged in to access that page';
header('Location:'.$url);
}
function permission_error_redirect($url = 'login.php'){
$_SESSION['error_flash'] = 'You don\'t have permission to access that page';
header('Location:'.$url);
}
function has_permission($permission = 'admin'){
global $user_data;
$permissions = explode(',', $user_data['permissions']);
if (in_array($permission,$permissions,true)) {
return true;
}
return false;
}
function get_category($child_id){
global $db;
$id = sanitize($child_id);
$sql = "SELECT p.id AS 'pid', p.category AS 'parent', c.id AS 'cid', c.category AS 'child'
FROM categories c
INNER JOIN categories p
ON c.parent = p.id
WHERE c.id = '$id'";
$query = $db->query($sql);
$category = mysqli_fetch_assoc($query);
return $category;
}
head.php:
<!DOCTYPE html>
<html>
<head>
<title>LettuceHeads</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/main.css">
<link rel="icon" href="../images/header/logoicon.png">
<meta name="Viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script SRC="js/bootstrap.min.js"></script>
</head>
<body>
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.6";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
navigation.php:
<?php
$sql = "SELECT * FROM navigation ORDER BY `navigation`.`sort` ASC";
$pquery = $db->query($sql);
?>
<nav id="navbar" class="navbar navbar-default navbar-fixed-top" role="navigation">
<div id="navtext" class="containter">
<a id="navborder" href="index.php" class="navbar-brand">**</a>
<ul class="nav navbar-nav">
<?php while($parent = mysqli_fetch_assoc($pquery)) : ?>
<li id="navborder"><?=$parent['name'];?></li>
<?php endwhile; ?>
</li>
</ul>
<ul id="navright" class="nav navbar-nav navbar-right" >
<li id="navborder2"><span class = "glyphicon glyphicon-shopping-cart"></span> My Cart</li>
<?php if(has_permission('admin')): ?>
<li id="navborder">Staff</li>
<?php endif; ?>
</ul>
</div>
</nav>
headerpartial.php:
<div id="partialHeaderWrapper">
<div id="partialbackitem"></div>
<div id="partiallogotext"></div>
<div id="partialfore-item"></div>
</div>
<div class="container-fluid">
footer.php:
I have the following line in my HTML file for my homepage. How come it won't print out the name of the current user when they log in? I have the line in the body section of the html file. I want to put it on all my pages too but it won't display. The user does exist as it logs in succesfully via my php echo mesage.
This line:
<div id="usernameDiv"><?php echo $_SESSION['username']; ?></div>
Here is the login page:
<?php
function SignIn() {
require_once("constants.php"); //Now constants will be accessible
session_start();
try {
$link = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASSWORD);
$username = $_POST['username']; //no need to esaping as we will use prepared statements
$password = $_POST['password'];
if (!empty($username) && !empty($password)) {
//You need to define a new column named "id" which will be int auto_increment and it will be your primary key
$sql = "SELECT id, username, password FROM users where username = :username AND password = :password";
//Prepare your query
$stmt = $link->prepare($sql);
//Execute your query binding variables values
$stmt->execute(array(':username'=>$username, ':password'=>$password));
//Fetch the row that match the criteria
$row = $stmt->fetch();
if (!empty($row['username']) && !empty($row['password'])) {
$_SESSION['is_logged'] = true; //Now user is considered logged in
$_SESSION['username'] = $row['username'];
$_SESSION['id'] = $row['id'];
//Never store passwords in $_SESSION
echo "Welcome to your User Account for CSIT Conference. Click to go home: ";
echo ' Home Page . ';
echo "Or here to go to your assigned papers: ";
echo ' Assigned Papers . ';
} else {
echo "SORRY... YOU ENTERED WRONG ID AND PASSWORD... PLEASE RETRY...";
}
$link = null;
} else {
echo 'Please enter username and password.';
}
} catch(PDOException $e) {
echo $e->getMessage();
}
}
if (isset($_POST['submit'])) {
SignIn();
}
?>
Here is the home page. Eventually I want it on all the pages.
<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="import" href="navigation.html">
</head>
<body>
<center> <b>World Congress CS-IT Conferences 2016</center>
<div id="horizontalmenu">
<ul>
<li>Home<br/></li>
<ul> <li>General Information <ul>
<li>About</li>
<li> Conference Fee</li>
<li>Hotel</li> </ul>
<li>Keynote Speakers<br/></li>
<li>Call for Papers<br/></li>
<li>Important Dates<br/></li>
<li>Major Areas<br/></li>
<li>Paper Submission<br/></li>
<li>Login<br/></li>
<li>Registration<br/></li>
<li>Conference Program<br/></li>
<li>Guidelines<br/></li>
<li>Comments<br/></li>
</ul>
</nav></b>
<div id="usernameDiv"><?php echo $_SESSION['username']; ?></div>
<br><br>
<div class="zoom pic">
<center> <img src="images/technology.png" alt="portrait"> <center>
</div>
</body>
</html>
You are starting the session inside of your SignIn() function. Remove session_start(), and instead put the following at the top of your file to start your session:
if (!session_id()) #session_start();
You must also include the above line anywhere that you want to use the session data (for example, it should be the first line in your index file.)
* All of this assumes that you either have PHP setup to execute in a .html file, or your file is actually index.php instead of index.html
I'm learning php and I'm using a tutorial to build a small community site.
I already have sign up, login and lost password set up as well as a profile page where the user can see his data which is saved in the database.
Now I'm trying to create a settings page where the user can edit his information and I scaled it down to just change the password for now for testing purposes.
So, to see if the user is logged in, I have this function, which I included on my settings page:
<?php
include_once("db_conx.php");
// Files that inculde this file at the very top would NOT require
// connection to database or session_start(), be careful.
// Initialize some vars
$user_ok = false;
$log_id = "";
$log_username = "";
$log_password = "";
// User Verify function
function evalLoggedUser($conx,$id,$u,$p){
$sql = "SELECT ip FROM users WHERE id='$id' AND username='$u' AND password='$p' AND activated='1' LIMIT 1";
$query = mysqli_query($conx, $sql);
$numrows = mysqli_num_rows($query);
if($numrows > 0){
return true;
}
}
if(isset($_SESSION["userid"]) && isset($_SESSION["username"]) && isset($_SESSION["password"])) {
$log_id = preg_replace('#[^0-9]#', '', $_SESSION['userid']);
$log_username = preg_replace('#[^a-z0-9]#i', '', $_SESSION['username']);
$log_password = preg_replace('#[^a-z0-9]#i', '', $_SESSION['password']);
// Verify the user
$user_ok = evalLoggedUser($db_conx,$log_id,$log_username,$log_password);
} else if(isset($_COOKIE["id"]) && isset($_COOKIE["user"]) && isset($_COOKIE["pass"])){
$_SESSION['userid'] = preg_replace('#[^0-9]#', '', $_COOKIE['id']);
$_SESSION['username'] = preg_replace('#[^a-z0-9]#i', '', $_COOKIE['user']);
$_SESSION['password'] = preg_replace('#[^a-z0-9]#i', '', $_COOKIE['pass']);
$log_id = $_SESSION['userid'];
$log_username = $_SESSION['username'];
$log_password = $_SESSION['password'];
// Verify the user
$user_ok = evalLoggedUser($db_conx,$log_id,$log_username,$log_password);
if($user_ok == true){
// Update their lastlogin datetime field
$sql = "UPDATE users SET lastlogin=now() WHERE id='$log_id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
}
}
?>
And this is the settings page:
<?php
include 'php_includes/db_conx.php';
include 'php_includes/login_ex.php';
include_once("php_includes/check_login_status.php");
// Initialize any variables that the page might echo
$u = "";
$sex = "Male";
$userlevel = "";
$country = "";
$joindate = "";
$lastsession = "";
$password = "";
// Make sure the _GET username is set, and sanitize it
if(isset($_GET["u"])){
$u = preg_replace('#[^a-z0-9]#i', '', $_GET['u']);
} else {
header("location: index.php");
exit();
}
// Select the member from the users table
$sql = "SELECT * FROM users WHERE username='$u' AND activated='1' LIMIT 1";
$user_query = mysqli_query($db_conx, $sql);
// Now make sure that user exists in the table
$numrows = mysqli_num_rows($user_query);
if($numrows < 1){
echo "That user does not exist or is not yet activated, press back";
exit();
}
// Check to see if the viewer is the account owner
$isOwner = "no";
if($u == $log_username && $user_ok == true){
$isOwner = "yes";
}
// Fetch the user row from the query above
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$profile_id = $row["id"];
$gender = $row["gender"];
$country = $row["country"];
$userlevel = $row["userlevel"];
$signup = $row["signup"];
$lastlogin = $row["lastlogin"];
$joindate = strftime("%b %d, %Y", strtotime($signup));
$lastsession = strftime("%b %d, %Y", strtotime($lastlogin));
if($gender == "f"){
$sex = "Female";
}
}
?>
<!doctype html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="robots" content="index, follow">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="css/bootstrap.css" rel="stylesheet" media="screen" type="text/css">
<link href="css/custom.css" rel="stylesheet" type="text/css">
<link href="css/bootstrap-min.css" rel="stylesheet" media="screen" type="text/css">
<script src="js/main.js"></script>
<title>KZ|Language exchange</title>
</head>
<body>
<div id="custom-bootstrap-menu" class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container-fluid">
<div class="navbar-header"><a class="navbar-brand" href="#">Brand</a>
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-menubuilder"><span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse navbar-menubuilder">
<ul class="nav navbar-nav navbar-left">
<li>Home
</li>
<li>Profile
</li>
<li>About Us
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><?php
if ($isOwner == "yes") {?>
<a class="navbar-brand" href="logout.php" style="border-left: 1px solid; padding-left: 10px;">Logout</a>
<?php
}
?>
</li>
</ul>
</div>
</div>
</div>
<div class="container">
<div class="row-fluid">
<div class="col-md-9">
<h3><?php echo $u; ?></h3>
<p>Is the viewer the page owner, logged in and verified? <b><?php echo $isOwner; ?></b></p>
<p>Gender: <?php echo $sex; ?></p>
<p>Country: <?php echo $country; ?></p>
<p>User Level: <?php echo $userlevel; ?></p>
<p>Join Date: <?php echo $joindate; ?></p>
<p>Last Session: <?php echo $lastsession; ?></p>
<p>Password: <?php echo $password; ?></p>
<?php var_dump($_SESSION);
var_dump($_SESSION['username']);
?>
<?php
// i need to make sure that $isOwner = "yes"; so only logged in users see the form and can change the password
if (isset($_POST['submit'])) {
$password = $_POST["password"];
var_dump($password);
$sql = "UPDATE users SET password='$password' WHERE username='$u'";
}
?>
<h3>Create new password</h3>
<form action="user.php" method="post">
<div>Password</div>
<input type="text" class="form-control" id="password" name="password">
<br /><br />
<input type="submit" name="submit" value="Submit">
<p id="status" ></p>
</form>
</div>
<div class="col-md-3">
<div class="loginbox">
<?php
if ($isOwner == "yes") {?>
<h3>Welcome <?php echo $u; ?>!</h3>
<?php
if ($isOwner == "yes") {?>
<p>Last online: <?php echo $lastsession;?> </p>
<br /><br />
<?php
}
?>
<button class="btn btn-default" href="logout.php">Log Out</button>
<?php
}
?>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
</body>
<?php
include 'php_includes/footer.php';
?>
</html>
For some reason nothing is changing in the db when i hit submit, its so weird i am totally out of ideas...
But my knowledge is so limited that I can't see where the error lies and i am stuck.
Does anyone have an idea on how I could make this work?
Thanks in advance!
EQ
Why are you using a select query on users where you check on ID, Username and password. I assume every username has his own ID so you can just check on ID. Dont put password in the session.
change to:
<form action="" method="post">