I want to create a logout.php so that it remembers the username from the login.php.
I want to use $_GET method so that it gets the session username from login and when we logout, the cookie session is logged out. And if there is no set cookie session then there will be an error saying no ones were logged in so log gout doesn't work.
The login.php does login's the user and set cookie which I checked from the browser settings.
login.php
<?php
require"connection.php";
if (!isset($_POST['submit'])){
$user = $_POST['username'];
$password = $_POST['password'];
if ($user){
if ($password){
setcookie('username', '$user', time()+3600);
setcookie('password', '$password', time()+3600);
//make sure login info correct
$query = mysql_query("SELECT * FROM users WHERE username = '$user'");
$numrows = mysql_num_rows($query);
if ($numrows == 1) {
$row = mysql_fetch_assoc($query);
$dbuser = $row['username'];
$dbpass = $row['password'];
echo '<script type="text/javascript">alert("Welcome, '.$user.'. A cookie session has been created.");</script>';
}else{echo "Please enter valid username or password";}
}else {echo "Your password didn't match. Please try again";}
}else {echo "Your username didn't match. Please try again";}
}else {echo "Please enter username and password";}
?>
try something like this..
if(isset($_COOKIE['username']) && !empty($_COOKIE['username'])) {
// Bye $_COOKIE['username'], you are logged out.
setcookie('username', '', time() - 3600);
} else {
// no user logged in
}
Related
I have built a login php form for an internal website I'm building for our intranet. I am going to combine a few different websites together under one login system. I want to see how I could check if a user is logged in if they visit one of the url's directly and if they're not logged in then redirect them to the login page then after successfully logging in redirect back to the initial page.
I have logged their username and password into a cookie. I know this isn't secure, but again this is just an in house website on the companies intranet. So I don't need much security. The log in system is to just track what each user is doing.
Here's my login code, but now I need to figure out how to check if a user is logged in or not on separate web pages.
//get info from login form
if(isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$rememberme = $_POST['rememberme'];
$username = mysqli_real_escape_string($connection, $username);
$password = mysqli_real_escape_string($connection, $password);
//query users table
$query = "SELECT * FROM users WHERE username = '{$username}' ";
$select_user_query = mysqli_query($connection, $query);
if(!$select_user_query) {
die("Query failed" . mysqli_error($connection));
}
//loop through user info and assigning to variables
while($row = mysqli_fetch_array($select_user_query)) {
$db_id = $row['user_id'];
$db_username = $row['username'];
$db_password = $row['user_password'];
$db_firstname = $row['user_firstname'];
$db_lastname = $row['user_lastname'];
$db_role = $row['user_role'];
}
//validate username and password
if($username === $db_username && $password === $db_password) {
//create cookie to remember user
if(isset($rememberme)) {
//set cookie to last one year
setcookie('username', $_POST['username'], time()+60*60*24*365, '/', 'localhost');
setcookie('password', md5($_POST['user_password']), time()+60*60*24*365, '/', 'localhost');
} else {
//cookie expires when browser closes
setcookie('username', $_POST['username'], false, '/', 'localhost');
setcookie('password', md5($_POST['user_password']), false, '/', 'localhost');
}
//if user exists send to dashboard
$_SESSION['username'] = $db_username;
$_SESSION['user_firstname'] = $db_firstname;
$_SESSION['user_lastname'] = $db_lastname;
$_SESSION['user_role'] = $db_role;
header("Location: ../dashboard.php ");
} else {
header("Location: ../index.php");
}
}
Here is how to check if a user is logged in and then redirect them to the page they first visited.
First check to see if a user is logged in:
<?php
session_start();
if(!(isset($_SESSION['username'])))
{
header("Location: index.php");
}
?>
Then include that file in all of your web pages you will be using. Also, create a session for the URL. This will go at the top of your page:
<?php include "includes/login-check.php"; ?>
<?php $_SESSION['url'] = $_SERVER['REQUEST_URI']; ?>
<?php ob_start(); ?>
Then right in the body of the HTML add this:
<input type="hidden" name="redirurl" value="<? echo $_SERVER['HTTP_REFERER']; ?>" />
Then within your login file check for the URL session:
//check to see what page user first visited
if(isset($_SESSION['url'])) {
$url = $_SESSION['url'];
} else {
$url = "../index.php";
}
//redirect user to page they initially visited
header("Location: $url");
That should fully answer your question.
Create a file which you should include at the top in every file of your system and add the following code
session_start();
if(!(isset($_SESSION['username'])))
{
header("Location:login.php")
}
Hello im completely new to php and my question is how can i echo out the username of the person who has logged in, on the page they get sent to after logging in successfully?
ive got the login system working and everything but not sure where to write the session stuff etc.
This is my login2a.php
$username = $_POST['username'];
$password = $_POST['password'];
$conn = mysqli_connect('localhost', 'root', '', 'assign02');
$username = mysqli_real_escape_string($conn, $username);
$query = "SELECT password, salt
FROM members
WHERE username = '$username';";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) == 0) // User not found. So, redirect to login_form again.
{
header('Location: login.html');
}
$userData = mysqli_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );
//check to see if the password is wrong if wrong redirect user to login forma again and if correct redirect to
if($hash == $userData['password'])
{
header('Location: signed_in.php?username = $username ');
//header('Location: login.html');
}else{ // Redirect to home page after successful login.
//header('Location: signed_in.php?username=$username');
header('Location: login.html');
}
?>
This is the page that i want their username to be displayed, this is just some parts of the website because its too big, what ive echoed is completely wrong i know but hope someone could help me with this problem. This page is the signed_in.php
<div class="layout-978">
<img id="content_background" src="Images/Background.png" />
<div class="main_content">
<div id="top_sellers_title">
<div class="col7">
<!--username displayed to show logged in-->
<?php
if (isset($_SESSION['username'])){
echo "<div id=\"welcome_msg\"> $username </div>";
}
?>
Modify this in your login page and don't forget to use session_start(); at the very beginning of your login page.
if($hash == $userData['password'])
{
$_SESSION['username'] = $username;
header('Location: signed_in.php');
//header('Location: login.html');
}
Then in signed_in.php page, to display the username just do the following
<?php
if(isset($_SESSION['username'])) echo '<div id="welcome_msg">'.$_SESSION['username']. '</div>';
?>
Use session_start() on top of both login2a.php and signed_in.php.
In your login2a.php file where you've successfully authenticated a user, create a session variable named username and assign the username you've passed to the query to that session variable. Here's how
.
.
.
if($hash == $userData['password'])
{
$_SESSION['username'] = $username;
// Continue with your code
}
Hope my answer helps
I have a this login script:
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
include 'includes/connect.php';
$username = mysqli_real_escape_string($con, $username);
$query = "SELECT password, salt
FROM member
WHERE username = '$username';";
$result = mysqli_query($con, $query);
if(mysqli_num_rows($result) == 0)
{
header('Location: login.html');
}
$userData = mysqli_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );
$_SESSION['username']=$username;
if($hash != $userData['password'])
{
header('Location: login.html');
}else{ // Redirect to home page after successful login.
$_SESSION['username']=$username;
header('Location: stats.php');
}
?>
then this is stats.php:
<?php
session_start();
if(!isset($_SESSION['username'])){
header("Location:register.html");
}
?>
and under this is my html 5 document.
however it doesnt matter if im logged in or not and it still allows me to access stats.php
You are not storing any session value so if condition will always fail.
So Add
$_SESSION['username'] = $userData['username'];
inside login.php.
You haven't set a session yet. That's why you are getting redirected.
Set a session here on your login.php code like this
$userData = mysqli_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );
//Set here like this
$_SESSION['username']=$username; // or whatever you have
you always set the username sesion var . Imagine this situation:
I wanna get the users stats , i only need test login with user and try again with other username .
if i write success one time the user name without the correct password , the result of query get a num_Rows > 0 , because the username is ok .
the next step you are going to test the password but between generate hash and test hash you init the sesion.Now my password is wrong but i get init sesion with the username. ????
if know the url to stats i could acces by http url and see the info that isn t mine.
Your structure to login has got a big bug.
You need insert the set session var inside check password. before header ... stats.php and remove the others occurs on login.php document.
you can make this to logout on logout.php : sesion_Destroy()
I'm not very good at PHP and I have a little problem. I've been playing around with this script.
And I can't for the life of me figure out how to echo the username of a logged in user.
I tried to print all the information of the session like this:
var_dump($_SESSION)
but I just got the hashed password and the userlevel int.
Can someone maybe help me here? I just want to be able to echo the username.
You have to store the username in the session for it to be available on another page load, currently the script only stores these values in the session;
$_SESSION['loggedin'] = $row[$this->pass_column];
$_SESSION['userlevel'] = $row[$this->user_level];
What you have to do is add the $username to the session that is passed into the login function, like below;
$_SESSION['username'] = $username;
The username will now be stored in the session with the key username.
To be able to use it on another page, make sure that before attempting to use it you initiate the session by calling the function session_start().
Basically, just write it inside like
session_start();
echo $_SESSION['username'];
or
echo $_SESSION['password'];
A brief explanation of how sessions work.
first you start the session and assign any value to a session ex:
session_start();
$_SESSION['username'] = 'john';
then echoing works like:
echo $_SESSION['username']; // will echo out 'jonh'
note session_start() must be shared in-between the pages you want to use the session
You have session_start(); on top ?
In the login function you should write the username to the session after a successful login.
//instantiate if needed
include("class.login.php");
$log = new logmein();
$log->encrypt = true; //set encryption
if($_REQUEST['action'] == "login"){
if($log->login("logon", $_REQUEST['username'], $_REQUEST['password']) == true){
//do something on successful login
$_SESSION['username'] = $_REQUEST['username'];
}else{
//do something on FAILED login
}
}
<?php
include('db.php');
session_start();
$name=$_POST['name'];
$password=$_POST['password'];
echo $sql="SELECT * FROM register WHERE (name='$name' OR email='$name') AND password='$password'";
$result=mysqli_query($conn,$sql);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0)
{
$_SESSION['user']=mysqli_fetch_assoc($result);
$row = $_SESSION['user'];
$role = $row['role'];
if($role == 1)
{
header('location:usermanagement.php');
}
else{
header('location:user.php');
}
}
else
{
echo "Wrong Username or Password";
header('location:login.php');
}
$conn->close();
?>
So i'm writing a simple login script and I ran into some problems. I was able to create the login.php file that works with this dashboard.php file below. Let me describe the scenario: User come into the main page, which is the login page. Enters username and password. If entered correctly user will see the output "dashboard succesfull". If entered wrongly it will redirect them to loginfailed.php. Problem is that the browser does not remember that the user has already been logged in. If I re-enter this page, it will directly goes to loginfailed.php. So my obivous n00b question here is......is there a way to make the browser remember that the user has already been logged in?
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
$dblink = mysql_connect("localhost", "root", "");
mysql_select_db("user",$dblink);
$sql = "select * from members where username = '$username' and password = '$password'";
$result = mysql_query($sql) or die ( mysql_error() );
$count = 0;
while ($line = mysql_fetch_assoc($result)) {
$count++;
}
if ($count == 1) {
$_SESSION['loggedIn'] = "true";
echo "<a href='dashboard.php'>dashboard succesfull</a>";
} else {
$_SESSION['loggedIn'] = "false";
header("Location: loginfailed.php");
}
?>
Sure. You just need to put, at the top of the page but below session_start(), something like:
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] == 'true') {
# do something. maybe redirect and then exit?
}
Also, I'd suggest using a session name and escaping the username and password before putting them in your SQL.