PHP session_id() being overridden - php

I really don't know how to describes this, but here goes. I'm trying to make a Login for an online multiplayer game (cluedo to be exact) that is written using mainly the LAMP stack (php,js,etc), and creating a session when someone logs in/registers works for me and all and I even save it to a sql database, but it seems that as soon as a next user Logs in/registers the session id to the previous user is overridden to the new ones details. In other words they both now have the same session for some reason.
My Game LogIn basically:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="StyleSheet.css">
<meta charset="UTF-8">
<title>Game Setup</title>
</head>
<body>
<header>
<h1>Game Setup</h1>
</header>
//My form for user details and character select
<form name="Registration" id=Form1 action="Lobby.php" method="POST">
<fieldset>
<legend>Player information:</legend>
<label for="Pid">Player Name(required): </label><br>
<input autofocus type="text" id="Pid" name="Pid" placeholder="Player ID" required><br>
<label for="Avatar">Character(required):</label><br>
<select name="Avatar">
<option value="Miss White">Miss White</option>
<option value="Col Mustard">Col Mustard</option>
<option value="Miss Scarlet">Miss Scarlet</option>
<option value="Mr Green">Mr Green</option>
<option value="Madame Plum">Madame Plum</option>
<option value="Benjamin Blue">Benjamin Blue</option>
</select><br><br>
<input type="submit" value="Register">
</fieldset>
</form>
</body>
and the lobby (where I wait for someone to press game start or for more people to register)
<?php
session_start() ;
session_regenerate_id();
$_SESSION["UserName"]=$_POST['Pid'];
$_SESSION["Avatar"]=$_POST['Avatar'];
?>
<?php require 'DatabaseConnect.php' ?>
<?php include 'Users.php' ?>
<?php
$PlayerID = mysqli_real_escape_string($conn, $_POST['Pid']);
$PlayerChar = mysqli_real_escape_string($conn, $_POST['Avatar']);
$SesID = session_id();
$sql = "INSERT INTO users (UserName, Avatar, sessionID)
VALUES ('$PlayerID', '$PlayerChar','$SesID')";
if ($conn->query($sql) === TRUE) {
echo "Welcome $PlayerID , currently in Lobby: <br>";
$User = new Users();
$User->setUserName($_SESSION['UserName']);
$User->setAvatar( $_SESSION['Avatar']);
$User->isPlaying = false;
$_SESSION['User'] = serialize($User);
?>
<html>
<body>
<div id="Players"> </div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src ="Display.js"></script>
</body>
</html>
<?php
}
else {
if($conn->errno == 1062){//when a userName or Character already in use
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
$sql = "ALTER TABLE users AUTO_INCREMENT = ".$result->num_rows;
$conn->query($sql);
echo "<script type='text/javascript'>alert('ERROR :Username or Character already in use!')</script>";
echo" <script>
window.location = 'LogIn.php';
</script>";
}
}
?>
and then the Display.js runs in a loop until either 6 people connect or a user presses start. It also displays everyone currently waiting for a game by outputting the SQL database, but I don't think that code is necessary to add, but then when that's done I go to the Cluedo.php page and if I echo session_id() there on two different browsers(same machine) I get the same session_id()
<?php
session_start() ;
?>
<?php require 'DatabaseConnect.php' ?>
<?php include 'Users.php' ?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="StyleSheet.css">
<meta charset="UTF-8">
<title>Cluedo</title>
</head>
<body>
<?php
$User = unserialize($_SESSION['User']);
echo session_id();
?>
</body>
</html>
Also I'm using XAMPP and running it all locally at the moment so don't know if there's a problem there maybe?
Here's an example of my database with the saved values, the table saves unique sessions however when the session_id() is echoed at the Cluedo.php page it is always the last registered user:
UserTable

Related

How do I make a value not reset each page reload?

