How to start a session, and then retrieve the session variable? - php

First and foremost, I have looked throughout the site and haven't been able to find a solution that works for my program.
Saying this, I am trying to create an authentication page that starts a session, and will save a username from a login page as a session variable. Then, I want my thrid page to retrieve the username session variable.
This is my Form:
<html>
<head>
<title>Form Test</title>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<h1 align="center">Log in with your username and</h1>
<form class="form-horizontal" method="POST" action="formauth.php">
<div class="form-group">
<div class="control-label col-sm-3">
<label for="card">Username:</label>
</div>
<div class="col-sm-5">
<input type="text" name="username" placeholder="enter username here">
</div>
</div>
<div class="form-group">
<div class="form-group">
<div class="control-label col-sm-3">
<label for="card">Password:</label>
</div>
<div class="col-sm-5">
<input type="text" name="password" placeholder="enter password here">
</div>
</div>
<div class="form-group">
<div class="control-label col-sm-3">
<div name="buttons" class="col-sm-offset-3">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</body>
</html>
Here is my authentication page. For some reason, I can't get this to save the username that is input into the form as a session variable.
<?php
session_start();
$_SESSION['username'] =$user_name;
if (isset($_POST['username']) &&
isset($_POST['password']))
{
$user = $_POST['username'];
$pwd = $_POST['password'];
require_once "login.php";
$conn = new mysqli($hn, $un, $pwd, $db);
if ($conn->connect_error) die($conn->connect_error);
$query = "Select Password from Users where Username = '$user'";
$result = $conn->query($query);
if (!$result) {
$result->close();
$conn->close();
header('Location: http://localhost/FormAuth/loginForm.html');
}
else {
$rows = $result->num_rows;
$result->data_seek(0);
$p=$result->fetch_assoc()['password'];
if ($p == $password) {
header("Location: http://localhost/FormAuth/afterlogin.php");
}
else {
$result->close();
$conn->close();
$result->close();
$conn->close();
header('Location: http://localhost/loginForm.html');
}
}
$result->close();
$conn->close();
}
else
{
$result->close();
$conn->close();
header('Location: http://localhost/loginForm.html');
}
?>
Now for my third page, I can't retrieve the username session variable.
session_start();
if (!isset($_SESSION['username'])) {
echo "Username is: ".$_user_name['username'] . "<br>";
echo "Test, I made it here!";
}else{
echo "You not logged in.";
}
?>
<html>
<head>
</head>
<body>
</body>
</html>
This results in:
Username is:
Test, I made it here!

You need to set username in session after check username and password in your database.
<?php
session_start();
if (isset($_POST['username']) &&
isset($_POST['password']))
{
$user = $_POST['username'];
$pwd = $_POST['password'];
require_once "login.php";
$conn = new mysqli($hn, $un, $pwd, $db);
if ($conn->connect_error) die($conn->connect_error);
$query = "Select Password from Users where Username = '$user'";
$result = $conn->query($query);
if (!$result) {
$result->close();
$conn->close();
header('Location: http://localhost/FormAuth/loginForm.html');
}
else {
$rows = $result->num_rows;
$result->data_seek(0);
$p=$result->fetch_assoc()['password'];
if ($p == $pwd) { // use $pwd instead of $password
$_SESSION['username'] = $user; // set username here
header("Location: http://localhost/FormAuth/afterlogin.php");
}
else {
$result->close();
$conn->close();
$result->close();
$conn->close();
header('Location: http://localhost/loginForm.html');
}
}
$result->close();
$conn->close();
}
else
{
$result->close();
$conn->close();
header('Location: http://localhost/loginForm.html');
}
?>
And In your third part, check if your username is set in session before try to display it:
if (isset($_SESSION['username'])) {
echo "Username is: ".$_SESSION['username'] . "<br>";
}

