Running PHP Even User Log Out - php

I have a php file that user can login and logout. I'm currently running on it. I want to show a number when user login.
for example user A login and redirect to userpage.php, I want to show a number like 1,2,3 and still count. I already created this one.
But the problem is when user log out and try to login again, the number is not continue? it become 1,2,3 again.
Is it possible to have a number still counting even when the user logout?
thanks

Update: as you want the numbers to get incremented in background irrespective of login/logout, use cron jobs see this for more info
You have to use counter for each user login which has to be persistent so, save this counter in DB whichever you are using for your application.
Flow would go like:
Check login > Login Succeeded > Fetch current login counter from db
for this specific user > Increment by one > Save it back to DB
General implementation in php would be like (Considering username is always unique)
Note: Below code is not tested
.
.
.
$stmt = $con->prepare("SELECT user_id, username, password, login_count FROM users WHERE username=? AND password=? LIMIT 1");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($user_id, $username, $password, $loginCount);
$stmt->store_result();
if($stmt->num_rows == 1) //To check if the row exists
{
if($stmt->fetch()) //fetching the contents of the row
{
$_SESSION['Logged'] = 1;
$_SESSION['user_id'] = $user_id;
$_SESSION['username'] = $username;
$loginCount = $loginCount+1; //increment login counter by 1
//this should be default as 0 when a new user register
//Now save it back to DB using update query
$Updatesql = "UPDATE Table SET loginCount=? WHERE username=?";
$Updatestmt = $con->prepare($Updatesql);
$Updatestmt->bind_param('ds', $loginCount,$username);
$Updatestmt->execute();
if ($Updatestmt->error) {
//Update failed
echo "FAILURE!!! " . $Updatestmt->error;
}
else echo "Updated {$Updatestmt->affected_rows} rows"; //Update succeeded
$Updatestmt->close();
exit();
}
}
else {
echo "INVALID USERNAME/PASSWORD Combination!";
}
$stmt->close();

To achieve this result you cant try logging the login time and logout time and take difference between time and and display the number of seconds have passed since first login.
Step 1: Log the first login time and save it in database.
Step 2: Log the logout time and save it in database.
Step 3: if you want the time elapsed for first login and last logout then calculate the time difference in seconds.
if you want the time elapsed form last login then calculate the time difference between last login and current time.
Step 4: Display the time elapsed on the HTML user page.

Related

How to make a generated code expire after a few times of entering (PHP)?

I have been trying to write a code in PHP that generates a random code, stores it in the database and asks the user to enter it. if the code is entered more than 3 times, the code needs to be expired. this is my code:
<?php
include("ProcessCode.php");
$con = mysqli_connect("localhost","root","") ;
if(mysqli_select_db($con,"login"))
{
echo 'database selected' ;
}
$rand=rand();
echo $rand ;
$sql = "INSERT INTO random (number) VALUES ('$rand') " ;
if(mysqli_query($con,$sql))
{
echo 'inserted' ;
}
?>
$CodeCheck=$_POST['code'];
//Establishing Connection with server
$conn = mysqli_connect("localhost", "root", "");
//Selecting Database
$db = mysqli_select_db($conn, "login");
//sql query to fetch information of registerd user and finds user match.
$query = mysqli_query($conn, "select * from random WHERE number='$CodeCheck'");
$rows = mysqli_num_rows($query);
if (mysqli_num_rows($query) > 0)
{
echo " Code exists already.";
}
if($rows == 1)
{
header("Location: Success.php");
}
else
{
$error = " Code is Invalid";
echo $error;
}
could you please explain how to implement the expiry part?
in your table you could have a field for count. When use login and login is wrong, add + 1 to your count. When user login successfuly, reset the count. If count meet +3, reset the code.
i understand from your question that you need the logic on how to make the random_code expired after inserting from interacted users on your website 3 times ,assuming that , as long as the code is not expired he will be able to do his inserts and you may load it on your page .
i would do that through database queries .
Please follow this instruction listed below
instructions :
while your php page generate the random code , you may store it in database table with a auto reference key , for instance ,
assuming that you have randomly generated a code as below :
"Some random code here"
the above code which was generated by your php page have load it from mysql table called Random_Generated_Code , i would go to edit this table and add new field in it and call it generated_Code_Reference_Key ( could be auto serial number ) to avoid any duplication as well make additional field called Expire_Flag which we are going to use later.
so once your page have loaded the above example code , you should retrieve the generated_Code_Reference_Key along with it and keep it in hidden variable on your page
it should be loaded on the page based on expire_Flag value as a condition
select generated_code from Random_Generated_Code where expire_flag = ""
now once the user try to insert that generated code , in each time he insert it define another table in your database lets call it ( inserted_Codes_by_users) and store in it the username of whoever is doing that on your website as well you have to store the generated_Code_Reference_Key which we are storing in hidden variable as mentioned earlier to indicate which code was used while inserting.
now during page load or any event you want you can find expired code by make select statement from the inserted_Codes_by_users table
select count(generated_Code_Reference_Key) as The_Code_Used_Qty from inserted_Codes_by_users where username = username_of_that_user
so you can get how many times this user have inserted this specific generated_random_Code
retrieve result of the query in a variable and to make sense lets call it The_Code_Used_Qty and make if condition on page load event or any event you like
if The_Code_Used_Qty = 3 then
fire update statement to first table which loaded that random generated code
and update the expire_flag field for that code (Expired) based on reference_key
update Random_Generated_Code set expire_Flag = "expired" where generated_Code_Reference_Key = "generated_Code_Reference_Key" << the one u stored in hidden variable
end if
so now that will get you directly to the point of why we are loading random_generated_code table first time with that condition expire_flag = ""
as it will only retrieve the codes which is not expired .
hopefully this will help you to achieve what you want .
good luck and let me know if you need any help or if you face any confusion while reading my answer.
Good luck .

