I've got a login script that puts user details into session variables. Today I moved the website to a new host, and now my coding doesn't work. This is the best I can do, and it still doesn't work
main_login.php:
(script above here gets all the $info from the database. So far it is working)
if($count==1){
session_start();
$_SESSION['username'] = $info['username'];
$_SESSION['given'] = $info['given_name'];
$_SESSION['family'] = $info['family_name'];
$_SESSION['profile'] = $info['profile'];
$_SESSION['adultchild'] = $info['adultchild'];
$_SESSION['id'] = $info['id'];
header("location:welcome.php");
}
welcome.php:
// Check if session is not registered , redirect back to main page.
// Put this code in first line of web page.
session_start();
if(!isset($_SESSION['username'])){
header("location:main_login.php");
}
The trouble is when I print any of the session variables nothing happens. I've even tried doing a var_dump($_SESSION) but it comes up as an empty array. Frankly I've spent all day on this and am stuck.
session_start();
if(!isset($_SESSION['username']));
header("location:main_login.php");
}
change to:
session_start();
if(!isset($_SESSION['username'])){
// ^ typing mistake
header("location:main_login.php");
}
Related
Is it possible to use a session in PHP to track how long a user has not been active (no movement/scrolling/clicking) for. Without having to include the php script in the top of every single page throughout the website. For example in my login script I set some session variables after a successful login:
login script:
if ($pwdCheck == true) {
// Starting a session now to be able to create the variables!
session_start();
// Then creating session variables.
$_SESSION['username'] = $row['username'];
$_SESSION['email'] = $row['email'];
$_SESSION['last_login_timestamp'] = time(); // testing this one here
}
Then in the top of each page throughout the website I have this:
<?php
require 'header.php'; // This includes my db login details
if((time() - $_SESSION['last_login_timestamp']) > 10){
echo $_SESSION['last_login_timestamp']; //nothing echo's at the mo
header('Location: scripts/logout-script.php');
}
?>
Logout script:
<?php
session_start();
session_unset();
session_destroy();
header("Location: ../index.php");
?>
Is this safe enough to use and is there a more efficient way of checking how long a user has been inactive for, than pasting the if((time() statement script in the top of each file?
I'm trying to create a user login system for use on a website I'm building. I have the login script and register script, but I'm having trouble with the logout and destroying the sessions.
Here's my index code. It gets the database info in config (doesn't do anything with it yet), then runs check-login to make sure the user is actually logged in. It has a logout button that routes to logout.php
<?php
include_once("config.php");
include_once("check-login.php");
session_start();
$username = $_SESSION["username"];
?>
<html>
<body>
<h1>
Hello <? echo $username ?>! We're still building, but feel free to... wait?
</h1>
<form action="logout.php">
<input class="logoutbutton" type="submit" value="Logout" />
</form>
</body>
</html>
Here is my check-login.php file. Notice that anytime I link back to the index, I'm using a $_GET to post some information into the address bar. There is no place where I simply go back to index.php
<?php
ob_start();
include_once("../myreadingplanner_config/config.php");
if(($_SESSION['username']) != null){ //If user is already logged in...
$username=$_SESSION['username'];
header("Location: index.php?Message=AlreadyLoggedIn$username");
}
else {
if(isset($_POST['username']) && strlen($_POST['username'])!=0){ //if username is valid
$username = $_POST['username'];
} else {
header('Location: login.php');
}
if(isset($_POST['password']) && strlen($_POST['password'])!=0){
$password = $_POST['password'];
} else {
header('Location: login.php');
}
$SQLString = "SELECT TOP(1) * FROM Users WHERE Username = '$username' AND Password = '$password'";
$result = sqlsrv_query($conn, $SQLString) or die ("");
if($result != null)
{
$_SESSION['username'] = $username;
header("Location: index.php?Message=YouLoggedIn$username");
} else {
header("Location: index.php?Message=UserLoginNotFound&Username=$username");
}
}
ob_flush();
?>
And finally here is my logout.php, which should (in theory) destroy the session, and head back to index.php. When it gets back to index.php, index.php will reroute to login.php using the include_once("check-login.php");
<?php
session_start();
session_destroy();
header('Location: index.php');
?>
Just looking at my logic, there SHOULD be an infinite loop in the check-login, right? Because if the user is logged in, it should reroute to index, which includes check-login, which reroutes to index, which... etc.
If you want to check out the site for yourself, please go to www.myreadingplanner.com, and use this info to login (user will be deleted eventually)
Username: StackUser
Password: password1
So functionality wise, login.php should NEVER be visible unless you have a valid session, and when it does, it should say 'Welcome $username!'. But if you hit the logout button on index, it will still keep the session open, but it will be null.
Any advice on either why logout doesn't seem to fully logout the user OR why it is logging the user out but is keeping the NULL $_SESSION around?
To remove sessions use
unset($_SESSION['SESSION_VAR'] );
session_destroy(); //closes the session and prevents session riding
For more information I'd research session riding as you should close your session as soon as you can to prevent this.
Also do not unset the entire session global array.
//don't do this
unset($_SESSION);
First, have a look at index.php file. in that file, change the code below:
include_once("config.php");
include_once("check-login.php");
session_start(); // move the session_start function and place at the top of the script
$username = $_SESSION["username"];
change it, so that it becomes like this:
session_start();
include_once("config.php");
include_once("check-login.php");
$username = $_SESSION["username"];
This problem occurs because at the file check-login.php you do not declare the function session_start();
I have tested this problem. And it works!
I built a PHP/MySql login system for a website I am working on and all was working fine. I took a month off from working on it, pulled it up last night, and all of a sudden it doesn't work. It recognizes if a wrong username or password was entered, but if you enter the correct information it redirects you to the login page again. Was there some update somewhere that I am unaware of? I did not change anything in any of my files. It was working perfectly a month ago, and with no change at all it doesn't work now. Any ideas?
UPDATE
It is working if I check the remember me box, but not if I don't I will paste my code below:
Login Script:
<?php
define('INCLUDE_CHECK',true);
require 'connect.php';
require 'functions.php';
session_name('TheLoginSession');
session_start();
// ---------- LOGIN ----------
if($_POST['submit']=='Login')
{
// Checking whether the Login form has been submitted
$err = array();
// Will hold our errors
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']);
$_POST['remembercheck'] = (int)$_POST['remembercheck'];
$storedsaltquery = mysql_fetch_assoc(mysql_query("SELECT rand FROM members WHERE usr = '".$_POST['username']."'"));
$storedsalt = $storedsaltquery['rand'];
// Escaping all input data
$row = mysql_fetch_assoc(mysql_query("SELECT id,compid,usr,firstName,level,yn FROM members WHERE usr='{$_POST['usernamelog']}' AND pass='".hash("sha256",$_POST['passwordlog'].$storedsalt)."'"));
if($row['id'])
{
// If everything is OK login
$_SESSION['usr']=$row['usr'];
$_SESSION['comp']=$row['compid'];
$_SESSION['id'] = $row['id'];
$_SESSION['name'] = $row['firstName'];
$_SESSION['usrlevel'] = $row['level'];
$_SESSION['new'] = $row['yn'];
$_SESSION['remembercheck'] = $_POST['remembercheck'];
// Store some data in the session
setcookie('Remember','remembercheck',time()+1209600,'/','.domain.com');
}
else $err[]='Wrong username and/or password!';
}
if($err)
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
echo header("Location: ../index.php");
exit;
}
Index Page:
<?php
define('INCLUDE_CHECK',true);
require 'includes/connect.php';
require 'includes/functions.php';
// Those two files can be included only if INCLUDE_CHECK is defined
session_name('TheLoginSession');
// Starting the session
session_start();
if($_SESSION['id'] && !isset($_COOKIE['Remember']) && !$_SESSION['remembercheck'])
{
// If you are logged in, but you don't have the Remember cookie (browser restart)
// and you have not checked the remembercheck checkbox:
$_SESSION = array();
session_destroy();
// Destroy the session
}
if(isset($_GET['logoff']))
{
$_SESSION = array();
session_destroy();
header("Location: index.php");
exit;
}
if($_SESSION['id'] && $_SESSION['new'] != 1){
header("Location: home.php");
exit;
}
?>
How can there be an update if nothing's changed?
Are you using a CMS or framework?
If it's all your own code, and you haven't changed anything, then nothing would have updated.
I've had an issue like this before but without more information, hard to know if it is the same issue. Mine had the symptom you describe (login with bad creds and get the authentication error, login with good creds and redirect back to login).
Mine was due to failing to include code to remove old session cookies. The login attempt 'works' but an old cookie also read and attempts to authenticate, fails (because it is too old), and kicks the user back to login.
If this is your issue, clear your site cookies and see if you can then log in.
If that works, you'll want to add some cleanup code to your logout and stale session handling. For instance, for logging out:
// per http://www.php.net/manual/en/function.session-destroy.php
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
session_destroy();
Again, just guessing at your issue here.
I am creating a simple login script, I have set everything up but I am having trouble with sessions.
At the end of the login check page I have the following code:
$count = mysql_num_rows($result);
if($count == 1){
$_SESSION["username"] = 'username';
$_SESSION["password"] = 'password';
header("location:success.php");
}else{
echo "Wrong username or password";
}
And on the success.php page I have the following:
<?php
session_start();
if (!isset($_SESSION['username'])) {
header ("Location: wrong.php");
}
?>
<html>
<body>
Login Successful
</body>
</html>
The problem is that when a correct user and pass is entered it takes you to wrong.php, whereas it needs to redirect to wrong.php when someone visits success.php without logging in.
I am quite new to sessions and would appreciate any help. Thanks.
You must make sure session_start() is present at the top of any document that requires using sessions..
So at the top of your login check page you need to include session_start();
I am using session_start(); at the top of my login page. After a user logs in, a message is displayed on screen which shows that the session is being set. But, I cannot carry sessions from page to page or can I echo out SID. It is a blank value. I would be grateful if someone could show me where I am going wrong. Thanks
<?php
$userpost = mysql_real_escape_string($_POST['user']);
if (!isset($_SESSION['user'])) {
session_start();
$_SESSION['user'] = $userpost;
}
echo $_SESSION['user'] .' '. 'Just logged in' . SID;
// Or maybe pass along the session id, if needed
?>
You have to have session_start(); on the very top of your code, after <?php. Since you are checking if the session is set without starting the sessions, your code will fail.
Is has to be like this:
<?php
session_start();
$userpost = mysql_real_escape_string($_POST['user']);
if (!isset($_SESSION['user'])) {
$_SESSION['user'] = $userpost;
}
echo $_SESSION['user'] .' '. 'Just logged in' . SID;
// Or maybe pass along the session id, if needed
?>
It's because you're always looking in $_POST for your user data.
Bring the session_start() out of that condition:
<?php
session_start();
$userpost = mysql_real_escape_string($_POST['user']);
if (!isset($_SESSION['user'])) {
$_SESSION['user'] = $userpost;
}
You said that you called session_start() at the top of your login page, but you did not mention your other pages. session_start() needs to be called at the top of every page in your application. I generally put my session_start() logic, along with a snippet of code for logging the user out after a period of inactivity, in an include file and then include it at the top of every page.
<? session_start();
if (isset($_SESSION["last_activity"]) && (isset($_SESSION["username"])) && ((time() - $_SESSION["last_activity"]) > 900))
{
unset($_SESSION["username"]);
}
else
{
$_SESSION["last_activity"] = time();
}
?>