Data not saving in session variable - php

The data is not storing in session everything is working fine the login system all things but the Data like username user pass and user Id should be saved in session but it's not I know it because if it was saving when you login successfully it should show welcome {username}.
Proceed to forums the main page but it is not showing username it was showing before but I got to problems and when all problems fixed this error came out.
Code:
<style>
<?php include 'signin.css'; ?>
</style>
<script type="text/javascript" src="signup.js"></script>
<?php
//signin.php
include 'connect.php';
include 'header.php';
//first, check if the user is already signed in. If that is the case, there is no need to display this page
if(isset($_SESSION['signed_in']) && $_SESSION['signed_in'] == true)
{
echo 'You are already signed in, you can sign out if you want.';
}
else
{
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
/*the form hasn't been posted yet, display it
note that the action="" will cause the form to post to the same page it is on */
echo '<form action="" method="post" >
<div class="all" >
<div class="container" >
<div class="first" >
<h2>SIGN IN</h2>
</div>
<div class="user" >
<input class="use" type="text" placeholder="Username" id="username" name="user_name" required>
</div>
<div class="userimg" >
<img src="user.png" style="height:2em;width:2em;" >
</div>
<div class="pass" >
<input type="password" placeholder="Password" id="password" name="user_pass" minlength="8" required >
<img src="lock.png" >
</div>
<div class="show">
<img src="visible.png" id="visible" class="visible" onclick="myFunction()">
<img src="invisible.png" id="invisible" class="invisible" onclick="mynot()" >
</div>
<div class="check" >
<input type="checkbox" required >
</div>
<div class="box" >
<p>I accept all <a href="#" >terms</a> and <a href="#" >privacy</a>.</p>
</div>
<div class="submit" >
<input type="submit" name="submit" onclick="submit()" value="Sign in">
</div>
<div class="close" >
<input type="button" value="Back" >
</div>
<div class="log" >
dont have an account? <a href="#" >Login</a>
</div>
<div class="organic" >
<img src="logo.png" class="organicpe" >
</div>
<div>
<h2 class="back" ><a href="#" >Go Back</a></h2>
</div>
</div>
</div>
</form>';
}
else
{
/* so, the form has been posted, we'll process the data in three steps:
1. Check the data
2. Let the user refill the wrong fields (if necessary)
3. Verify if the data is correct and return the correct response
*/
$errors = array(); /* declare the array for later use */
if(!isset($_POST['user_name']))
{
$errors[] = 'The username field must not be empty.';
}
if(!isset($_POST['user_pass']))
{
$errors[] = 'The password field must not be empty.';
}
if(!empty($errors)) /*check for an empty array, if there are errors, they're in this array (note the ! operator)*/
{
echo 'Uh-oh.. a couple of fields are not filled in correctly..';
echo '<ul>';
foreach($errors as $key => $value) /* walk through the array so all the errors get displayed */
{
echo '<li>' . $value . '</li>'; /* this generates a nice error list */
}
echo '</ul>';
}
else
{
//the form has been posted without errors, so save it
//notice the use of mysql_real_escape_string, keep everything safe!
//also notice the sha1 function which hashes the password
$sql = "SELECT
user_id,
user_name,
user_level
FROM
Users
WHERE
user_name = '" . mysql_real_escape_string($_POST['user_name']) . "'
AND
user_pass = '" . sha1($_POST['user_pass']) . "'";
$result = mysqli_query($conn,$sql);
if(!$result)
{
//something went wrong, display the error
echo 'Something went wrong while signing in. Please try again later.';
//echo mysql_error(); //debugging purposes, uncomment when needed
}
else
{
//the query was successfully executed, there are 2 possibilities
//1. the query returned data, the user can be signed in
//2. the query returned an empty result set, the credentials were wrong
if(mysqli_num_rows($result) == 0)
{
echo 'You have supplied a wrong user/password combination. Please try again.';
}
else
{
while ($row = $result -> fetch_row())
session_start();
//set the $_SESSION['signed_in'] variable to TRUE
$_SESSION['signed_in'] = true;
//we also put the user_id and user_name values in the $_SESSION, so we can use it at various pages
{
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
$_SESSION['user_level'] = $row['user_level'];
}
while ($row = mysqli_fetch_array($result)) {
//set the $_SESSION['signed_in'] variable to TRUE
$_SESSION['signed_in'] = true;
//we also put the user_id and user_name values in the $_SESSION, so we can use it at various pages
while($row = mysqli_fetch_assoc($result))
{
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
}
}
echo '<h3>Welcome, ' . $_SESSION['user_name'] . '. Proceed to the forum overview.</h1>';
}
}
}
}
}
include 'footer.php';
?>

