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;
Related
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
I have created a webpage (lets call the root as main.php) and decided to put a login on top of it (file index.php). The login works fine, but the problem is this. If I type the address of the page (main.php) directly in the browser, it is opened.
Is there any way to prevent opening the page unless I go through the login?
In case it is relevant, this is the login code:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="/css/style.css">
</head>
<body>
<div class="login_container">
<div id="login-form">
<h3>Login</h3>
<fieldset>
<form action="checklogin.php" method="post">
<input name="username" type="text" required placeholder="Username">
<input name="password" type="password" required placeholder="*******">
<input type="submit" value="Login">
</form>
</fieldset>
</div>
</div>
</body>
</html>
and it directs to :
<?php
ob_start();
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
$username = pg_escape_string($username);
$password = pg_escape_string($password);
if($username == "username" && $password == "password"){
$_SESSION['username']="username";
$_SESSION['password']="password";
header("location:main.php");
}
else header("location:index.php");
ob_end_flush();
?>
You need to check, on every request that requires a login, that the user is logged in and is authorized.
A good way of looking at this is seeing the request URL as part of the input to your program. Just like the cookies and GET/POST parameters are input.
main.php will either return a page with data or a request for login.
Sure.
Check if the user is currently logged on when they access the page using php sessions if they aren't logged on send an error, or redirect them elsewhere.
So I'm trying to make a secure homepage that checks if you're logged in by getting the text that the user entered on the login page and checking they are correct (so you can't just do www.website.com/home.php to bypass login)
<body onload="OpenPhp()">
<form name="GetLogin" action="GetIfLoggedIn.php">
</body>
The script is :
<script>
function OpenPhp(){
document.GetLogin.submit();
}
</script>
the php script should include the username and password vars from the login script and re-check them
<?php include "Login.php";
if($Username === "*****" and $Password === "******"){
// Return To Page
}else{
//Go Back To Login Page
}
?>
But the include statement makes the home page inaccessible. Every time I go to the home page it just sends me back to the index.html page.
Are there any better ways to secure a web page? If so please tell me or explain why this doesn't work,
For securing a webpage i encourage you to work with sessions.
You use one script (lets call it login.php) to allow the user to login. If the login is correct you store the username as a session variable.
In your secured pages you just check if the username is set in the session.
In all your scripts you need to execute session_start(); to make the $_SESSION superglobal variable available.
For logging out you can just destroy the users session using session_destroy();
Examples:
login.php:
session_start();
function isValidLogin($username_, $password_)
{
if($username_=='sam' && $password_=='secret')
return true;
return false;
}
if(isValidLogin($username, password))
{
$_SESSION['username']=$username;
}
your_secured_page.php:
session_start();
if(isset($_SESSION['username'))
{
// display page
}
else
{
// redirect to login.php
}
logout.php
session_destroy();
Another tutorial i found:
http://www.formget.com/login-form-in-php/
You Might Wanna Use This.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Fetch Array Trick</title>
</head>
<body>
<?php
$con = mysqli_connect("localhost","root","","lesson") or die("Connection Not Established");
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$username = $_POST['username'];
$password = $_POST['password'];
$get=array("0"=>$username,"username"=>$username,'1'=>$password,"password"=>$password);
//Created an array above that matches username and password.
$lol = mysqli_query($con,"Select username,password from users");
while($pre= mysqli_fetch_array($lol)){
//Now we check if, while in the loop, any tuple matches
if (($get == $pre)){
echo '<h1><font color=green>Found</font></h1>';
//Use JavaScript To Redirect or clear headers to use header("location: dashboard.php");
exit;
}
}
echo '<h1><font color=red>Not Found</font></h1>';
}
?>
<form action="" method="post">
<p><label for="u">Username</label><input type="text" name="username" id="u"></p>
<p><label for="password">Password</label><input type="password" name="password" id="password"></p>
<p><input type="submit" name="submit" value="Login" id="submit"></p>
</form>
</body>
</html>
I have created a HTML page which takes user-id and password from user and then check there validity through database. Till now i was directing them to another page after successful login. But now i want to update same page after login. Just like www.facebook.com ; when we are NOT logged in its asks for user-id and password, but if we are login our profile contents are displayed on the same page i.e. facebook.com. What i was doing; directing it to page "login.php" which of course you can access without login.
For example there is a page "movies.com" which allows user to watch some movies after login; before i was just directing them to another page say "successful_login.com" after they login. It was a funny approach, but was working for my college assignments.
PS. Am just a noob, sorry if i asked something funny.
<?php
if(mysql_connect("localhost","root","")==false)
{
die ("Connection Failed");
}
mysql_select_db("data");
if($_POST)
{
$id=$_POST["email"];
$pwd=$_POST["password"];
$pwd=hash( 'sha256', $pwd);
$sql=mysql_query("SELECT* FROM admin_data WHERE id='$id' AND pass='$pwd'");
if($sql)
{
header("Location: login.php");
}
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset="UTF-8" />
<title>
HTML Document Structure
</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<form method="POST">
<h1>Welcome</h1>
<div class="inset">
<p>
<label for="email">Login</label>
<input type="text" name="email" id="email">
</p>
<p>
<label for="password">PASSWORD</label>
<input type="password" name="password" id="password">
</p>
</div>
<p class="p-container">
<span>Forgot password ?</span>
<input type="submit" name="Login" id="Login" value="Log in">
</p>
</form>
</body>
</html>
To use the session variable you need to start session at the top.
session_start();
Now store the email value in the session in here.
if(mysql_num_rows()>0)//It was originally if($sql)but I am using mysql_num_rows
//The reason for saving the value in the session here is this.
First you want to make sure that user have valid credential to log in.
{
$_SESSION['email']=$id
header("Location: login.php");
}
In your form you can do something like this
session_start();//Start the session at the top so you can use the session variable.
then simply use if else statement.
if($_SESSION['email']==TRUE)
{
$email=$_SESSION['email'];
//Now you can run the query by using $email to fetch the record of the user.
}
else
{
//Show them a form or redirect them to another page.
}
Note:mysql is deprecated and is going to be dropped soon. Use mysqli or P.D.O
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()