Issues while creating a session - php

I am creating a user session but it's like code has gone wrong somewhere and doesn't hold session, I simply redirect user to a blank page where I echo user id of session holder to check whether it's working or not. Their is no problem with table or db as register page works fine and data gets stored in db. My login.php
<?php
$con = mysqli_connect("localhost","root","","findfriends") or die ("Connection not established");
?>
<?php
if(isset($_POST['login'])){
$username = strip_tags(#$_POST['user_login']);
$password = strip_tags(#$_POST['password_login']);
$result = $con->query("SELECT * FROM users WHERE username='$username' AND password='$password'");
$row = $result->fetch_array(mysqli_both);
session_start();
$_SESSION["userid"] = $row['userid'];
header("Location: test12.php");
}
?>
<h2>Already a member? Login Below</h2>
<form action="" method="POST">
<input type="text" name="user_login" size="25" placeholder="Username"/><br><br>
<input type="password" name="password_login" size="30" placeholder="Passsword"/><br><br>
<input type="submit" name="login" value="Login">
</form>
test.php for checking session
<?php
$con = mysqli_connect("localhost","root","","findfriends") or die ("Connection not established");
?>
<?php
session_start();
?>
<div style="margin-left:30px;margin-right:400px;border:1px solid #000;">
<h2>User id is:</h2>
<?php echo $_SESSION["userid"]; ?>
</div>

Make session_start(); your first line in the file

try by using $_SESSION['userid'] instead of $_SESSION["userid"].

Related

Getting a variable from another page in php

I wanted to show the variable username into another page. These are the codes I've used. This is the first page where the username is inserted.
<?php
include('login.php'); // Includes Login Script
if(isset($_SESSION['login_user'])){
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<div id="login" align="center">
<h2>Welcome!</h2>
<form action="" method="post">
<label>Username :</label>
<input id="name" name="username" placeholder="username" type="text"><br>
<label>Password :</label>
<input id="password" name="password" placeholder="**********"
type="password">
<br><br>
<input name="submit" type="submit" value=" Login ">
<span><?php echo $error; ?></span>
</form>
</div>
</body>
</html>
Then in this page I wanted to show the username that was inserted
<?php include 'database.php'; ?>
<?php session_start(); ?>
<?php
function visualizza($file) {
$f = fopen($file, "r"); // apro il file in lettura
return fread($f, filesize($file));
fclose($f);
}
?>
<html>
<main>
<div class="container">
<h2> Quiz Completato!</h2>
<p> Congratulations <?php
$username = $_POST['username'];
echo $username;
?>
! You completed the test</p>
<p>Final Score:<?php echo $_SESSION['score']; ?> </p>
</div>
</main>
I can't put form action="final.php", because this is the final page of a quiz, while the submit button has to send me to another page
Do you know how to do this please?
This is where the user and password are processed (login.php)
<?php
session_start(); // Starting Session
$error = ''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
// Define $username and $password
$username = $_POST['username'];
$password = $_POST['password'];
// mysqli_connect() function opens a new connection to the MySQL server.
$conn = mysqli_connect("localhost", "root", "", "quizzer");
// SQL query to fetch information of registerd users and finds user match.
$query = "SELECT username, password from login where username=? AND
password=? LIMIT 1";
// To protect MySQL injection for Security purpose
$stmt = $conn->prepare($query);
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if($stmt->fetch()) //fetching the contents of the row
{
$_SESSION['login_user'] = $username; // Initializing Session
header("location: quizzer.php"); // Redirecting To Profile Page
}
else {
$error = "Username o Password sbagliate";
}
mysqli_close($conn); // Closing Connection
}
}
?>
In your form element, the action attribute needs to go to another page submitting all the $_POST[] requests.
<form action="page2.php" method="post">
Now the $_POST['username'] can now be seen in the second page.
As soon as you login u may store the username in session as follows
$_SESSION['username'] = $_POST['username'];
And echo it on any page by starting starting session
echo $_SESSION['username'];

prepared statement executes, but i can't fetch the results

I'm was doing this tutorialHow to create a login system in PHP
I'm trying to use an IF statement to check if to set the session id. The current allows a user to log in and echos the current session id. When I purposely enter a wrong password, the code should echo a message, but it doesn't do anything. In addition, I am unable to use the logout button to kill the session.
Here is my login page
<?php
session_start();
//include 'dbh.php';
//probably do not need this can write connection in this file too
$conn = new PDO('mysql:host=localhost;dbname=testtable', 'root', '');
$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
if(!$conn){
die("Connection is fubar yo!!! ");
}
$uid = $_REQUEST['uid'];
$pwd = $_REQUEST['pwd'];
$sql = "SELECT * from user WHERE uid='$uid' AND pwd='$pwd'";
$result = $conn->prepare($sql);
$result->execute();
if(!$row = $result->fetch(PDO::FETCH_ASSOC)){
echo("Your username or Password is wrong");
} else {
echo("hey man..it works");
$_SESSION['id'] = $row['id'];
}
header("Location: fakelogin.php");
?>
Here is my logout page.
<?php
session_start();
session_destroy();
header("Location: fakelogin.php");
?>
here is the main page that contains login, signup and logout buttons.
<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Look ma, no hands!</title>
</head>
<body>
<form action="login.php" method="POST">
<input type="text" name="uid" placeholder="Enter username"><br>
<input type="password" name="pwd" placeholder="Enter password"><br>
<button type="submit" id="login">LOGIN</button>
</form>
<?php
echo("testing");
if(isset($_SESSION['id'])){
echo($_SESSION['id']);
} else {
echo("You are not logged in");
}
?>
<br><br><br>
<form action="signup.php" method="POST">
<input type="text" name="first" placeholder="Enter first name"><br>
<input type="text" name="last" placeholder="Enter last name"><br>
<input type="text" name="uid" placeholder="Enter username"><br>
<input type="password" name="pwd" placeholder="Enter password"><br>
<button type="submit" id="sbt">SIGN UP HERE YO!</button>
</form>
<br><br><br>
<form>
<button action="logout.php">LOG OUT</button>
</form>
</body>
</html>
Based on the code you have provided, you will always return to the login page.
When logged in, the string below login button will say testing followed by your user account id.
Otherwise, it will show testingYou are not logged in.
You cannot add a message on login.php and expect it to appear on fakelogin.php auto-magically.
There are a lot of ways to share information between pages and the session variable is one of it.
By using the method below, you can set the session variable id as "Your username or Password is wrong" and since fakelogin.php will print it out if there's a value, this should show the error message.
login.php
<?php
session_start();
//include 'dbh.php';
//probably do not need this can write connection in this file too
$conn = new PDO('mysql:host=localhost;dbname=testtable', 'root', '');
$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
if(!$conn){
die("Connection is fubar yo!!! ");
}
$uid = $_REQUEST['uid'];
$pwd = $_REQUEST['pwd'];
$sql = "SELECT * from user WHERE uid='$uid' AND pwd='$pwd'";
$result = $conn->prepare($sql);
$result->execute();
if(!$row = $result->fetch(PDO::FETCH_ASSOC)){
echo("Your username or Password is wrong");
$_SESSION['id'] = "Your username or Password is wrong";
} else {
echo("hey man..it works");
$_SESSION['id'] = $row['id'];
}
header("Location: fakelogin.php");
?>
So when you attempt to login with wrong details, you will see testingYour username or Password is wrong.
For problem with your logout button, there's a problem with your HTML. action attribute should be in the form tag and not the button tag like so.
<form action="logout.php">
<button>LOG OUT</button>
</form>

Cannot check login error (blank)

i have problem with login validation. The problem is when i try to login using admin, the page stop on checklogin.php and won't tell if it is succeed or not. Here is my code.
Index.html
<body>
<section class="container">
<div class="login">
<h1>Aplikasi Pengelola Data Pelatihan dan Seminar</h1>
<form method="post" action="checklogin.php">
<p><input type="text" name="username" value="" placeholder="Username or Email"></p>
<p><input type="password" name="password" value="" placeholder="Password"></p>
<p class="remember_me">
<label>
<input type="checkbox" name="remember_me" id="remember_me">
Remember me on this computer
</label>
</p>
<p class="submit"><input type="submit" name="commit" value="Login"></p>
</form>
</div>
<div class="login-help">
<p>Forgot your password? Click here to reset it.</p>
</div>
</section>
</body>
checklogin.php
<?php
if (isset($_POST['login']))
{
if(isset($_POST['username']))
{
$username=$_POST['username'];
}
if(isset($_POST['password']))
{
$password=$_POST['password'];
}
// Connect to database.
$host="localhost"; // Host name.
$db_user="root"; // MySQL username.
$db_password=""; // MySQL password.
$db="seminardanpelatihan"; // Database.
$con = mysqli_connect($host,$db_user,$db_password,$db);
if(mysqli_connect_errno())
{
echo "Failed to connect : " . mysqli_connect_error();
}
else
{
mysqli_select_db($con, $db);
$result = mysqli_query($con, "SELECT * FROM login WHERE username='$username' and password='$password'");
$count=mysqli_num_rows($result);
if($count==1)
{
$_SESSION['username']= "username";
$_SESSION['password']= "password";
header("login_success.php"); // Re-direct to login_success.php
}
else
{
echo "Something wrong";
}
mysqli_close($con);
}
}
?>
Thank you for your help.
change
if (isset($_POST['login']))
to
if (isset($_POST['commit']))
I tested.
Edit
Also Change (Dont skip previous changes)
$_SESSION['username']= "username";
$_SESSION['password']= "password";
header("login_success.php");
To
$_SESSION['username']= $username;
$_SESSION['password']= $password;
header("Location: login_success.php"); //Proper Redirect Method
1)You need Location: prefix for redirect
2)You used "username" instead of $username
First of all change the first line of your code:
<?php
if (isset($_POST['login']))
to
<?php
if (isset($_POST['username']))
this will give you the option to execute all the code of the page if the user will post at least the username. I'd prefer to go for something even more strict:
<?php
if (isset($_POST['username'])&&isset($_POST['password'])
so you won't run the code if the user doesn't submit both the values. (only username or only password will anyway fail the validation!)
Then: your issue is that you don't retrieve the values from the query.
mysqli_select_db($con, $db);
$result = mysqli_query($con, "SELECT * FROM login WHERE username='$username' and password='$password'");
$count=mysqli_num_rows($result);
if($count==1)
{
is ok to check if you have one and only one result but then you have to add after those lines:
$row=mysqli_fetch_array($result);
$username = $row['username'];
$password = $row['password'];
session_start();
and then edit the following two this way:
$_SESSION['username']= $username;
$_SESSION['password']= $password;
Also note that I wouldn't store the password in $_SESSION array or in any other value in my code and that I'd suggest you to use some encryption method on the password.

I'm using a login script (PHP, MySQL) which uses sessions. I need to create a variable so i can use it in the other pages?

The PHP script I have for the login.php which is the form is the code below.
<?php
include 'dbc.php';
$user_email = mysql_real_escape_string($_POST['email']);
if ($_POST['Submit']=='Login')
{
$md5pass = md5($_POST['pwd']);
$sql = "SELECT id,user_email FROM users WHERE
user_email = '$user_email' AND
user_pwd = '$md5pass' AND user_activated='1'";
$result = mysql_query($sql) or die (mysql_error());
$num = mysql_num_rows($result);
if ( $num != 0 ) {
// A matching row was found - the user is authenticated.
session_start();
list($user_id,$user_email) = mysql_fetch_row($result);
// this sets variables in the session
$_SESSION['user']= $user_email;
if (isset($_GET['ret']) && !empty($_GET['ret']))
{
header("Location: $_GET[ret]");
} else
{
header("Location: myaccount.php");
}
//echo "Logged in...";
exit();
}
header("Location: login.php?msg=Invalid Login");
//echo "Error:";
exit();
}
?>
<link href="styles.css" rel="stylesheet" type="text/css">
<?php if (isset($_GET['msg'])) { echo "<div class=\"msg\"> $_GET[msg] </div>"; } ?>
<p> </p><table width="40%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td bgcolor="#d5e8f9" class="mnuheader" >
<div align="center"><font size="5"><strong>Login
Members</strong></font></div></td>
</tr>
<tr>
<td bgcolor="#e5ecf9" class="mnubody"><form name="form1" method="post" action="">
<p> </p>
<p align="center">Your Email
<input name="email" type="text" id="email">
</p>
<p align="center"> Password:
<input name="pwd" type="password" id="pwd">
</p>
<p align="center">
<input type="submit" name="Submit" value="Login">
</p>
<p align="center">Register | Forgot</p>
</form></td>
</tr>
I want to create a session vairable like the $_SESSION['user']= $user_email; which i can use in other pages. The problem is i don't know how to do so and i want to select a different row from my database called points. So it will be something like
$sql = "SELECT id,user_email,points FROM users WHERE
user_email = '$user_email' AND
user_pwd = '$md5pass' AND user_activated='1'";
Like i say i want it to select the number of points so it can be used on all pages where the session has been start.
Here is an account page which echos the logged in user. But i want it to also echo the points row from my database.
<?php
session_start();
if (!isset($_SESSION['user']))
{
die ("Access Denied");
}
?>
<h2>My Account </h2>
<?php if (isset($_SESSION['user'])) { ?>
<p>Logged as <?php echo $_SESSION['user']; ?>
Settings
Logout </p>
<?php } ?>
Thank you for your help!
put the session_start() start of the page
<?php
session_start();
your code follows this line the variables were working.
You must place session_start() at the top of any pages you want to carry the session over to, so try that and see if that works :)
you should have the following to return a assoc array with the users details into a variable $user.
$sql = "SELECT * FROM users WHERE user_email = '{$_SESSION['user']}'";
$res = mysqli_query($sql);
$user = mysqli_fetch_assco($res);
Also, mysql_ is depreciated, so you should change all of your references of mysql_ to mysqli_
To creat a session variable,try doing the same as $_SESSION['user']= $user_email
So $_SESSION['WhateverYouWant']= $Anything

Despite creating a session, when a person navigates to a second page, it acts as though the session never existed

For some reason despite the fact that IsLoggedIn() is checking for the session, it acts as though none exists.
I used this to create the functions
<?php
session_start();
function DoLogin($email, $password)
{
$sql = "
SELECT U.id, password, FirstName, LastName
FROM Users U
Join ContactMethods CM On U.id=CM.User_Id
WHERE CM.`Value` = '$email'
";
$conn = getConnection();
$result = $conn->query($sql);
//echo $conn->error;
$rs = $result->fetch_assoc();
$conn->close();
if($rs['password'] == $password)
{
$_SESSION['UserId'] = $rs['id'];
$_SESSION['UserEmail'] = $email;
$_SESSION['UserName'] = $rs['FirstName'] . ' ' . $rs['LastName'];
}
}
function IsLoggedIn()
{
return isset($_SESSION['UserId']);
}
and this on top of pages
require_once('inc/loginauth.php'); // calls the script with the functions listed above
if(isset($_REQUEST['email']))
DoLogin($_REQUEST['email'],$_REQUEST['password']);
?>
and this for the login piece on each page
<?php
session_start();
if(IsLoggedIn()){ ?>
<h2>Welome <?=GetUserName()?>!</h2>
<p class="grey">Would You Like to Log Out?</p>
<p class="grey">Log Out</p>
</div>
<div class="left">
<!-- Login Form --><? }else{ ?>
<form method="post">
<label class="grey" for="email">Email:</label>
<input class="field" type="email" name="email" />
<label class="grey" for="password">Password:</label>
<input class="field" type="password" name="password" />
<input type="submit" class="bt_login" value="Log In" />
</form>
<? } ?>
Put session_start(); at the beginning of the second script (if the session is not started automatically)
Try var_dump($_SESSION); in the second script to see what you have in the session.
Don't use short open PHP tags <? ?>. They are deprecated. Use full tags <?php ?>
Try putting the session start within the php function.
also the start and end delimiters are <?php if(IsLoggedIn()){ ?>

Categories