You need to start every php file use session with
session_start();

Related

Attempt to read property "Name" on array on my laravel login

Hello i have been getting a Attempt to read property "Name" on array error on my login for laravel. we have been trying different ways to get it working but so far no success.
#extends("Layout")
<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
echo '<p>TEST</p>';
$sql = DB::select('select * from users where Name = ?', [$_POST["txtuser"]]);
if(!$sql->Name == "") {
echo 'No user found!';
} else {
if($sql->password == $_POST["txtpass"]) {
session_start();
$_SESSION["loggedin"] = true;
header("location: home.blade.php");
} else {
echo 'wrong password!';
}
}
}
?>
<div class="card2">
<div class="center">
<button><a href="{{url('/home')}}" >Home</a> </button>
<button> <a href="{{url ('/b2b') }}" >Business to business</a> </button>
<button><a href="{{url ('/b2c') }}" >Business to consumer </a> </button>
<button><a href="{{url ('/c2c')}}" >Consumer to consumer</a> </button>
<button><a href="{{url ('login-system/login')}}" >Login</a> </button>
<button>Store</button>
</div>
<H1>Login</H1>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
#csrf
<input type="text" name="txtuser" value='' />
<input type="password" name="txtpass" />
<input type="submit" name="login" value="submit"/>
</form>
</div>
you need to loop through your select first. If I'm not mistaken even if you select a specific user you will get an array back.
example:
$users = DB::select('select * from users');
foreach ($users as $user) {
echo $user->name;
}
or you could do something try to get the first item from the array that is returned and store it in a variable $user and then you could use $user->name
also it's not a bad thing to count the items returned before using them. It could be that you have 0 items returned and in that cause you can show user not found (i quickly wrote the code below without testing)
$users = DB::select('select * from users where Name = ?', [$_POST["txtuser"]]);
if(count($users) == 0) {
echo 'No user found!';
}
also it would be a good thing to include your password check into the sql statement itself. It's better practice to check username and password together instead of saying if a user exists or not

Data not update when login is successfull in index.php?

I make a login page like user login. if registered then login with email and password(navigate register.php to index.php page) or sign up if not registered. works good but i want to add update functionality in my index.php page concept is simple if user wants to update its record then he make updations in a form and submit. I make a update query here but its shows Notice: Undefined index: id in C:\wamp\www\LOginKodingMadSimple\index.php on line 34. Where i am wrong ?
index.php :
<?php
session_start();
include_once 'dbconnect.php';
?>
<?php
if (isset($_POST['UpdateUser']))
{
$name = mysqli_real_escape_string($con, $_POST['name']);
$id = mysqli_real_escape_string($con, $_POST['id']);
//------- name can contain only alpha characters and space -------
if (!preg_match("/^[a-zA-Z ]+$/",$name))
{
$error = true;
$name_error = "Name must contain only alphabets and space";
}
//------- Update users -------
if (!$error)
{
if(mysqli_query($con, "UPDATE users SET name='" . $name . "' WHERE id='" . $id . "'"))
{
$successmsg = "Successfully Updated! ";
}
else
{
$errormsg = "Error in Update...Please try again later!";
}
}
}
else
{
$errormsg = "Failed Please Try Again Later !";
}
?>
<div class="collapse navbar-collapse" id="navbar1">
<ul class="nav navbar-nav navbar-right">
<?php if (isset($_SESSION['usr_id'])) { ?>
<li>
<p class="navbar-text">Signed in as <?php echo $_SESSION['usr_name']; ?></p>
<a class="navbar-brand" href="updatephp.php">Update</a>
</li>
<li>
Log Out
</li>
<div style="border:1px dashed transparent;margin-top:400px;position:absolute;margin-left:-35%;">
<h1> Hello User <?php echo $_SESSION['usr_name']; ?> ! </h1>
<h1> Your Email is <?php echo $_SESSION['usr_email']; ?> ! </h1>
<form action="" method="post">
Name: <input type="text" name="name" placeholder="<?php echo $_SESSION['usr_name']; ?>"><br>
<input type="submit" value="Update" name="UpdateUser">
</form>
</div>
<?php } else { ?>
<li>Login</li>
<li>Sign Up</li>
<?php } ?>
</ul>
</div>
add input hidden field with id like.
<input type="hidden" name="id" value="<?php echo $_SESSION['usr_id'];?>">
[NOTE: You don't have any textbox named as id.]
Choose any way.
Way 1)
Change
$id = mysqli_real_escape_string($con, $_POST['id']);
To
$id = $_SESSION['usr_id'];
Updated Code:
<?php
if (isset($_POST['UpdateUser'])) {
$name = mysqli_real_escape_string($con, $_POST['name']);
$id = $_SESSION['usr_id'];
Way 2)
Add one hidden input field having value session usr_id.
<form action="" method="post">
Name: <input type="text" name="name" placeholder="<?php echo $_SESSION['usr_name']; ?>"><br>
<input type='hidden' value="<?php echo $_SESSION['usr_id'];?>" name='id'>
<input type="submit" value="Update" name="UpdateUser">
</form>
In this way, your submitting form code will be same as you are having.
Use below function to hide the error notice :
error_reporting(0);

