I'm not very good at PHP and I have a little problem. I've been playing around with this script.
And I can't for the life of me figure out how to echo the username of a logged in user.
I tried to print all the information of the session like this:
var_dump($_SESSION)
but I just got the hashed password and the userlevel int.
Can someone maybe help me here? I just want to be able to echo the username.
You have to store the username in the session for it to be available on another page load, currently the script only stores these values in the session;
$_SESSION['loggedin'] = $row[$this->pass_column];
$_SESSION['userlevel'] = $row[$this->user_level];
What you have to do is add the $username to the session that is passed into the login function, like below;
$_SESSION['username'] = $username;
The username will now be stored in the session with the key username.
To be able to use it on another page, make sure that before attempting to use it you initiate the session by calling the function session_start().
Basically, just write it inside like
session_start();
echo $_SESSION['username'];
or
echo $_SESSION['password'];
A brief explanation of how sessions work.
first you start the session and assign any value to a session ex:
session_start();
$_SESSION['username'] = 'john';
then echoing works like:
echo $_SESSION['username']; // will echo out 'jonh'
note session_start() must be shared in-between the pages you want to use the session
You have session_start(); on top ?
In the login function you should write the username to the session after a successful login.
//instantiate if needed
include("class.login.php");
$log = new logmein();
$log->encrypt = true; //set encryption
if($_REQUEST['action'] == "login"){
if($log->login("logon", $_REQUEST['username'], $_REQUEST['password']) == true){
//do something on successful login
$_SESSION['username'] = $_REQUEST['username'];
}else{
//do something on FAILED login
}
}
<?php
include('db.php');
session_start();
$name=$_POST['name'];
$password=$_POST['password'];
echo $sql="SELECT * FROM register WHERE (name='$name' OR email='$name') AND password='$password'";
$result=mysqli_query($conn,$sql);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0)
{
$_SESSION['user']=mysqli_fetch_assoc($result);
$row = $_SESSION['user'];
$role = $row['role'];
if($role == 1)
{
header('location:usermanagement.php');
}
else{
header('location:user.php');
}
}
else
{
echo "Wrong Username or Password";
header('location:login.php');
}
$conn->close();
?>
Related
I'm trying to create a password protected area of a website.
I'd like to allow access by checking username and password from a MySql table, then start a session and allow access to a number of pages while the session is active. If someone tries to directly access one of these pages directly, I'd like to redirect them to login page.
My code for the login page is:
if (isset($_POST['submit']))
{
include("config.php");
session_start();
$username=$_POST['username'];
$password=$_POST['password'];
$passwordc=md5($password);
$query = "SELECT username FROM admin WHERE username='$username' AND password='$passwordc'";
$result2 = $conn->query($query);
if ($result2->num_rows != 0) {
$_SESSION["username"] = $user;
echo "<script language='javascript' type='text/javascript'> location.href='admin_view.php' </script>";
}else{
echo "<script type='text/javascript'>alert('User Name Or Password Invalid!')</script>";
}
}
It seems to work (correctly redirects if username and password matches, shows alert if not).
What I fail to do, is actually protect my pages from display if session is not active.
session_start();
if (!$_SESSION["username"]) {
header("Location: login.php");
}
I'm not a programmer or fully-educated web developer. I know HTML and CSS, and I'm barely able to use ready-to-use php and js scripts following readme files.
Any help would be greatly appreciated.
modify your login code as
if (isset($_POST['submit']))
{
include("config.php");
$username= $crud->escape_string($_POST['username']);
$password= $crud->escape_string($_POST['password']);
$passwordc=md5($password);
$query = "SELECT username FROM admin WHERE username='$username' AND
password='$passwordc'";
$result2 = $conn->query($query);
if ($result2->num_rows != 0) {
session_start();
$_SESSION["username"] = $user;
header("Location:admin_view.php");
}else{
$Message = urlencode("user name password invalid!");
header("Location:login.php?Message=".$Message);
}
}
if your values successfully stored in session then you can use like
session_start();
if(!isset($_SESSION['username']))
{
header("Location: login.php");
}
on everypage top
you must store name from query into session
I have session page with these code
session_start();
if (!isset($_SESSION['id'])){
header('location:order.php');
}
$ses_id = $_SESSION['id'];
I included it into my login page (order.php)
<?php include('session.php'); ?>
Here is the login scripts and functions
$username = clean($_POST['username']);
$password = md5($_POST['password']);
$apollos=$username;
$query=Login($username,$password);
$count = mysql_num_rows($query);
$row = mysql_fetch_array($query);
$phone=$row['Contact_Number'];
DeleteActivation($username);
if ($count > 0) {
$_SESSION['id'] = $row['memberID'];
UserPin($username,$pin,$member);
$From='eFarms';
$Message='Your User Login Pin from St. Apollos eFarms is '.$pin;
die("<script>location.href = 'login_sms.php'</script>");
session_write_close();
} else {
session_write_close();
}
Here is my Pin Validation Page
<?php include('header.php'); ?>
pin = clean($_POST['pin']);
$query=CheckPin($username,$pin,$member);
$count = mysql_num_rows($query);
$row = mysql_fetch_array($query)
if ($count > 0) {
$_SESSION['id'] = $row['memberID'];
die("<script>location.href = 'user_home.php'</script>");
session_write_close();
} else {
session_write_close();
}
Someone should please examine these codes, correct and show me how to receive the session to the USer Home Page as Username.
First, as provided by others, ur using very bad and insecure method !
Try to use PDO which is much easier (when u understand how it work) and it's much more secure !
Second, ur coding is not so clean, I think that's why u can't find the problem urself !
And finally, I think ur missing :
session_start();
in some part of ur code !
Before session start you have to check the session is already started or not like below in each script or in common script file.
if (!isset($_SESSION)) {
session_start();
}
Edited:
the above condition is not needed as it is checking internally as descripe in the documentation - http://php.net/manual/en/function.session-start.php
session_start();
When I try to display the username of a logged-in user I get 'Welcome, 1' where 1 should be the username of the person logged in.
This is my code in the members.php. The commented out line doesn't work either.
<?php
require_once('include.php');
?>
<?php
// echo "welcome, {$_SESSION['username']}";
$user = $_SESSION['username'];
echo "Welcome $user";
?>
The user is logged in, I wonder if I've made a mistake in the check-login page.
The code for the check_login page is:
<?php
require_once('include.php');
$username = trim($_POST['user']);
$password = trim($_POST['pass']);
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$sql="SELECT * FROM user WHERE username='$username' and password='$password';";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count !== 0){
$_SESSION['logged-in'] = true;
header("location:members.php?user=$username");
exit;
}
else {
$_SESSION['logged-in'] = false;
header("location:login_again.php");
exit;
}
?>
which redirects to the members.php page upon successful login.
Anybody have any ideas why the username is '1' everytime?
Many thanks
there needs to be a session_start() somewhere at the top of your code
<?php session_start();
require_once('include.php');
?>
<?php
// echo "welcome, {$_SESSION['username']}";
$user = $_SESSION['username'];
echo "Welcome $user";
?>
you also need to set it before accessing it with session_start at the top of this file also
if($count>0){
$_SESSION['username']=$username;
$_SESSION['logged-in'] = true;
header("location:members.php?user=$username");
exit;
}
your code is open for sql injection attacks, Use prepared statements instead
In your check_login page I don't see either session_start and the code for saving username into session so that you can retrieve it on the other page.
In check_login page please add:
session_start();
at the start and then set:
$_SESSION['username'] = $username;
so that you can retrieve and display it on the other page.
Please check following points.
Make sure you set username in the Session variable.
From your code, I do not see any line like following:
$_SESSION['username'] = $username
Without setting, you can get nothing.
If you did session_start() before using $_SESSION variable.
session_start() is required function to be called if you gonna use $_SESSION variable.
So i'm writing a simple login script and I ran into some problems. I was able to create the login.php file that works with this dashboard.php file below. Let me describe the scenario: User come into the main page, which is the login page. Enters username and password. If entered correctly user will see the output "dashboard succesfull". If entered wrongly it will redirect them to loginfailed.php. Problem is that the browser does not remember that the user has already been logged in. If I re-enter this page, it will directly goes to loginfailed.php. So my obivous n00b question here is......is there a way to make the browser remember that the user has already been logged in?
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
$dblink = mysql_connect("localhost", "root", "");
mysql_select_db("user",$dblink);
$sql = "select * from members where username = '$username' and password = '$password'";
$result = mysql_query($sql) or die ( mysql_error() );
$count = 0;
while ($line = mysql_fetch_assoc($result)) {
$count++;
}
if ($count == 1) {
$_SESSION['loggedIn'] = "true";
echo "<a href='dashboard.php'>dashboard succesfull</a>";
} else {
$_SESSION['loggedIn'] = "false";
header("Location: loginfailed.php");
}
?>
Sure. You just need to put, at the top of the page but below session_start(), something like:
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] == 'true') {
# do something. maybe redirect and then exit?
}
Also, I'd suggest using a session name and escaping the username and password before putting them in your SQL.
I'm trying to make a login and logout script for a page but for some reason its not working very well for me. it seems to work fine until I try to logout. it seems to destroy the session variables, but it still lets me view the page.
heres my login code:
Code:
login.php
<?php
// Use session variable on this page. This function must put on the top of page.
session_start();
////// Logout Section. Delete all session variable.
session_destroy();
$Name=$_POST['Name'];
$Pass=$_POST['Pass'];
// To protect MySQL injection (more detail about MySQL injection)
$Name = stripslashes($Name);
$Pass = stripslashes($Pass);
$Name = mysql_real_escape_string($Name);
$Pass = mysql_real_escape_string($Pass);
$sql="SELECT * FROM reg1 WHERE uname='$Name' and pass='$Pass'";
$result=mysql_query($sql);
if(mysql_num_rows($result)!='0') // If match.
{
session_register("uname"); // Craete session username.
header("location:loged.php"); // Re-direct to loged.php
exit;
}else{ // If not match.
echo '<script type="text/javascript">
window.alert("Wrong UserName And Password");
window.location="index.php"
</script>';
}
// End Login authorize check.
?>
logout.php
<?php
// Inialize session
session_start();
// Delete certain session
unset($_SESSION['uname']);
// Delete all session variables
session_destroy();
// Jump to login page
header("Location: index.php?msg=Successfully Logged out");
}
?>
thanks to every one...
You are setting the session, but you are not checking it any where that whether it is set or not. means you are not checking that user is logged in or not.. you need to do like this
if (!isset($_SESSION['uname'])) /*If uname not set then it is a guest*/
{
//page contents for guest user
}
else
{
//page for authenticated user.
}
session_register() is deprecated as of PHP 5.3.0. Replace:
session_register("uname"); // Craete session username.
with:
$row = mysql_fetch_assoc($result);
$_SESSION['uname'] = $row['uname'];
Log out with (replacing session_destroy()):
////// Logout Section.
unset($_SESSION['uname']);
The final result will look like:
<?php
// Use session variable on this page. This function must put on the top of page.
session_start();
// Logout Section
if (isset($_SESSION['uname']))
unset($_SESSION['uname']);
// Login Section
$Name=$_POST['Name'];
$Pass=$_POST['Pass'];
// To protect MySQL injection (more detail about MySQL injection)
$Name = stripslashes($Name);
$Pass = stripslashes($Pass);
$Name = mysql_real_escape_string($Name);
$Pass = mysql_real_escape_string($Pass);
$sql="SELECT * FROM reg1 WHERE uname='$Name' and pass='$Pass'";
$result=mysql_query($sql);
if(mysql_num_rows($result)!='0') // If match. {
$row = mysql_fetch_assoc($result);
$_SESSION['uname'] = $row['uname'];
header("Location: loged.php"); // Re-direct to loged.php
exit;
} else { // If not match.
echo '<script type="text/javascript">
window.alert("Wrong UserName And Password");
window.location="index.php"
</script>';
}
?>
Logout script (syntax error fixed and session_destroy(); since unnecessary):
<?php
// Inialize session
session_start();
// Delete certain session
if (isset($_SESSION['uname'])) {
unset($_SESSION['uname']);
}
// Jump to login page
header("Location: index.php?msg=Successfully Logged out");
?>
How to check if logged in:
session_start();
if (isset($_SESSION['uname']))
{
// logged in
}
else
{
// not logged in
}
In your page that you want to be accessed only by logged in user, do you check the value of $_SESSION['uname'] ?
I think only session_destroy(); function is good enough to log you out. You need not to unset the 'uname'. And for those pages that will come after user logged in then you must apply some session check functionality at the top of each page...
if uname is the value you use to validate if the user is logged you should try to put first:
session_destroy(); and then the unset($_SESSION['uname'])
I hope this works for you....