how to get unique session numbers in php - php

I am trying to create two separate sessions- one for if the user is admin and another if the user is author. $type stored type as enum (can be either author or admin). But, I am not getting unique session id's for my sessions. I am new to PHP and MySQL . can somebody tell me where the error is in my code.
Please help
<?php
session_start();
?>
<?php
include("dbconnect.php");
$con= new dbconnect();
$con->connect();
//create and issue the query
$sql = "SELECT type FROM users WHERE username = '".$_POST["username"]."' AND password = PASSWORD('".$_POST["password"]."')";
$result = mysql_query($sql);
//get the number of rows in the result set; should be 1 if a match
if (mysql_num_rows($result) == 1) {
$type_num=0;
//if authorized, get the values
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
}
if($type == "admin")
{
$_SESSION['type']=1;
$u = 'welcome.php';
header('Location: '.$u);
}
else
{
$_SESSION['type']=$type_num;
$u = 'welcome.php';
header('Location: '.$u);
}
}
else {
//redirect back to loginfailed.html form if not in the table
header("Location: loginfailed.html");
exit;
}
?>
welcome.php is as follows:
<?php
session_start();
?>
<html>
<body>
<h2>Welcome to SOD73.</h2>
<?
if($_SESSION['type']==1){
echo "You are of the usertype Admin and your session id is ";
echo session_id();
session_destroy();
}
else {
echo "You are of the usertype Author and your session id is ";
echo session_id();
session_destroy();
}
?>
</body>
</html>

You have to use session_regenerate_id() before call session_destroy() in the file welcome.php

Related

Can't Tranfer Session ID When trying to allow access to a page when logged in