Having some issues on PHP login script

This code below is having a problem..
<?php
session_start();
include_once("databaseConnect.php"); // This creates $database by mysqli_connect().
if(isset($_SESSION['id'])){ // checking if user has logged in
$id = $_SESSION['id'];
$sql = "SELECT * FROM tableName WHERE id = '$id'";
$query = mysqli_query($database, $sql);
$row = mysqli_fetch_row($query);
$activated = $row[1]; // This is where I store permission for the user
if(!($activated == 2 || $activated == 3)){ // if the user has not enough permission:
header("Location: http://myWebsiteIndex.php");
}
// code for users
}else{
header("Location: http://myWebsiteIndex.php");
}
?>
I have a user who has 3 for $activated, so they should be able to access.
When a user logges in to my website, it sets $_SESSION['id'] to store the id of the user.
This session variable is used to check if the user is logged in.
However, when I run the code several time, sometimes it works and sometimes it doesn't. Sometimes, it will run the '// code for users' part, and sometimes it will just redirect to my 'http://myWebsiteIndex.php'.
How would I fix this??
First, try changing the headers to different redirects. What part of the conditional is failing? If the $_SESSION['id'] is not properly set it will redirect to the same url as it will redirect to when the user does not have proper permissions. Changing one of them will show you what part is executed when you encounter the behaviour.
Second, the comment from Barth is helpful. The if(!($activated == 2 || $activated == 2)) evaluation seems incorrect. You are evalutaing for (not) 2 or 2.
Third, take note of your session data and compare when the redirect happens to when it does not.

Only let a certain group display page

I want to make a certain page viewable only to a certain group of a database. My SQL table is set up as:
Table: DD_users
Columns: id | group | username | paraphrase | guild | level | salt
This is the code I am trying to use:
// First we execute our common code to connection to the database and start the session
require("common.php");
// At the top of the page we check to see whether the user is logged in or not
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
header("Location: /DD/index.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to /DD/index.php");
}
if($_SESSION['user']['group'] == '0')
{
// Destroy the session to make them log in again.
unset($_SESSION['user']);
// If they are not, we redirect them to the login page.
header("Location: /DD/index.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to /DD/index.php");
}
// Everything below this point in the file is secured by the login system
When I try this, will let any user group (0, 1, and 2) access the page when I only want groups 1 and 2 to access the page.
You don't have any code to check if they are in groups 1 or 2. Just wrap the code around an if.
if($_SESSION['group'] == '1' || $_SESSION['group'] == '2')
Also make sure $_SESSION['group'] is set using isset. If it is not set then the last if will fail.
Got it working another way:
require('common.php');
$charname = $_SESSION['user']['username'];
$query = "SELECT adminaccess, guild, username, class, level, active, canRegister, canNews, canActive
FROM DD_users
WHERE username = ?";
try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$stmt->execute(array($charname));
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
//print_r($rows);
$group = $rows['0']['adminaccess'];
$guild = $rows['0']['guild'];
$username = $rows['0']['username'];
$class = $rows['0']['class'];
$level = $rows['0']['level'];
$accessAdmin = $rows['0']['adminaccess'];
$canRegister = $rows['0']['canRegister'];
$canNews = $rows['0']['canNews'];
$canActive = $rows['0']['canActive'];