I am trying to show people their profiles from my database using PHP.
But every time a button is clicked I want the person_id ($which_person) to go up by 1 so the next person's profile is shown. I don't know how to do that because every time I click a button the page reloads so the variable "which_person" gets reset to 1.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="assets-putinhouse/css/style1.css" rel="stylesheet" type="text/css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Festive&display=swap" rel="stylesheet">
<title>Put people in a house</title>
</head>
<body>
<?php
include "db/connection.php";
$conn = create_connection();
$which_person = 1; //This resets to "1" every time the page reloads
$getSql = "select * from Person where person_id = 1;";
$data_labels = mysqli_query($conn, $getSql)->fetch_all(MYSQLI_ASSOC);
?>
<div class="pagesize">
<h1>Put people in a house</h1>
<img src="assets-putinhouse/images/create_account.png" alt="profilepic" class="image_person">
<?php
foreach($data_labels as $labels)
{
?>
<li class="labels" data-id="<?php echo $labels['person_id'];?>">
<?php echo $labels["firstname"] ?>
<br>
<br>
<?php echo $labels["secondname"] ?>
<br>
<br>
<?php echo $labels["gender"] ?>
<br>
<br>
<?php echo $labels["descriptie"] ?>
</li>
<?php
}
?>
<br>
<form method="GET">
<input type="submit" class="slytherin_button" value="Slytherin" name="slytherin_button_name">
<br>
<input type="button" class="gryffindor_button" value="Gryffindor" name="gryffindor_button_name">
<br>
<input type="button" class="hufflepuff_button" value="Hufflepuff" name="hufflepuff_button_name">
<br>
<input type="button" class="ravenclaw_button" value="Ravenclaw" name="ravenclaw_button_name">
<br>
<input type="button" class="nextperson_button" value="Go to next person">
<p class="text_firstname">Firstname: </p>
<p class="text_name">Name: </p>
<p class="text_gender">Gender: </p>
<p class="text_info">Info: </p>
<?php
if(isset($_GET['slytherin_button_name'])) {
onFunc($conn, $which_person);
}
if(isset($_GET['gryffindor_button_name'])) {
offFunc();
}
function onFunc($conn, $wich_person){
$sqlUpdate = "UPDATE Person SET slytherin = slytherin + 1 WHERE person_id like '$which_person';"; //this does the value "slytherin" of which_person go up by 1;
mysqli_query($conn, $sqlUpdate);
$wich_person = $wich_person + 1; //which person goes up by 1 so the next person will be shown but gets reset at the start
}
function offFunc(){
echo "Button is clicked";
}
?>
</div>
<script src="assets-putinhouse/js/script.js"></script>
</body>
</html>
´´´
(Untested) Instead of:
$wich_person = 1;
It seems you could do something like:
if (isset($_GET["id"]) {
$wich_person = (int)$_GET["id"] + 1;
}
else {
$wich_person = 1;
}
and then add the following to your form:
<form action="?<?php echo $wich_person ?>" method="GET">
...
</form>
And also, unless I'm mistaken it seems you've forgot to add </form> to your code.
In any event, this code should add the current ID to your URL every time you press submit, where then it gets increased by 1.
Edit: This is intended as a quick solution based on the code structure you provided, but upon reflection not sure if it's exactly what you're looking for. More robust solutions could be had, such as cookies or sessionStorage.

i keep coming back to login page in php

newbie here...
so yeah, i already tried searching all those page-related about my question, but im still stuck...
anyway, my problem is that i always keep getting back at my login page, which is my index.php
oh btw, im still using PHP version 4.4.8
here is my code for my problematic main page, main.php
<?php
session_start();
include '../config.php';
if(!isset($_SESSION['admin'])){
header("location:index.php");
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>KSP Setia Finance</title>
</head>
<body>
<h1>test page</h1>
</body>
</html>
and here is my login page code, which is index.php
<?php
session_start();
include '../config.php'; ?>
<!DOCTYPE html>
<html >
<head>
<title>Login Form</title>
</head>
<body>
<div class="login">
<h1>Login</h1>
<form action="login_act.php" method="post">
<input type="text" name="username" placeholder="Username" required="required" />
<input type="password" name="password" placeholder="Password" required="required" />
<button type="submit" name="login" value="Login" class="btn btn-primary btn-block btn-large">Log In</button>
</form>
</div>
<script src="js/index.js"></script>
</body>
</html>
since everyone asking, here my login_act.php, already inserted with session_start
<?php
session_start();
include('../config.php');
if(isset($_POST['login'])){
$user = mysql_real_escape_string(htmlentities($_POST['username']));
$pass = mysql_real_escape_string(htmlentities(md5($_POST['password'])));
$sql = mysql_query("SELECT * FROM user WHERE username='$user' AND password='$pass'") or die(mysql_error());
if(mysql_num_rows($sql) == 0){
echo 'User not found';
}else{
$row = mysql_fetch_assoc($sql);
if($row['level'] == 1){
$_SESSION['admin']=$user;
echo '<script language="javascript">alert("u are Login as Admin!"); document.location="index.php";</script>';
}else
echo 'sorry, u cant access this one';
}
}
?>
print value of $_SESSION on main.php and check if there is any key as 'username' and check login.php, what values are you storing in $_SESSION array
so i recently asking my friends, and here is the results:
all i need is just put those $SESSION_START above all, or make another php and link them all. so here my latest result that worked :
main.php
<?php
include 'access.php';
?>
<!DOCTYPE HTML>
<html>
<head>
<title>KSP Setia Finance</title>
</head>
<body>
<h1>test page</h1>
</body>
</html>
access.php
<?php
session_start();
if(!isset($_SESSION['admin'])){
echo '<script language="javascript">alert("you must Login!"); document.location="../index.php";</script>';
}
?>
and last, config.php
<?php
session_start();
mysql_connect("localhost","root","");
mysql_select_db("koperasi");
?>
i deleted that broken login_act.php, and making all the page i had to be linked directly with the access.php, which make it easier to manage the session. thank you to all that bear with my php problem and stupidity. hope this all gonna help those who still wandering and asking the same question.

session variables do not carry over to other pages

php session variables dont carry over from login page to home page. I can see the variables being saved in the session files on the web server with the correct values, but the second page doesn't see them. looks like it is openeing a new session every time.
The home page just redirects back to login page even after successful login. I do see that there have been quite a few questions in the forum on this issue. But most of them have the same solution. use session_start().
I've used session_start() on both pages.
My actual plan was to use MySQL db for saving session data. Login page would write session data to DB but the home page wouldnt read it. I'm trying to use local files now to eliminate any issue with the DB or my code for session management using DB. I still have the same issue with local files as well.
login.php
<?php
session_start();
if(isset($_POST['submit'])) {
//sanitize the data
$user = htmlspecialchars (stripslashes (trim ($_POST['user'])));
$password = htmlspecialchars (stripslashes (trim ($_POST['password'])));
$domain = htmlspecialchars (stripslashes (trim ($_POST['domain'])));
//validate user account from LDAP.
//once authorized, assign session variables and redirect to home page.
$_SESSION['accesslevel'] = "III";
$_SESSION['loggedin'] = "true";
$_SESSION['user'] = $user;
$_SESSION['name'] = $name;
header('location:home.php');
?>
`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Admin Login</title>
<link rel="stylesheet" href="css/login.css">
</head>
<body>
<div class="logincontainer">
<div class="login">
<h1>Login</h1>
<form action="<?php htmlentities(urldecode($_SERVER['PHP_SELF']));?>"
method="post">
<p><b></b><input type="text" name="user" value="" placeholder="ADM_5-
2-1" required autocomplete="off"></p>
<p><b> </b><input type="password" name="password" value=""
placeholder="Password" required autocomplete="off"></p>
<p><select name="domain">
<option value="DOMAIN">DOMAIN</option>
<option value="domain">NANET</option>
<option value="domain">EUNET</option>
<option value="domain">APNET</option>
<option value="domain">JPNET</option>
</select>
</p>
<p class="submit"><input type="submit" name="submit" value="Login">
</p>
</form>
</div>
</div><br>
<div class="error">
<?php //print_r($_POST);?>
<?php //var_dump($_POST);?>
<?php //echo $msg;?>
</div>
</body>
</html>
home.php
<?php
session_start();
if ((!isset($_SESSION['loggedin'])) or ($_SESSION['loggedin'] != true)) {
header ("location: login.php");
}
<<<<html (php uses session variable (name) for user profile menu>>>>>
?>
In your login.php, Change the $_SESSION['loggedin'] = "true"; to $_SESSION['loggedin'] = true;

page does not load when it is online php

I have a page which loads completely when it is on a local server i uploaded the site on the server and some of my pages won't load here is the example of my pages
should i do something more when it is on server?what is the common problems in this situations?
<?php include("includes/manager_session.php");?>
<?php require_once("includes/connection.php");?>
<?php
$message="";
if(isset($_POST['submit'])){
$uname= mysqli_real_escape_string($cnn,$_POST['uname']);
$pass= mysqli_real_escape_string($cnn,$_POST['pass']);
$hashed_pass=sha1($pass);
function redirect_to($location){
header('Location:'.$location);}
//checking for available users
$query="select manager_id,uname,hashed_pass from manager where uname='{$uname}' and hashed_pass='{$hashed_pass}'";
$result=mysqli_query($cnn,$query);
//if query returns a thing
if($result){
$num_rows = mysqli_num_rows($result);
//agar user peida shod
if($num_rows == 1){
$found_user=mysqli_fetch_array($result);
$_SESSION['manager_id']=$found_user['manager_id'];
$_SESSION['manager_pass']=$found_user['hashed_pass'];
redirect_to("manager_profile.php");
}
//useri peida nashod
else{
echo "can not find user";
redirect_to("manager_login.php");
}
}else{echo mysqli_error($cnn);}
}
?>
<html lang='fa'>
<head>
<meta charset="utf-8">
<title>
کیمیافکر
</title>
<link rel="stylesheet" type="text/css" href="stylesheets/login-form.css" />
</head>
<body>
<div id="wrapper">
<form name="login-form" class="login-form" action="" method="post">
<input type="text" name="uname"/>
<input type="pass" name="pass"/>
</div>
</body>
</html>
<?php
mysqli_close($cnn);
?>
all pages that has the session part comes up with nothing in it (on of the sessions) when it is online so what is the problem her am i missing something ?

PHP Session forms

I'm having some difficulty with PHP sessions.
The idea is to prevent users from accessing the administrator panel / pages by using the direct URL.
I have created a login form and that works well (login.php)
Once the username and password are correctly entered, the login form takes the user to the admin panel (admin.php)
However when I added the following script PHP to the (admin.php) page, it does not work.
When I enter the username and password on the login page, it always fails and re-directs me to login.php
The script on the admin.php is used to prevent users from accessing the page if
the session variable is not set
ANY help greatly appreciated :)
<link rel="stylesheet" type="text/css" href="admin_panel.css" media="all">
</head>
<body>
<form method="post">
<input type="text" name="user_name" placeholder="Username" required="required" />
<input type="password" name="user_pass" placeholder="Password" required="required" />
<button type="submit" class="btn btn-primary btn-block btn-large" name="login">Let me in.</button>
</form>
</div>
</body>
//===================================== login.php
<?php
include("includes.php");
if(isset($_POST['login'])) {
echo $user_name = mysql_real_escape_string ($_POST['user_name']);
echo $user_pass = mysql_real_escape_string ($_POST['user_pass']);
$encrypt = md5($user_pass);
$select_user = "select * from users where user_name= '$user_name' AND user_password = '$user_pass'";
$run_user = mysql_query($select_user);
if(mysql_num_rows($run_user)>0){ // what does this function DO?
$_SESSISON['user_name'] =$user_name;
echo "<script> window.open('admin_panel.php?logged=You have logged in','_self' )</script>";
}
else {
echo "<script> alert('Wrong details')</script>";
} }
?>
</html
// admin.php script ====================
<?php
session_start();
if(!isset($_SESSION['user_name'])) {
echo "<script>window.open('login.php','_self')</script>";
}
else { // ELSE CLOSED BOTTOM OF THE PAGE
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Admin page</title>
<link rel="stylesheet" type="text/css" href="admin_panel.css" media="all">
</head>
<body>
comments(0)
Insert New Post
Admin Logout
<?php
if(isset($_GET['insert_cat'])) {
include("insert_cat.php");
}
if(isset($_GET['insert_post'])) {
include("insert_post.php");
}
?>
</body>
<?php } ?> // CLOSE ELSE
</html>
It's better to use an authentication system from framework like Zend, Symfony, Laravel etc. than $_SESSION included in PHP.
To redirect user you can use function header()
for example:
header('Location: login.php');
it's important to set charset to 'UTF-8 without BOM' and it can't be any output before header()

Categories