I'm trying to get a user on my web shop to enter a username which will then be displayed on each page. I've started the session here in header.php and set the username variable:
session_start();
$_SESSION['username'] = $username;
$username = ''; //set blank variable to be filled in index
I'm then calling header.php in index.php using:
<?php
include "header.php";
?>
Inside of the logIn div I'm then asking for the username to be entered (no form to submit it yet, haven't gotten that far without running into the problem below). The script should show a message if the user isn't logged in alongside a form to log in, but if they have submitted a username to use then the form should display a welcome message:
<div class="logIn">
<?php
if (!isset($_SESSION['username'])) {
echo 'Welcome, '.$_SESSION['username'];
} else {
echo 'Sorry, You are not logged in.';
}
?>
</div>
I'm currently getting this error:
Notice: Undefined variable: username in /header.php on line 13
but I can't figure out why. I thought I'd declared it as empty, but even when I give it a value the if statement in index.php isn't working as intended.
How can I set up a simple session and accept a username variable (no password) which will then be displayed on index.php?
Your error is simple .
$_SESSION['username'] = $username;
$username = '';
You are trying to use $username before assigning it.
$username = '';
$_SESSION['username'] = $username;
Should be better !
I guess line 13 is this one $_SESSION['username'] = $username; ?
If you are assigning $username to $_SESSION['username'] it must be set somewhere before, I can't see that in your example.
Your code has to look something like this:
//declare $username
$username = "somename";
$_SESSION['username'] = $username;
Or if you set $username in a condition or something else you can try this:
$_SESSION['username'] = ( isset( $username ) ) ? $username : '';
Related
Whenever the user login on my page the username is stored as a $_SESSION variable like so:
$_SESSION['username'] = $username;
where $username is the email address of the user and further user is assumed to be logged in. What I have observed is that my user is automatically logged out instantly after logging in or after few times. Are my session variables lost or what other problem should be?
My session_start() is always at the beginning and there is no space above it, so this is not the problem.
The part of my login code when login is successful is:
if ($usererror != 1 && $passworderror != 1 && $conferror != 1) {
$_SESSION["username"] = $username;
$_SESSION["password"] = $password;
header('Location:/dashboard_test/index.php');
}
The first page that accepts login has the first few lines as:
session_start();
$username = $_SESSION['username'];
I'm creating a site that uses sessions to store login details - I know its a bad security practice but that'll be dealt with later; for now I just need to fix this issue. Page 1 gets the login details from a login form and stores them in a session. Page 2 is meant to display those variables, but I get these errors when trying to access the variables:
Notice: Undefined index: email in /customers/0/4/0/my-domain.com/httpd.www/upload-photo.php on line 10
Notice: Undefined index: password in /customers/0/4/0/my-domain.com/httpd.www/upload-photo.php on line 11
Here is the code - I've left off the unrelated parts:
Page 1
session_start();
var_dump($_SESSION);
ini_set('display_errors',1);
error_reporting(E_ALL);
// Just logged in
if($_POST["email"] != "" || $_POST["password"] != ""){
$email = strtolower($_POST["email"]);
$password = md5($_POST["password"]);
$_SESSION["email"] = $email;
$_SESSION["password"] = $password;
//echo "setting details from http post";
}else{
// Just redirected to this page
$email = $_SESSION["email"];
$password = $_SESSION["password"];
}
And page 2 where I'm getting the errors mentioned above:
session_start();
ini_set('display_errors',1);
error_reporting(E_ALL);
var_dump($_SESSION);
$_SESSION["advert"] = $_GET['id'];
echo $_SESSION["email"];
echo $_SESSION["password"];
I've searched SO and have made sure there are no spaces or whatever before my session_start();
By the way, if it helps my domain company that I'm using is One.com
$_SESSION["email"] and $_SESSION["password"] are set in the if, so in the case it is skipped you get this undefined indexes error (as elements with this indexes were not defined anywhere before).To get rid of this Notice you can use isset() function(also use it to validate $_POST user input). Example :
echo isset($_SESSION["email"]) ? $_SESSION["email"] : 'There is no element with key "email"';
P.S. Validating your POST input :
if(isset($_POST["email"]) && isset($_POST["password"])){}
Change condition to:
if(isset($_POST['email']) && isset($_POST['password'])){
//do login
}
else {
echo " Plese enter email and password";
}
For full:
Login.php
<?php
//here must be totaly clear, nothing can't be here
session_start();
if(isset($_POST['email']) && isset($_POST['password'])){
$_SESSION['email'] = $_POST['email'];
$_SESSION['password'] = $_POST['password'];
}
else {
echo "Please enter email and password";
}
//here must be form to login
Logged.php:
<?php
//here must be totaly clear, nothing can't be here
session_start();
if(!isset($_SESSION['email']) && !isset($_SESSION['password'])){
header("Location: Login.php?err=Please login to use members area");
}
else {
echo "You are logged in as:". $_SESSION['email'];
}
I solved the problem. When I was on one page I was on www.domain.com/page1 but when I was on the other page there was no www - domain.com/page2. This meant that session variables were not persisting. To fox this, I need to edit the htaccess file to redirect to www if there is no www in the URL.
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.
Another attempt at designing a user membership. Got to log in successfully, finds the data in the database. But in my index file, after logging in, it should check if I'm logged in and display links to my account instead of register and login. Here's the code:
<?php
session_start(); // Must start session first thing
// See if they are a logged in member by checking Session data
$toplinks = "";
if (isset($_SESSION['id'])) {
// Put stored session variables into local php variable
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '' . $username . ' •
Account •
Log Out';
} else {
$toplinks = 'Register • Login';
}
?>
And here is the login form code, where I think the problem is because it's not storing my session id:
<?php
if ($_POST['email']) {
//Connect to the database through our include
include_once "connect_to_mysql.php";
$email = stripslashes($_POST['email']);
$email = strip_tags($email);
$email = mysql_real_escape_string($email);
$password = preg_replace("[^A-Za-z0-9]", "", $_POST['password']);
// filter everything but numbers and letters
$password = md5($password);
// Make query and then register all database data that -
// cannot be changed by member into SESSION variables.
// Data that you want member to be able to change -
// should never be set into a SESSION variable.
$sql = mysql_query("SELECT * FROM users WHERE email='$email' AND password=
'$password'AND emailactivated='1'");
$login_check = mysql_num_rows($sql);
if($login_check > 0){
while($row = mysql_fetch_assoc($sql)){
// Get member ID into a session variable
$userid = $row["id"];
$_SESSION['id'] = $userid;
// Get member username into a session variable
$username = $row["username"];
$_SESSION['username'] = $username;
// Update last_log_date field for this member now
mysql_query("UPDATE users SET lastlogin=now() WHERE id='$userid'");
// Print success message here if all went well then exit the script
header("location: member_profile.php?id=$userid");
exit();
} // close while
} else {
// Print login failure message to the user and link them back to your login page
print '<br /><br /><font color="#FF0000">No match in our records, try again
</font> <br/>
<br />Click here to go back to the login page.';
exit();
}
}// close if post
?>
Once again I'm following someone's tutorial and trying to implement it to my website and this would be perfect if it worked. Please advice why the $toplinks aren't being set after logging in.
I think the problem is, that you have to include the session_start() in every file where you want to use your session. Otherwise its working in the file like a normal array but not global. In your form i can't see that you start your session.
Edit: You need this only if you have 2 files. When you have only one file and include the other page its working when you include in once on top.
If you want to log out, then you should create a logout file, and include
session_destroy();
probably add also a href to get redirection link by doing something like:
header('location:index.php'); // will return you to index as soon as you logout.
If anyone can make a better title, please edit it.
The issue I am having is being unable to show the users name in their post. Quick snip of code.
if (isset($_SESSION['username']) )
{
$name = $_SESSION['username'];
}
else
{
$name = $_POST['name'];
}
How can I make it when the user posts it check to see if there is a session and then displays their name in their post.
There's nothing particularly wrong with what you've done here. Does $_SESSION['username'] actually have a value?
Also, make sure when you are working with sessions that you call session_start() before saving or pulling session data.
<?php
session_start();
$_SESSION['username'] = 'Greg';
if (isset($_SESSION['username']) )
{
$name = $_SESSION['username'];
}
Please try the following
session_start();
if (isset($_SESSION['username']) )
{
$name = $_SESSION['username'];
}
else
{
$name = $_POST['name'];
$_SESSION['username'] = $name;
}
Then reload the page, $_SESSION['username'] now should contain the user name
Garrett am i right in thinking your route is create $_SESSION['name'] first and regardless unless they have logged in if so the $_SESSION['name'] becomes $_SESSION['username']
If I am right and you are creating $_SESSION['username'] on login all you need to do is check if $_SESSION['name'] = $_SESSION['username'] and if it does unset it example:
// YOUR LOGIN CODE TO CHECK ASSUME SQL QUERY OF SOME DESCRIPTION AND 'true' IS YOUR RESULT and 'false' NOT A USER
if(true) {
$_SESSION['username'] = $result;
if($_SESSION['name'] && $_SESSION['name'] == $_SESSION['username'] ){
unset($_SESSION['name'])
}
// ACTION TO GO TO PAGE
} else {
// YOUR ERROR ACTION
}