Trying to get a login to last 10 days

I'm using a login system, and I'm trying to keep the user logged in for 10 days unless they specifically log out. I thought by using session_set_cookie_params('864000'); that it would make the user stay logged in for 10 days. But it's not doing that, at least in Chrome. The user only seems to be logged in for the standard 20-30 minutes before being automatically logged out. When I check the cookies in Chrome, there are two PHP Session cookies listed for my URL with expiration dates 10 days into the future. But this seems to be unrelated to the login variables. Most of the relevant code should be below.
Any idea why the user is not logged in for 10 days?
Thanks in advance,
John
In the index file, I have the following:
require_once "header.php";
//content
include "login.php";
In the header.php file, the following is included:
session_set_cookie_params('864000');
session_start();
In the login.php file, the following is included:
if (checkLogin($_POST['username'], $_POST['password']))
{
show_userbox();
}
Here is the function "checkLogin":
function checkLogin($u, $p)
{
global $seed; // global because $seed is declared in the header.php file
if (!valid_username($u) || !valid_password($p) || !user_exists($u))
{
return false; // the name was not valid, or the password, or the username did not exist
}
//Now let us look for the user in the database.
$query = sprintf("
SELECT loginid
FROM login
WHERE
username = '%s' AND password = '%s'
AND disabled = 0 AND activated = 1
LIMIT 1;", mysql_real_escape_string($u), mysql_real_escape_string(sha1($p . $seed)));
$result = mysql_query($query);
// If the database returns a 0 as result we know the login information is incorrect.
// If the database returns a 1 as result we know the login was correct and we proceed.
// If the database returns a result > 1 there are multple users
// with the same username and password, so the login will fail.
if (mysql_num_rows($result) != 1)
{
return false;
} else
{
// Login was successfull
$row = mysql_fetch_array($result);
// Save the user ID for use later
$_SESSION['loginid'] = $row['loginid'];
// Save the username for use later
$_SESSION['username'] = $u;
// Now we show the userbox
return true;
}
return false;
}
Looks more likely that your server is discarding the sessions -- you'd need to store pertinent information in a local friendly database and load from there, based on the cookies as appropriate

Getting all info of the logged in user? PHP

HI
Could I fetch ALL the info from the user when he/she login and store it in sessions instead of having this piece of code on top of all pages to get username, email etc of the logged in user?
$userq = mysql_query("SELECT * FROM users WHERE id = {$_SESSION['id']}");
$auth_user = mysql_fetch_assoc($userq);
Login.PHP
$sql = mysql_query("SELECT id FROM users
WHERE username = '$username' AND password = '$password'");
if (mysql_num_rows($sql) < 1) {
echo "Wrong username/password";
} else {
$_SESSION['id'] = mysql_result($result, 0, 'id');
header("Location: index.php");
}
Yes you (probably) could.
A couple of things to consider, though :
you might want to keep in session only what you need (to not have a giant session file with lots of useless data)
if the user updates his profile, you'll have to store the new data both in database, and in session -- which means a bit more works on the "edit profile" page.
if some other user (like an admin) edits a user's profile, you won't be able to change the session data of that user, and the updates will be loaded from database into the session only the next time the user logs in.
if this is something that happens frequently, you might want to refresh the data from databse every couple of minutes (but it's rarely the case on a "normal" website)
yeah, instead of getting just the id in the query, you get everything:
$sql = mysql_query("SELECT * FROM users
WHERE username = '$username' AND password = '$password'");
if (mysql_num_rows($sql) < 1) {
echo "Wrong username/password";
} else {
$_SESSION['userdata'] = mysql_result($result, 0);
header("Location: index.php");
}

Categories