I have a login page which records the username that the user enters and adds it to a variable of $uname. However when the page after the login page loads, I cannot echo the $uname. For example, when i type
Welcome <?php echo $uname; ?>
it does not insert the username.
below is a copy of my login-validation code. but I am not sure if the $_SESSION variable is working correctly, or how to reference it in my profile.php file.
<?php
session_start();
$_SESSION['uname'] = $uname;
// Grab User submitted information
$uname = $_POST["uname"];
$pass = $_POST["pass"];
// Connect to the database
$con = mysql_connect("mysql.*********.co.uk","******","************");
// Make sure we connected succesfully
if(! $con)
{
die('Connection Failed'.mysql_error());
}
// Select the database to use
mysql_select_db("onedirectionaffection_members",$con);
$result = mysql_query("SELECT uname, pass FROM users WHERE uname = $uname");
$row = mysql_fetch_array($result);
if($row["uname"]==$uname && $row["pass"]==$pass)
header("Location: ../../profile/profile.php");
else
echo"Sorry, your credentials are not valid, Please try again.";
?>
If anyone could help I would be hugely thankful. Also, I am an absolute beginner at all of this so if you need anymore details I'll try my best to answer.
profile.php
<?php
session_start();
echo $_SESSION['uname'];
?>
<html>
<head>
<title>1D Affection</title>
<link rel="stylesheet" Type="text/css" href="../css/stylesheet.css" />
<link rel="stylesheet" Type="text/css" href="../css/font.css" />
<link rel="stylesheet" Type="text/css" href="../css/profile.css" />
</head>
<body bgcolor="white">
<div id="wrapperhead">
<div id="headcont">
<div class="logo">
<img src="../images/1DA logo ripped.png" height="150px">
</div>
<div class="subheading">
<img src="../images/1d subheading.png" height="150px">
</div>
</div>
</div> <!--END OF HEADER-->
<div id="nav">
<div class="navigation">
<ul>
<li><a class="nav" href="../index.html">Home</a></li>
<li><a class="nav" href="#">News</a></li>
<li><a class="nav" href="#">Fan-fiction</a></li>
<li><a class="nav" href="#">Gallery</a></li>
<li><a class="nav" href="#">Testimonials</a></li>
<li><a class="nav" href="http://www.onedirectionstore.com/" target="_blank">Store</a></li>
</ul>
</div> <!-- END OF MENU-->
<!-- END OF NAVIGATION-->
</div>
<div id="wrappercontent">
<div class="content">
<div class="maincont">
<div class="profcust">
<div class="profpic">
</div>
<div class="profinfo">
</div>
</div>
<div class="username">
Welcome <?php session_start(); echo $uname; ?>
</div>
<div class="story">
</div>
</div>
<div class="sidenav">
Coming Soon
</div>
</div><!--end of content-->
</div>
</body>
</html>
Seems like you haven't added session_start(); on top of your profile.php page.
Try like this
//profile.php
<?php
session_start();
echo $_SESSION['uname'];
This is probably a good part of the issue.
$_SESSION['uname'] = $uname;
$uname = $_POST["uname"];
Your setting your session's uname to blank on every load of that page. Put $_SESSION['uname'] = $uname; at the end of the code when it's validated.
1) You need to add a value to $uname first, then assign its value to $_SESSION element, so it's better be like this:
$uname = $_POST['uname'];
$_SESSION['uname'] = $uname;
or even like this:
$_SESSION['uname'] = $_POST['uname'];
2) As already mentioned, At profile.php you should also have session_start();
3) Make a clean exit like this:
header("Location: ../../profile/profile.php");
exit();
My bet is that it should be working fine after.
Some how, this is now working. From what I can figure out, the solution was to call in the $_SESSION variable, and then wrap that inside another variable. so
<?php
session_start();
$uname = $_SESSION['uname'];
?>
Thanks for all the help :D
session_start(); needs to be inside all pages using sessions.
I tested the following:
<?php
session_start(); // page_2.php
echo "Welcome " . $_SESSION['uname'];
?>
In conjunction with my test page: page_a.php
<?php
session_start();
$uname = "FRED";
$_SESSION['uname'] = $uname;
?>
CLICK
Echo'ed Welcome FRED on page 2.
I also noticed you have another instance of session_start(); in your page profile.php, remove it because you will be starting a new session while overwriting your first.
<div class="username">
Welcome <?php session_start(); echo $uname; ?>
</div>
Therefore you should be using:
$uname = $_SESSION['uname'];
in conjunction with:
<div class="username">
<?php echo "Welcome " . $_SESSION['uname']; ?>
</div>
As berkes stated in this comment you have a security issue:
$uname = $_POST["uname"];
$pass = $_POST["pass"];
Change it to:
$uname = mysql_real_escape_string($_POST['uname']);
$pass = mysql_real_escape_string($_POST['pass']);
MySQL_ functions are deprecated, therefore using MySQLi_ with prepared statements is highly suggested or PDO.
Do read the following articles:
How can I prevent SQL injection in PHP?
On owasp.org
Related
I want to make the logout li to be shown only if user is logged in. Menubar is under the leftsidebar.php file. The file is required by the index.php and the con_login.php does the verification.
I'm new to php so i'm not sure about how to do that. I tried some lines of code i find online but doesn't work
leftsidebar.php
<nav id="leftsidebar">
<ul class="menu">
<li>Home Page</li>
<li>Δημόσια Σελίδα</li>
<li>Σελίδα Χρήστη</li>
<li>Logout</li>
</ul>
</nav>
index.php
<?php session_start(); ?>
<?php
$title="Super eShop - Home Page";
require('part_header.php');
require('part_leftsidebar.php');
?>
<main id="main">
<h2>Home Page</h2>
<?php echo_msg(); ?>
<?php if(!isset($_SESSION['username'])) { ?>
<p>Please login:</p>
<form name="form1" method="post" action="con_login.php">
<p>username: <input type="text" name="username"/> </p>
<p>password: <input type="password" name="password"/> </p>
<p><input name="submit" type="submit"></p>
</form>
<?php } else echo '<p> Hello ' .$_SESSION['username'].'</p>';?>
</main>
<?php require('part_footer.php'); ?>
con_login.php
<?php
if (!isset($_SESSION['username']) && isset($_POST['username']) && isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$authorised=false;
if ($username=='test'){
$authorised=true;
session_start();
$_SESSION['username']=$username;
}
if ($authorised==true){
header("Location: page_user.php");
exit();}
else{
header("Location: index.php?msg=Αποτυχημένη διαπίστευση χρήστη!");
exit();}
}
else{
session_start();
session_destroy();
header("Location: index.php?msg=Πρόβλημα σύνδεσης. Ξαναδοκιμάστε!");
exit();
}
?>
I'm not quite sure if I get your question, but if $authorised says whether you're logged in or not, you could write s.th. like the following in your HTML / PHP file.
<nav id="leftsidebar">
<ul class="menu">
<li>Home Page</li>
<li>Δημόσια Σελίδα</li>
<li>Σελίδα Χρήστη</li>
<?php echo ($authorised ? '<li>Logout</li>' : ''); ?>
</ul>
</nav>
But this would require, that you set $authorised every time you call the page, alternatively, you could do it with a $_SESSION
If your code works as is, then you just need to set this in your sidebar
<?php if(isset($_SESSION['username'])) { ?>
<li>Logout</li>
<?php } ?>
i have declared a session_start() function in the start of both the pages but still the variable is not passing on to the session variable please help
this is where i have included my login.php
<?php
include("template/header.php");
include("template/content.php");
include("template/footer.php");
include("login.php");
?>
this my login.php file where i have passed $email variable to SESSION
<?php
session_start();
include("includes/connection.php");
if(isset($_POST['login'])){
$email= mysqli_real_escape_string($con,$_POST['email']);
$pass= mysqli_real_escape_string($con,$_POST['pass']);
$select_user = "select * from users where user_email= '$email' AND
user_pass='$pass' AND status='verified'";
$query = mysqli_query($con,$select_user);
$check_user= mysqli_num_rows($query);
if($check_user===1){
$_SESSION['usermail']=$email;
echo "<script>window.open('home.php','_self')</script>";
} else {
echo "<script>alert('incorrect details try again')</script>";
}
}
?>
and this is where i have tried to access the session variable but it says undefined:usermail but i dont understand i am giving the session_start() at the beginning and have checked that $email is successfully getting its value from the database then why this is not working
<?php
session_start();
include("includes/connection.php");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome User!</title>
<link rel="stylesheet" href="styles/home_style.css" media="all"/>
</head>
<body>
<!--container starts-->
<div class="container">
<!--header wrapper starts here-->
<div id="head_wrap">
<!--header starts-->
<div id="header">
<ul id="menu">
<li>Home</li>
<li>Members</li>
<strong>Topics:</strong>
<?php
$get_topics = "select * from topics";
$run_topics= mysqli_query($con,$get_topics);
while($row=mysqli_fetch_array($run_topics)){
$topic_id = $row['topic_id'];
$topic_title = $row['topic_name'];
echo "<li><a href='topic.php?
topic=$topic_id'>$topic_title</a></li>";
}
?>
</ul>
<form method="get" action="results.php" id="form1">
<input type="text" name="user_query" placeholder="search a
topic"/>
<input type="submit" name="search" value="search"/>
</form>
</div><!--header ends-->
</div><!--head wrap ends-->
<!--content area starts-->
<div class="content">
<!--user timeline starts here-->
<div id="user_timeline">
<div id="user_details">
<?php
$user=$_SESSION['usermail'];
var_dump($_SESSION);
$get_user="select * from users where user_email='$user'";
$run_user= mysqli_query($con,$get_user);
$row=mysqli_fetch_array($run_user);
$user_id= $row['user_id'];
$user_name= $row['user_name'];
$user_country= $row['user_country'];
$user_image= $row['user_image'];
$register_date= $row['user_reg_date'];
$last_login= $row['user_last_login'];
$user_posts="select * from posts where user_id='$user_id'";
$run_posts = mysqli_query($con,$user_posts);
$posts =mysqli_num_rows($run_posts);
//getting the number of unread messages
$sel_msg = "select * from messages where receiver='$user_id' AND
status='unread' ORDER by 1 DESC";
$run_msg = mysqli_query($con,$sel_msg);
$count_msg = mysqli_num_rows($run_msg);
echo "
<center>
<img src='users/default.png' width='200' height='200'?>
</center>
<dev id='user_mention'>
<p><strong>Country:</strong>$user_country</p>
<p><strong>Last Login:</strong>$last_login</p>
<p><strong>Member Since:</strong>$register_date</p>
<p><a href='my_messages.php?inbox&u_id=$user_id'>Messages
($count_msg)</a></p>
<p><a href='edit_profile.php?u_id=$user_id'>Edit my account</a>
</p>
<p><a href='logout.php'>Logout</a></p>
</div>
";
?>
</div><!--user details ends here-->
</div><!--user timeline ends here-->
</div><!--content area ends-->
</div><!--container ends-->
</body>
</html>
<?php
session_start();
if(isset($_SESSION['login']))
{
include_once('includes/header.php'); ?>
<!DOCTYPE html>
<html>
<body>
<div id="mainframe">
<img src="img/header.png">
<div id="menu">
<?php include_once('includes/navbar.php'); ?>
</div>
<div id="content">
<h3>Shopping Cart</h3>
</div>
</div>
<?php include_once('includes/footer.php'); ?>
</body>
</html>
<?php }
else
{
header('location: login.php');
}
?>
Here is my small PhP code I've got at the moment, my login session is $_SESSION['login'].
And I'd like to display : Logged in As on my page when they are logged in, I've tried several things but it didn't work out.
Does anyone know a simple method / solution for this?
Put this somewhere in your if statement.
It will show Logged in as User at right top corner of page
<div style="position:absolute; right:0px; top:0px;">
<?php echo "Logged In as". $_SESSION['login']; ?>
</div>
U need to pass username using SESSION variable for the same
write a simple sql query to get the username from any variable you are taking from user to make sure that the particular user is the correct user.i am taking password.
$query = "SELECT name FROM users WHERE password='$password'";
$username = mysql_result(mysql_query($query),0);
$_SESSION['username'] = $username;
than proceed as you are doing
<?php
session_start();
if(isset($_SESSION['login']) && isset($_SESSION['username']))
{
echo "logged in as".$_SESSION['username'];
}
I am trying to create a log in form which allows user to log in, based on their registration details (which is saved in a flat file) and this what I have come up with so far.
At the moment the this code allow any user to log in even when there are not on the registration.
<html>
<body>
<table align="center">
<tr>
<th><h3>MY ACCOUNT</h3></th>
</tr>
<form action = "index.php" method = "POST">
<tr>
<td>Username:</br><input type="text" name="username"></br></td>
</tr>
<tr>
<td>Password:</br><input type="password" name="password"></br></td>
</tr>
<tr>
<td align = "center"><input type="submit" name = "submit"></td>
</tr>
</form>
</table>
<?php
if (isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
$file = file_get_contents("data.txt");
if(empty($_POST['username']) || empty($_POST['password'])){
die (print '<script> alert ("You must enter both your username and password to continue."); window.location="index.php"; </script>');
}
if(!strstr($file, "$username#$password")) {
die(print '<script> alert ("Wrong"); window.location="index.php"; </script>');
}
else {
header("Location: wacc.php");
}
}
?>
Please what is wrong with code
In your other post here you were given a suggestion to use a script called PHP Login. This would help solve a lot of your problems if you follow this suggestion.
I suggest you change the strstr to the strpos function, it's the desired function for checking if a string occurs, and works ok.
So:
if(!strstr($file, "$username#$password")) {
To:
if(strpos($file, "$username#$password") === false) {
Note the === , it needs to be false, not 0 or ''. See for more info http://www.php.net/function.strpos
Edit
The logging in always is most of the time true, because whats happening is that your searching for if the specified string is occurring in your text document. Now, incase that if you leave both fields $username and $password empty, it will be true ( is there a # in the text document? Yes. ) This also applies when you write a valid part username or password.
I would suggest you rethink this login system, and use a PHP array or database to match a valid username and password. If you just want a simple bump for visitors, try adding an delimiter.
In your username and password list for example:
#username#password#
And as strpos function
if(strpos($file, "#$username#$password#") === false) {
With adding the # before and after, your script always nows where the username must start and must end, and the same for the password. If the username was too short, too long, or empty the # gets added anyway and will the strpos will then be wrong (is there an ### in the list? No.).
you could use facebook login instead.
I dont think a flat file login could ever be totally secure. /shrug.
Facebook is really easy though and is a multi-billion dollar corporation that pays programmers to make it as secure as possible. No need to worry about security at all.
<?php
require 'fbconfig.php'; // Include fbconfig.php file
?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>Login with Facebook</title>
<link href="http://www.bootstrapcdn.com/twitter-bootstrap/2.2.2/css/bootstrap-combined.min.css" rel="stylesheet">
</head>
<body>
<?php if ($user): ?> <!-- After user login -->
<div class="container">
<div class="hero-unit">
<h1>Hello <?php echo $fbuname; ?></h1>
<p>Welcome to "facebook login" tutorial</p>
</div>
<div class="span4">
<ul class="nav nav-list">
<li class="nav-header">Image</li>
<li><img src="https://graph.facebook.com/<?php echo $user; ?>/picture"></li>
<li class="nav-header">Facebook ID</li>
<li><?php echo $fbid; ?></li>
<li class="nav-header">Facebook Username</li>
<li><?php echo $fbuname; ?></li>
<li class="nav-header">Facebook fullname</li>
<li><?php echo $fbfullname; ?></li>
<div>Logout</div>
</ul></div></div>
<?php else: ?> <!-- Before login -->
<div class="container">
<h1>Login with Facebook</h1>
Not Connected
<div>
Login with Facebook</div>
</div>
<?php endif ?>
</body>
</html>
I'm new to php and I'm following a tutorial to make a login panel. It works fine on the demo website but when I download the code and run on my machine, 5 notices popped up. They all look like: "Notice: Undefined index: submit in C:\xampp\htdocs\myfolder\demo.php on line 24".
From other programming experiences I think that these means I didn't define the variables before using them. However, these variables seem to be existing in the system (from what I understand reading other questions >-<).
I attached my code below and marked the undefined index on the right. Can anyone help me explain what's wrong with the code and how can I solve it? Thanks a lot!
<?php
session_name('Login');
session_start();
if($_POST['submit']=='Login') //undefined submit
{
$err = array();
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
// Escaping all input data
$row = mysql_fetch_assoc(mysql_query("SELECT id,user FROM writers WHERE user='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));
if($row['user'])
{
$_SESSION['user']=$row['user'];
$_SESSION['id'] = $row['id'];
// Store some data in the session
}
else $err[]='Wrong username and/or password!';
}
if($err)
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
header("Location: demo.php");
exit;
}
$script = '';
if($_SESSION['msg'])
{
// The script below shows the sliding panel on page load
...
}
?>
<head>
......
</head>
<body>
<!-- Panel -->
<div id="toppanel">
<div id="panel">
<div class="content clearfix">
<?php
if(!$_SESSION['id']): //undefined id
?>
<div class="left">
<form class="clearfix" action="" method="post">
<h1>Writer Login</h1>
<?php
if($_SESSION['msg']['login-err']) //undefined login-err
{
echo '<div class="err">'.$_SESSION['msg']['login-err'].'</div>';
unset($_SESSION['msg']['login-err']);
}
?>
//Login form
</form>
</div>
<?php
endif;
?>
</div>
</div> <!-- /login -->
<!-- The tab on top -->
<div class="tab">
<ul class="login">
<li class="left"> </li>
<li>Hello <?php echo $_SESSION['user'] ? $_SESSION['user'] : 'Guest';?>!</li> //undefined user
<li class="sep">|</li>
<li id="toggle">
<a id="open" class="open" href="#"><?php echo $_SESSION['id']?'Open Panel':'Log In';?></a> //undefined id
<a id="close" style="display: none;" class="close" href="#">Close Panel</a>
</li>
<li class="right"> </li>
</ul>
</div> <!-- / top -->
</div> <!--panel -->
Sorry for the long code! I really not sure which ones will be relevant to the problem and do not dare to delete more. Thank you for your patience!
You need to check if that variable exists before you use it. You would use isset() for that:
if(isset($_POST['submit']) && $_POST['submit']=='Login')
If you're just checking to see if the form was submitted you could just check to see if the page was request via POST instead:
if('POST' === $_SERVER['REQUEST_METHOD'])
You can also put # in front of your array references that can be null, for example:
if(#$_POST['submit']=='Login')
This will supress the warning