Setting Session Variables and Calling them on Another Page

I salute you all for your previous help.
Would anyone imagine this very simple error, which has put me down for a couple of hours.
From the Login Page, I compare (authenticate) the login username and password with the database values. If they match, I store them in session variables and redirect to the dashboard page.
Before redirection, I print_r ($_SESSION) to see whether the variables are set or not. They output was TRUE (session is set).
But on the dashboard, calling the session variables returned session !set.
Please check the following code.
[LOGIN PAGE]
<?php
session_start();
require_once('../data/conString_mysqli.php');
$uNameErr = $pWordErr = "";
$uName = $pWord = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//*************************************
if (!empty($_POST["username"])) {
$uName = test_input($_POST["username"]);
} else {
$uNameErr = "Email is required!";
// check if e-mail address is well-formed
if (!filter_var($uName, FILTER_VALIDATE_EMAIL)) {
$uNameErr = "Invalid email format";
}
}
if (!empty($_POST["password"])) {
$pWord = test_input($_POST["password"]);
$hashed = md5($pWord);
} else {
$pWord1Err = "Password is Required!";
if ($pWord < 8) {
$pWordErr = "Invalid Password.";
}
}
}//end if... IS_POST
function test_input($data) {
//require connection file
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}//end function
?>
<?php
if (!empty($uName) && !empty($pWord)){
$hashed = md5($pWord);
$read_data = mysqli_query($connect, "SELECT * FROM service_providers WHERE activated='1' AND ppword ='".$hashed."' AND pemail='".$uName."'") or die(mysqli_error());
$count = mysqli_num_rows($read_data);
if($count >= 1){/*echo '<script type="text/javascript">alert("Records Found!");</script>';*/
//store session variables
$row = mysqli_fetch_array($read_data);
$_SESSION[ 'serv_pid' ] = $row[ 'serv_pid' ];
$_SESSION[ 'providerName' ] = $row[ 'pname' ];
echo '<script type="text/javascript">alert("Session Name: '.$_SESSION['providerName']." - Session ID: ". $_SESSION['serv_pid'].'");window.location="../dashboard/";</script>';
/*echo "<pre>";
print_r ($_SESSION);
echo "</pre>";
*/
}else{echo '<script type="text/javascript">alert("Invalid Login Details");window.location="../login/";</script>';
}
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" style="margin-top: 1.5em;">
<div class="form-group">
<div class="input-group">
<input type="text" name="username" class="form-control text-center" placeholder="username (your email)" value="<?php echo $uName;?>"><span class="error"> <?php echo $uNameErr;?></span>
<span class="input-group-addon btn btn-warning" style="background: #f0ad4e; color: #fff;">
<span class="glyphicon glyphicon-user" style="margin: 0;"></span>
</span>
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="password" name="password" class="form-control text-center" placeholder="password" value="<?php echo $pWord;?>"><span class="error"> <?php echo $pWordErr;?></span>
<span class="input-group-addon btn btn-warning" style="background: #f0ad4e; color: #fff;">
<span class="glyphicon glyphicon-lock" style="margin: 0;"></span>
</span>
</div>
</div>
<p style="font-size: 16px !important;"><a style="color: #fff; text-decoration: none; margin-top: 2em; display: block;" href="../sign-up/">Don't have an Account? <u>Get one!</u></a> <span style="color:#FF0000; font-weight:bold; text-decoration:underline;"><em>Forgot your password?</em></span></p>
<div class="col-md-6 col-md-offset-3 text-center" style="margin-top: 5px;">
<button type="submit" name="login" class="btn btn-warning btn-lg btn-custom" style="margin-right: 1em; border-width: 3px;">LOGIN</button>
SIGN UP
</div>
<div class="clearfix"></div>
</form>
[DASHBOARD PAGE]
<?php
session_start();
echo "<pre>";
print_r ($_SESSION);
echo "</pre>";
/*
if (!isset($_SESSION['serv_pid'])){// or !isset($_SESSION['providerName'])){
die('<script type="text/javascript">alert("You do not have permission to access beyond the previous page.");window.location="../login/";</script>');
}else{
$serv_pid = $_SESSION['serv_pid'];
$pName = $_SESSION['providerName'];
}*/
?>
From the Login Page, the result returned by print_r is:
Array
(
[serv_pid] => 1
[providerName] => No Name
)
But on getting to the login page, it's like the session is destroyed.
The result returned by print_r is:
Array
(
)
Please help me with any ideas.
Thank you in advance.
When you start a session in PHP, it sets a session cookie, that's sent to the browser when you print the first character outside php brackets or at your first echo.
I think the problem is when you try to redirect the user to the dashboard page. You're setting the session, writing to the browser a script that redirects to another page, but in the meanwhile the server doesn't stop the processing on the page.
Try replacing the echo "<script>..." with a header("Location: dashboard.php") in PHP, followed by a exit(0); instruction.
The first one actually tells the browser to redirect to the dashboard.php page (or whatever the page is), the second tells the browser to stop executing the page.
Moreover, delete the blank row between ?> and <?php brackets. That row actually sends the headers to the browser, along with cookies, even if it's a blank character.
There were excess session_start() functions on the landing page and on the sending page. Each session_start() cancelled the other and the variables were destroyed before getting to the landing page.
However, I had to drop the entire pages and recreate them one line at a time. So, it's working now.
I really want to appreciate Marco Todisco, who also contributed suggestive responses to assisting me on my coding.

My form won't work within my bootstrap

I've written code to make a login page, this worked fine. However when I implemented it into my modified bootstrap-template, it wouldn't work anymore.
edit: it will just not give any result, if I understand firebug correctly the submit button does work but the rest of it doesn't, (atleast, it gives me an output in the firebug console) it doesn't seem to send a username or password, and it does sertainly not redirect me to the page set in action=" "
Here is my code:
<div id="login" class="container" style="color:#f7f7f7; background-color:#222222">
<div class="row">
<div class="col-lg-12 text-center">
<h2 class="section-heading">Login</h2>
</div>
</div>
<div class="row text-center">
<div class="col-md-4 col-md-offset-4">
<form method="POST" action="passwordunhash.php">
<p> username: <input type="text" name="username" value="username"></p>
<p> password: <input type="password" name="password" value=""></p>
<p> <input type="submit" value="Inloggen"></p>
</form>
</div>
</div>
</div>
<?php
if (empty($_POST['username']) && empty($_POST['password']) ){
echo " ";
}
else {
$query = "SELECT rank FROM users WHERE username='$username'";
if (!$resultaat = mysql_query($query) ){
$boodschap .= "query \"$query \" mislukt";
// echo "Dit is de boodschap: ".$boodschap." einde boodschap ";
echo "username not found";
}
else {
$rij = mysql_fetch_array($resultaat);
$_SESSION['rank'] = $rij["rank"];
}
$query = "SELECT password FROM users WHERE username='$username'";
if (!$resultaat = mysql_query($query) ){
$boodschap .= "query \"$query \" mislukt";
// echo "Dit is de boodschap: ".$boodschap." einde boodschap ";
echo "username not found";
}
$rij = mysql_fetch_array($resultaat);
$hash = $rij["password"];
if (password_verify($password, $hash)){
$_SESSION['loggedin'] = true;
header("Location: /index.php");
exit();
}
else {
echo 'username or password is incorrect';
session_unset();
session_destroy();
}
}
?>
this is the part I think the problem should be in.
I tried various things, including using the bootstrap form functions and leaving the action blank.
Sorry for the dutch words in it.
This is also my first question on stackoverflow, so if I missed any critical info you might need, please tell me.

After php user validation look up user_id to give user certain access

I have a login form built into a site that uses PHP and JQuery to validate. However, I would like to add a function built into the PHP or the JQuery validator that will take the user_id of the user logged in and compare it to another table in the same database. The other table will have data that will allow users to select from a drop-down list of projects specific to that user that will ultimately control what the user sees in the website. The 2 tables are the "login" table and "projects" table. I think I need to fetch the user_id from the login table and compare to the user_id on the projects table to see if it matches. Not sure how to go about that.
PHP:
<?php
session_start();
$con = mysqli_connect("localhost","****","****","db") or die("Connection error: " . mysqli_error($con));
$query = mysqli_query("projects");
if(isset($_POST['submit'])){
$username = $_POST['user_name'];
$password = $_POST['pwd'];
$stmt = $con->prepare("SELECT * FROM login WHERE username = ? AND password = ? LIMIT 1");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if($stmt->num_rows == 1)
{
while($stmt->fetch())
{
$_SESSION['Logged'] = 1;
$_SESSION['user_name'] = $username;
$_SESSION['timeout'] = time();
echo 'true';
}
}
else {
echo 'false';
}
$stmt->close();
}
else{
}
$con->close();
?>
JQuery:
$("#login_validation").click(function(){
var username=$('#user_name').val();
var password=$('#password').val();
if(username===''){
$("#add_err").html("*Please enter a user name.");
return false;
}
else if(password===''){
$("#add_err").html("*Please enter a password.");
return false;
}
else{
var loadTimeout = setTimeout(tick, 12100);
$.ajax({
type: "POST",
timeout:12000,
url: "login_validation.php",
data: "submit=true&user_name="+username+"&pwd="+password,
beforeSend:function(){
$("#add_err").fadeIn("fast").html('<img src="image/loader.gif" />');
},
success: function(html){
clearTimeout(loadTimeout);
var html=trim(html);
if(html=='true'){
$("#login_b").fadeOut("normal");
$("#login_b").promise().done(function(){
$('#projects').css("display", "block");
})
//$('#profile').css("display", "block");
//$("#profile").html("<a href='logout_session.php' id='logout'>Logout</a>");
}
else{
$("#add_err").html("*Wrong username or password");
}
}
});//end ajax
return false;
}
});//end #login_validation
$("#project_validation").click(function(){
});
var tick = function(){
$("#add_err").html('Unable to fetch page!');
}
function trim(str){
var str=str.replace(/^\s+|\s+$/,'');
return str;
}
Form:
<fieldset id="login_form_wrap" class="login_form_header">
<legend>CUSTOMER LOGIN</legend>
<?php session_start(); ?>
<div id="profile">
<?php if((!isset($_SESSION['user_name'])) || ($_SESSION['timeout'] + 10 * 60 < time())){ ?>
<div id="login_a">
<a id="login_profile" href="#">click to login</a>
</div>
<?php }else {;?>
<a href='logout_session.php' id='logout'>Logout</a>
<!-- header('location: dashboard.php'); -->
<?php } ?>
</div>
<form action="login_validation.php" id="login_form" method="POST">
<div id="login_b">
<div class="welcome"></div>
<div class="wrapper">
<span class="col1">USER NAME:</span>
<input type="text" id="user_name" name="user_name" class="input" required />
</div>
<div class="wrapper">
<span class="col1">PASSWORD:</span>
<input type="password" id="password" name="password" class="input" required />
</div>
<div class="wrapper">
<span class="col1"></span>
<input type="submit" name"submit" id="login_validation" value="SUBMIT" />
<input type="reset" id="cancel_hide" value="CANCEL" />
<div class="err" id="add_err"><br></div>
<div id="divMayus" style="visibility:hidden">Caps Lock is on.</div>
</div>
</div>
<div id="projects">
<div class="welcome">Welcome <?php echo $_SESSION['user_name']; ?></div>
<div class="wrapper">
<span class="col1">PROJECTS:</span>
<select id="Projects" class="input">
<option value="" selected="selected" disabled='disabled'>Choose a Project...</option>
<?php
// Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query)) {
echo '<option value="'.$row['projects'].'">'.$row['projects'].'</option>';
}?>
</select>
</div>
<div class="wrapper">
<span class="col1"></span>
<input type="submit" name"submit" id="project_validation" value="SELECT" />
<div class="err" id="add_err"><br></div>
</div>
</div>
</form>
I'm still learning JQuery and PHP so any help in the right direction is greatly appreciated.
grab the users id you are checking
run a query for of the table, where the user id's allowed are, and explode that into an array
then check to see if the user id you're checking is within that array.

Categories