You need to first check whether the posted values are set or not.
<?php
session_start();
if (isset($_POST['username'], $_POST['password'])){
...
Then, only when the passwords match, set the session variable $_POST['username'] before redirecting.
if ($p == $password) {
$_SESSION['username'] =$user;
header("Location: http://localhost/FormAuth/afterlogin.php");
}
Then you can access your set session variable $_SESSION['username'] on any page provided you use session_start();. Take the third page for instance,
session_start();
if(isset($_POST['username']) && !empty($_POST['username'])){
// proceed to account dashboard / your required page
} else {
// redirect to login page / index
}

Your problem comes from this line :
<?php
session_start();
$_SESSION['username'] = $user_name;
if (isset($_POST['username']) &&
isset($_POST['password']))
{
$user = $_POST['username'];
Do this one instead:
<?php
session_start();
if (isset($_POST['username']) && isset($_POST['password'])) {
$user = $_POST['username'];
$_SESSION['username'] = $user;
EDIT: The third page:
session_start();
if (isset($_SESSION['username'])) {
echo "Username is: ".$_SESSION['username'] . "<br>";
echo "Test, I made it here!";
} else {
echo "You not logged in.";
}
?>
Good luck.

Related

How do I make sure only logged-in users can acces a page?

I'm really struggling with the whole 'only logged-in users can view this page'. Php is new to me and I can't seem to figure this out. Maybe this is a dumb question or my code is not right, but I'm really trying to figure this out.
login.php:
<?php
session_start();
function is_logged() {
if (isset($_SESSION['username'])) return $_SESSION['username'];
else return false;
}
if (is_logged()) {
$user_id = is_logged();
do_something($user_id);
} else {
if (isset($_POST['submit'])) { //form submitted
//check login and password, if they are correct, do this:
$_SESSION['username'] = $username_from_database;
//if not correct
unset($_SESSION['username']);
header('Location: welcome.php'); //refresh page
} else {
//show login form with button named 'submit'
}
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<?php
if (!isset($_POST['submit'])){
?>
<!-- The HTML login form -->
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
<input type="submit" name="submit" value="Login" />
</form>
<?php
} else {
require_once("db_const.php");
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * from GEBRUIKERS WHERE username LIKE '{$username}' AND password LIKE '{$password}' LIMIT 1";
$result = $mysqli->query($sql);
if (!$result->num_rows == 1) {
echo "<p>Invalid username/password combination</p>";
} else {
echo "<p>Logged in successfully</p>";
// do stuffs
}
if (mysqli_num_rows($result) > 0) {
// Output data of each row
while($row = mysqli_fetch_assoc($result)) {
$_SESSION['+login_user']=$user; // Initializing Session
header("location: welcome.php"); // Redirecting To Other Page
}
}
else {
$error = "Username or Password is invalid";
}
mysqli_close($conn); // Closing Connection
}
?>
</body>
</html>
Welcome.php:
<?php
session_start();
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style.css"/>
<!--Header wordt opgehaald-->
</head>
<?php
require "header2.php"
?>
<?php
$servername = "localhost";
$username = "";
$password = "";
$database = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
<body>
<?php
//Perform queries
$sql = "SELECT acteur_voornaam, acteur_tussenvoegsel, acteur_achternaam, acteur_geboortedatum FROM FILM_ACTEURS";
$result = $conn->query($sql);
//Films
if ($result->num_rows > 0) {
echo "<table style='border: solid 1px grey; margin-left: auto; margin-right: auto; margin-top:50px;'><th>Voornaam</th><th>Tussenvoegsel</th><th>Achternaam</th><th>Geboortedatum</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["acteur_voornaam"] . "<td>" . $row["acteur_tussenvoegsel"]. "<td> " . $row["acteur_achternaam"]. "<td> " . $row["acteur_geboortedatum"] . "" . "</td></tr>";
}
echo "<table>";
} else {
echo "0 results";
}
$conn->close();
?>
</body>
<?php
//Footer wordt opgehaald
include "footer.php"
?>
</html>
session_start(); and checking with is_logged(); must be included in all member only pages, there is another reason your code is not working, and that is you are not clearing the session variable after logout, so your browser logs you in automatically
Within your login functionality create a session variable inside successful login block like:
$_SESSION['loggedIn'] = true;
Now on every page, where logged-in is required to access the page put the following check:
if( !isset($_SESSION['loggedIn']) && ($_SESSION['loggedIn'] != true) )
{
// redirect the user to login screen if the session variable is not set and its value is not true
header('location: login.php');
}
Note: To access the session you have to put session_start() on each page, and it must be the first line.
Try with isset function in php. put the bellow code after session start in the welcome.php file.
if(!(isset($_SESSION['username']) && $_SESSION['username'] != '')){
header ("Location: login.php");
}else{
header ("Location: welcome.php");
}
This redirect on login page if the session 'username' has not set. if the session already initialized then redirect to the welcome.php.
First create a page called session.php which you have to include in all the pages
<?php
session_start();
function is_logged() {
if (isset($_SESSION['username'])) return $_SESSION['username'];
else return false;
}
if (is_logged()) {
$user_id = is_logged();
do_something($user_id);
} else {
if (isset($_POST['submit'])) { //form submitted
//check login and password, if they are correct, do this:
$_SESSION['username'] = $username_from_database;
//if not correct
unset($_SESSION['username']);
header('Location: welcome.php'); //refresh page
} else {
//show login form with button named 'submit'
}
}
?>
Second: include the session.php page in all the pages. This will check for session or redirect to login page.
in Welcome page: Welcome.php on the top of the page include session.php like:
<?php
inlcude 'session.php';
?>
Do necessary changes in session.php file if required.
NOTE: you can give any name to session.php file.

Can't execute login function. No errors

I've been looking at my code for days, but can't seem to find the problem. I'm new in PHP, so I'm not really familiar with all of it.
Below is my code. No errors. No registered session variable values.
db-config.php
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'mcsh';
$conn = mysqli_connect($host, $user, $pass, $db);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
login.php
<form id="user-login" action="index.php" method="POST">
<h1>Administrator Login</h1>
<input type="text" name="username" placeholder="Username" required/>
<input type="password" name="password" placeholder="Password" required/>
<button type="submit">Login</button>
Forgot your password?
</form>
<?php
if (!empty($_POST)) {
if (!empty($_SESSION['username'])) {
header("Location: index.php");
}
$username = $_POST['username'];
$password = $_POST['password'];
include("../config/db-config.php");
$sql = "SELECT `userid`, `password` FROM users WHERE userid = '" . $username . "' AND userlevel = '99'";
$result = mysqli_query($conn, $sql);
if ($row = mysqli_fetch_assoc($result)) {
if (password_verify($password, $row['password'])) {
$_SESSION['username'] = $row['userid'];
header("Location: index.php");
exit;
}
else {
?>
<p class="msg" id="error">Invalid username or password. Please try again.</p>
<?php
}
}
else {
?>
<p class="msg" id="error">Invalid username or password. Please try again.</p>
<?php
}
}
?>
index.php
<?php
session_start();
include("../config/config.php");
if (empty($_SESSION['username'])) {
header("Location: login.php");
}
else {
//the rest of the index page...
?>
Your form in login.php submits to index.php. In index.php, if the username is not yet in the session, you are redirected back to login.php. There you check if (!empty($_POST)) { at the beginning of your PHP code.
$_POST will be empty, because you have redirected to that page, not POSTed to it, so the PHP code will not be executed.
Remove the action="index.php" and that form will submit to itself (login.php). Also, move the HTML form code below the PHP code so that you will not have output before the redirect header if the login is successful.

Not redirecting to the next page after logging in

After logging in, my code isn't redirecting me to the next page.
<?php
$con = mysqli_connect("localhost","myusername","mypassword","mydatabase");
include ("connection.php");
session_start();
if(isset($_POST['login']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$check = "SELECT * FROM admin WHERE username='$username' and password='$password'";
$queryString = mysqli_query($db, $check) or die('ERROR:' . mysqli_error($db));
if (mysqli_num_rows($queryString) > 0)
{
$admin = mysqli_fetch_assoc($queryString);
$_SESSION['username'] = $admin['username'];
session_write_close();
header("location: http://mywebsite.com/home.php");
die();
}
else
{
echo '<div class="popup-position">
<div id="popup-wrapper">
<h3>Invalid user name or password.</h3><br/>OK
</div>
</div>';
}
}
mysqli_close($con);
This is the authentication of the next page after login:
<?php
session_start();
if (!isset($_SESSION['username']))
{
header("location: login.php");
exit();
}
try this
/send user to index. if he is login/
<?php
require_once("inc/ header.inc.php");
if(isset($_SESSION['id']))
{ header("Location: index.php");
exit(); }
<div class="container">
<div class="form-container">
<p class="heading text-center">Login</p>
<form action=" <?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<div class="form-group">
<input type="text" name="username" placeholder="Enter your Username" class="form-control">
</div>
<div class="form-group">
<input type="password" name="password" placeholder="Enter your Password" class="form-control">
</div>
<input type="submit" value="Login" class="btn btn-primary" name="login">
</form>
<?php
//login script
if(isset($_POST['login'])){
$username = trim( htmlspecialchars ($_POST['username']));
$password = trim( htmlspecialchars ($_POST['password']));
//if username or password is empty
if(empty($username) || empty($password)){
echo "<div class='alert alert-danger'>Fill in all the fields</div>";
exit();
}
//check username and password match the db record
$q = mysqli_query($con,"SELECT id FROM `user` WHERE username='$username' AND password='$password'");
if(mysqli_num_rows($q) != 1){
echo "<div class='alert alert-danger'>Invalid username or password</div>";
exit();
}
//fetch the if of the logged in user start the session
$row = mysqli_fetch_assoc($q);
//set the session with logged in user id
$_SESSION['id'] = $row['id'];
$_SESSION['username'] = $username;
header("Location: index.php");
exit();
}
?>
</div>
</div>
Let me help you with logging in.
login.php
<html>
<head>
<title>Hospital Login</title>
<link href="login.css" rel="stylesheet" type="text/css">
</head>
<body>
<form name="form1" method="post" action="process_login.php">
<fieldset class="formDisplay">
<legend><strong>Member Login </strong></legend>
<strong>Username</strong></br></br> <input name="myusername" type="text" id="myusername">
</br></br>
<strong>Password</strong></br></br><input name="mypassword" type="password" id="mypassword">
</br></br>
<input type="submit" name="Submit" value="Login">
</br></br>
<?php
echo $message;
?>
</fieldset>
</form>
</body>
</html>
The code above is literally what should be in your login script, forget about the fieldset thing, I'm just using it for something else :)
Now we want a pure PHP file to handle the input for logging into our system as so.
process_login.php
<?php
include('database_connection.php');
$myusername = mysqli_real_escape_string($DBConn, $_POST['myusername']);
$mypassword = mysqli_real_escape_string($DBConn, $_POST['mypassword']);
$query="SELECT * FROM $doctor_table WHERE username='$myusername' AND passwd='$mypassword'";
$result=mysqli_query($DBConn, $query);
if(!$result){
echo "<p>
There was an error with the query.<br />\n" .
"The error was " .
htmlspecialchars(mysqli_error($DBConn), ENT_QUOTES) .
".<br />\nThe query was '" .
htmlspecialchars($query, ENT_QUOTES ) .
"'</P>\n";
}
else if (!mysqli_num_rows($result)){
$message = "<p>Failed to Log In. Please check your username/password</p>\n";
include 'login.php';
}
else{
$count=mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_start();
$_SESSION['myusername'] = $myusername;
$_SESSION['mypassword'] = $mypassword;
header("Location: login_success.php");
}
}
?>
Now when your authentication has been successful, you should then display your main page.
Note that you must 'clean' every entry by a user in order to avoid SQL injection (helps stop ppl from stealing data from your database)
These full codes work perfectly, I'd encourage you to use the code i've supplied, and feel free to tweak it for your own use :)

This webpage has a redirect loop - PHP Login

I'm trying out a login page example in php. I get the error: This webpage has a redirect loop
Details say: Error code: ERR_TOO_MANY_REDIRECTS
Here's my code:
index.php
<?php
include('login.php'); // Includes Login Script
if(isset($_SESSION['login_user'])){
header("location: profile.php");
}
?>
<form action="" method="post">
<label>UserName :</label>
<input id="name" name="username" placeholder="username" type="text">
<label>Password :</label>
<input id="password" name="password" placeholder="**********" type="password">
<input name="submit" type="submit" value=" Login ">
<span><?php echo $error; ?></span>
</form>
login.php
<?php
session_start();
$error='';
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
$username=$_POST['username'];
$password=$_POST['password'];
$connection = mysql_connect("localhost", "root", "");
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$db = mysql_select_db("rjtest", $connection);
$query = mysql_query("select * from login where myPassword='$password' AND myUserName='$username'", $connection);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$username;
header("location: profile.php");
} else {
$error = "Username or Password is invalid";
}
}
}
?>
profile.php
<?php
include('session.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Your Home Page</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="profile">
<b id="welcome">Welcome : <i><?php echo $login_session; ?></i></b>
<b id="logout">Log Out</b>
</div>
</body>
</html>
session.php
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("rjtest", $connection);
session_start();
$user_check=$_SESSION['login_user'];
$ses_sql=mysql_query("select myUsername from login where myUsername='$user_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
$login_session =$row['username'];
if(!isset($login_session)){
header('Location: index.php');
}
?>
And logout.php
<?php
session_start();
if(session_destroy())
{
header("Location: index.php");
}
?>
I can't seem figure out why. The site where I got this code is now inactive, so that's why Im asking this here. Hope you guys could help me out. Sorry for the long post though.
Comment to answer:
What I think is going on is that your code is erroring out and you're not seeing it, causing it to fight against what it should be showing you as an error.
You have $login_session =$row['username']; using the "username" as the row, but you're not selecting it in your query select myUsername from login where myUsername.
So, I'm thinking that if that row doesn't in fact exist, you'd need to do
$login_session =$row['myUsername'];

Issue on Welcome to logged in User

I am trying to add a welcome to user in a restricted area using PHP login system. I used this code to transfer usernale from first user login page to restricted page but it didnt work
if ( (isset($_POST['username'])) || (isset($_POST['password'])) {
$user = $_SESSION['username'];
}
Here are the files that I am using, Can you please take a look at them and let me know what I am doing wrong?
<form id="login-form" method="post" action="includes/login.inc.php">
<fieldset>
<legend>Login to Web Site</legend>
<label for="username">
<input type="text" name="username" id="username" />Username:
</label>
<label for="password">
<input type="password" name="password" id="password" />Password:
</label>
<label for="submit">
<input type="submit" name="submit" id="submit" value="Login" />
</label>
</fieldset>
I have a php login file which is like this:
<?php
require_once('config.inc.php');
require_once('functions.inc.php');
// Start session
session_start();
// Check if user is already logged in
if ($_SESSION['logged_in'] == true) {
// If user is already logged in, redirect to main page
redirect('../index.php');
} else {
// Make sure that user submitted a username/password and username only consists of alphanumeric chars
if ( (!isset($_POST['username'])) || (!isset($_POST['password'])) OR
(!ctype_alnum($_POST['username'])) ) {
redirect('../login.php');
}
// Connect to database
$mysqli = #new mysqli(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
// Check connection
if (mysqli_connect_errno()) {
printf("Unable to connect to database: %s", mysqli_connect_error());
exit();
}
// Escape any unsafe characters before querying database
$username = $mysqli->real_escape_string($_POST['username']);
$password = $mysqli->real_escape_string($_POST['password']);
// Construct SQL statement for query & execute
$sql = "SELECT * FROM users WHERE username = '" . $username . "' AND password = '" . md5($password) . "'";
$result = $mysqli->query($sql);
// If one row is returned, username and password are valid
if (is_object($result) && $result->num_rows == 1) {
// Set session variable for login status to true
$_SESSION['logged_in'] = true;
redirect('../index.php');
} else {
// If number of rows returned is not one, redirect back to login screen
redirect('../login.php');
}
}
?>
and on my restricted page I have:
<?php
// Start session
session_start();
if ( (isset($_POST['username'])) || (isset($_POST['password'])) {
$user = $_SESSION['username'];
}
require_once('includes/functions.inc.php');
if (check_login_status() == false) {
redirect('login.php');
}
?>
<!DOCTYPE html>
<html>
<body>
<div id="page">
<a class="welcome">
Welcome: <?php echo $user; ?>
</a>
</div>
use
$_SESSION['username'] = $_POST['username'];
and then echo out $_SESSION['username']
EDIT
<?php
// Start session
session_start();
if (isset($_POST['username']) || isset($_POST['password'])) {
require_once('includes/functions.inc.php');
if (check_login_status() == false) {
redirect('login.php');
}
$_SESSION['username'] = $_POST['username'];
}
?>
<!DOCTYPE html>
<html>
<body>
<div id="page">
<a class="welcome">
Welcome: <?php echo $_SESSION['username']; ?>
</a>
</div>

Categories