Hello I am trying to create a login page where the user enters an access code, if correct it will redirect the user to the main index.php, I am trying to only allow access to the index.php page if the user has logged in, but it wont display when logged in.
Phpmyadmin:
Login.php Code
<?php
include("DB.php"); //database connection
session_start();
if(isset($_POST["login"]))
{
if(empty($_POST["code"]))
{
echo '<script>alert("Code Feild is Empty")</script>';
}
else
{
$code = mysqli_real_escape_string($connect, $_POST["code"]);
$query = "SELECT * FROM login";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
if(password_verify($code, $row["Code"]))
{
//return true;
header("location:index.php");
}
else
{
//return false;
echo '<script>alert("Wrong User Details")</script>';
}
}
}
else
{
echo '<script>alert("Wrong User Details")</script>';
}
}
}
include("loginpage.html"); //log in forum
?>
Index.php code
<?php
session_start();
if(isset($_SESSION["ID"])){
?>
//website code
<?php
} else{
echo "You Need To Enter the Access Code to enter the site";
}
?>
I fixed it by adding
$_SESSION['auth'] = 1 ;
to login.php when the password gets checked.
then on index.php i added
if(isset($_SESSION["auth"])){
this fixed my problem

How to redirect to the same page with username after login in PHP

I want to redirect on the same page after login, but I need conditions like if username and password come from index.php then page will redirect to dashboard.php, else it will redirect on the same page (exmple.php).
login.php:
<?php
include ('include/connection.php');
if (isset($_POST['loginform'])) {
session_start();
$email = trim(mysql_escape_string($_POST['email']));
$passwords = trim(mysql_escape_string($_POST['pwd']));
$password = md5($passwords);
$verify_query = "SELECT * FROM end_user WHERE (email='$email' AND password='$password')";
verify_result = mysqli_query($con, $verify_query);
if(!$verify_result){
echo '<h2>Couldnot Process your request Please try to login after some time. </h2>';
}
if (#mysqli_num_rows($verify_result) == 1) {
$_SESSION = mysqli_fetch_array($verify_result, MYSQLI_ASSOC);
header("Location: dashboard.php");
}
else {
echo '<h2 style="color:#CC3300;">Incorrect Credentials, You need to register Here</h2>';
}
mysqli_close($con);
}
?>
index.php:
session_start(); // starts the session
$_SESSION['url'] = $_SERVER['REQUEST_URI'];
And I used the same code in example.php, so that I can get the URL in $_SESSION.
From Your index.php login form pass an hidden field like
<input type="hidden" name="extrafield" value="fromindex">
Then
<?php
include ('include/connection.php');
if (isset($_POST['loginform'])) {
session_start();
$email = trim(mysql_escape_string($_POST['email']));
$passwords = trim(mysql_escape_string($_POST['pwd']));
$password = md5($passwords);
$verify_query = "SELECT * FROM end_user WHERE (email='$email' AND password='$password')";
$verify_result = mysqli_query($con, $verify_query);
if(!$verify_result){
?>
<?php
echo '<h2>Couldnot Process your request Please try to login after some time. </h2>';
}
if (#mysqli_num_rows($verify_result) == 1)
{
$_SESSION = mysqli_fetch_array($verify_result, MYSQLI_ASSOC);
if(isset($_POST['extrafield']) == 'fromindex'){
header("Location: dashboard.php");
} else {
header("Location: exmple.php");
}
}else
{
?>
<?php echo '<h2 style="color:#CC3300;">Incorrect Credentials, You need to register Here </h2>';
}
mysqli_close($con);
}
?>

PHP echo display name not user

I can login succesfuly and the user can be displayed... But im doing something wrong here, i can't display the name of the user. Here is the form I tried:
<?php
include("dbconfig.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password received from loginform
$name=mysqli_real_escape_string($dbconfig,$_POST['name']);
$username=mysqli_real_escape_string($dbconfig,$_POST['username']);
$password=mysqli_real_escape_string($dbconfig,$_POST['password']);
$sql_query="SELECT id FROM user WHERE username='$username' and password='$password'";
$result=mysqli_query($dbconfig,$sql_query);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
$count=mysqli_num_rows($result);
// If result matched $username and $password, table row must be 1 row
if($count==1)
{
$_SESSION['login_user']=$username;
header("location: home.php");
}
else
{
$error="Useri ose passwordi gabim!";
}
}
?>
and here is the desplay code:
<?php
if(!isset($_SESSION['login_user']))
{
header("Location: login.php");
}
else
{
$name=$_SESSION['login_user'];
?>
Welcome <?php echo $name;?>
<?php
}
?>
What am I missing can anyone help me out? Thanks!
From what I understand, you're trying to display the user's name and not the username in the welcome message.
First of all, please see that you are not even retrieving the user's name. So, you need to fetch that along with the id.
Considering the field is "name" in your database.
You can modify your query:
$sql_query="SELECT id, name FROM user WHERE username='$username' and password='$password'"; // Add name along with id
$result = mysqli_query($dbconfig,$sql_query);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
if($count==1) {
$_SESSION['User']['username'] = $username; // Change this
$_SESSION['User']['name'] = $row['name']; // Add this
header("location: home.php");
} else {
/* Other code */
}
Now, your display code:
<?php
session_start();
if(!isset($_SESSION['User'])) {
header("Location: login.php");
} else {
$name = $_SESSION['User']['name'];
?>
Welcome <?php echo $name;?>
<?php } ?>
Hope this helps.

After Logout don't navigate to the page visited before

How to create a session variable, and once logout is successful no need to navigate to the page that is visited before.
The Login.php and logout.php pages are provided below:
Login.php
require( 'dbConfig.php');
session_start();
$msg = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST["userid"];
if ($name == '' ) {
$msg = "You must enter all fields";
}
else
{
$sql = "SELECT * FROM user WHERE userid = '$name' ";
$query = mysql_query($sql);
if ($query === false) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($query) > 0) {
$_SESSION['userid'] = $name;
header('Location: teams.php');
exit;
}
$msg = "Username do not match";
}
}
?>
Logout.php
<?php
session_start();
if(session_destroy())
{
header("Location: index.php");
}
?>
ISSUE : After successful logout the page is navigating to the page visited before.
Any help is appreciated, thanks in advance.
In your logout.php page, instead of if condition, simply write:
session_destroy();
So your page code would be :
<?php
session_start(); // not compulsory to write
session_destroy();
?>

Get values of userAccount upon Login

I am creating a login system for my website. I want to grab the user's userID (aka a primary key out of the database) to use when they log in.
I have 3 files I'm using:
/index.php - that is basically the login form with a username and password fields. It contains this php code:
<?php
session_start();
require_once('../inc/db/dbc.php');
?>
Once form is submitted, it goes to check_buyer.php (/check_buyer.php)
<?php
session_start(); #recall session from index.php where user logged
require_once('../inc/db/dbc.php');
$connect = mysql_connect($h, $u, $p) or die ("Can't Connect to Database.");
mysql_select_db($db);
$LoginUserName = $_POST['userName'];
$LoginPassword = mysql_real_escape_string($_POST['userPass']);
//connect to the database here
$LoginUserName = mysql_real_escape_string($LoginUserName);
$query = "SELECT uID, uUPass, dynamSalt, uUserType FROM User WHERE uUName = '$LoginUserName';";
$result = mysql_query($query);
if(mysql_num_rows($result) < 1) //no such USER exists
{
echo "Invalid Username and/or Password";
}
$ifUserExists = mysql_fetch_array($result, MYSQL_ASSOC);
function isLoggedIn()
{
if(isset($_SESSION['valid']) && $_SESSION['valid'])
#header( 'Location: buyer/' ); # return true if sessions are made and login creds are valid
echo "Invalid Username and/or Password";
return true;
}
function validateUser() {
$_SESSION['valid'] = 1;
$_SESSION['uID'] = (isset($ifUserExists['uID'])) ? $ifUserExists['uID'] : null;
echo 'sessuID: '.$_SESSION['uID'];
$_SESSION['uUserType'] = 1; // 1 for buyer - 2 for merchant
}
$dynamSalt = $ifUserExists['dynamSalt']; #get value of dynamSalt in query above
$SaltyPass = hash('sha512',$dynamSalt.$LoginPassword); #recreate originally created dynamic, unique pass
if($SaltyPass != $ifUserExists['uUPass']) # incorrect PASS
{
echo "Invalid Username and/or Password";
}
else {
validateUser();
}
// If User *has not* logged in yet, keep on /login
if(!isLoggedIn())
{
header('Location: index.php');
die();
}
?>
If the credentials are valid, the user is sent to login_new/buyer/index.php
<?php
session_start();
if($_SESSION['uUserType'] != 1) // error
{
die("
<div class='container_infinity'>
<div class='container_full' style='position:static;'>
<img src='img/error/noAccess.png' style='float:left;' /> <br />
<h2>403 Error: You may not view this page. Access denied.</h2>
</div>
</div>
");
}
function isLoggedIn()
{
return ($_SESSION['valid'] == 1 && $_SESSION['uUserType'] == 1);
}
//if the user has not logged in
if(!isLoggedIn())
{
header('Location: ../index.php');
die();
}
?>
<?php
if($_SESSION['valid'] == 1 && $_SESSION['uUserType'] == 1){
#echo "<a href='../logout.php'>Logout</a>";
echo 'buyerid: '.$_SESSION['uID'];
require_once('buyer_profile.php');
}
else{
echo "<a href='../index.php'>Login</a>";
}
?>
The problem is, when I login with valid credentials it sends me to login_new/buyer/index.php with the account, but is not outputting the buyer ID using the code echo 'buyerid: '.$_SESSION['uID']; what am I doing wrong here?
Try commenting the header() redirect and echo the $_SESSION['uID'] right after you set it in function validateUser() to see if the session data is actually set right there

Categories