I have a login script in Php. If the credentials are correct then the session is started, session variables are set and then redirected to the profile page. In the profile page, I have a script that redirects the user back to login page if they have not logged in.
Now, whenever I enter the correct credentials of the user and click on login, it redirects me back to the login page. To solve it, I commented out the code which was responsible for the redirection back to the login page. As a result, I got access to the profile page but I could not access the session variables.
And sometimes this code runs perfectly while sometimes it shows the above-stated problem.
The login code is as shown in the picture :
session_start();
require_once 'includes/config.php';
if(isset($_POST['login'])){
$user = trim($_POST['username']);
$pass = trim($_POST['password']);
$ch = $_POST['position'];
$stmt = $db->prepare("SELECT C_Name, PAN_id, Password FROM master_registration WHERE PAN_id = ?");
$stmt->bindParam(1,$user);
$stmt->execute();
$row = $stmt->fetch();
$username = $row["PAN_id"];
$Name = $row["C_Name"];
$hash = $row["Password"];
if(password_verify($pass, $hash)) {
session_start();
$_SESSION["loggedin"] = true;
$_SESSION["username"] = $username;
$_SESSION["Name"] = $Name;
header("Location: main_folder/master/profile.php");
Login page code
The profile page code is as shown in the picture:
session_start();
require_once '../../includes/config.php';
if(!isset($_SESSION['loggedin']) && $_SESSION['loggedin'] !== true){
header("location:../../index.php");
exit;
}
$user = $_SESSION['username'];
profile page code
The seems fine, but there is a problem in sessions, plus it works in localhost but when I hosted in CPanel the problem starts.
Please help anyone...
Sometimes the Cpanel need config on the PHP SESSION, php.ini
First yo can check the CPanel session.save_path and enabel output_buffering .
to used phpinfo()
Your code its correct. but if try session_start(); to inculed the config.php file
Change your profile pic code with this code...
Your logic is incorrect thatswhy you are redirected everytime
if(!$_SESSION['loggedin']) {
header("location: ../../index.php");
exit() ;
}
Related
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've been following some tutorials and managed to get my login and logout scripts working. What I"m now trying to do it get it to only allow access to pages when the user is logged in. Right now it's just redirecting users to the login page every time, which tells me that the session isn't being set or or my code is just wrong (and I've tried everything I can think of)
This is the login.php script that my form runs in order to set the session:
<?php
// establishing the MySQLi connection
require 'init.php';
if (mysqli_connect_errno())
{
echo "MySQLi Connection was not established: " . mysqli_connect_error();
}
// checking the user
if(isset($_POST['login'])) {
$username = mysqli_real_escape_string($conn,$_POST['username']);
$pass = mysqli_real_escape_string($conn,$_POST['password']);
$sel_user = "select * from login where username='$username' AND password='$pass'";
$run_user = mysqli_query($conn, $sel_user);
$check_user = mysqli_num_rows($run_user);
if($check_user>0) {
$_SESSION['username']=$username;
echo "<script>window.open('index.php','_self')</script>";
} else {
echo "<script>alert('Sorry. Your username or password is not correct, try again!')</script>";
}
}
?>
And this is what I'm including at the top of every page:
<?php
session_start();
if (!(isset($_SESSION['username']) && $_SESSION['username'] != '')) {
header ("Location: account-login.php");
}
require 'init.php';
?>
I switched the login.php file from directing to a page to a popup telling me that I logged in and I get the popup, so the user and password are registering fine, it's just not storing the session somehow. Any ideas? Thanks!
OK, so I got it to work finally!
Apart from all the comments (which helped a TON), I also decided to change the name I was setting in $_SESSION. I think it may be because the session name matched the name or POST data and that eas causing a conflict somewhere.
Changed this:
$_SESSION['username']=$username;
Which I think conflicted to this:
$_SESSION['session_id']=$username;
Worked!
THANK YOU!!!!!!!
Okai, so I attempted to post this a bit earlier, although my question has changed slightly.
I have identified the problem to be in between my login.php (where I assign the $_SESSION value) and my members.php page (where I try to pick up the $_SESSION variable again, but fail to recover it). The way I identified this problem was by running a var dump on session in my members.php file which gave me 0. I also did this after I asign the value in login.php and I got the asigned value as an outcome.
If you help me out I will really appreciate it!
This is my login.php page:
<?php
session_start();
require('connect.php');
$username = $_POST['username'];
$password = $_POST['password'];
if (isset($username) && isset($password))
{
$query = mysql_query("SELECT * FROM login WHERE username='$username' AND password='$password'");
$result = mysql_num_rows($query);
if($result > 0)
{
echo "You have been logged in. <a href='members.php'>Go to the members page</a>";
$username = $_SESSION['login'];
}
else
{
echo "Password is incorrect. Try again.";
}
}
else
{
echo "You have to enter your username and password. Try again";
}
?>
This is my members.php page:
<?php
session_start();
if (isset($_SESSION['login']))
{
echo "Welcome " . $login . " | <a href='logout.php'>Logout</a>";
}
else
{
header('Location: index.php');
}
?>
Solved in Chat:
Turns out var_dump(is_writable(session_save_path())); returned bool(false).
The session_save_path() was /var/php_sessions/.
realpath(dirname(__FILE__)); was /hermes/bosoraweb124/b185/dom.gjertgjersundcom/public_html.
I tried moving the session save path -- however for some reason the folder within public_html couldn't be written, same with read (couldn't read). In any case, it's a bad idea to have sessions in the public folder for everyone to see anyway.
I recommended the OP contact their host provider to run the command of chmod 766 -R /var/php_sessions/.
Solved: The staff at his webhost applied the permissions and it works fine now.
Your session "login" variable is not set because you never set it in your login file...
You should specifically set it with $_SESSION['login'] = "blah";
I assume your problem is you meant to set login and not the username when you log in the user...
swap
if($result > 0)
{
echo "You have been logged in. <a href='members.php'>Go to the members page</a>";
$username = $_SESSION['login'];
}
with
if($result > 0)
{
echo "You have been logged in. <a href='members.php'>Go to the members page</a>";
$_SESSION['login'] = $username;
}
Then you should be able to access your "login" session variable from your member page.
Also on your member page I do not see you set your $login variable. So I assume that would be a blank space and you meant to echo your session login variable with $_SESSION['login'].
The login system I have created logs the user in fine initially, the user is redirected to an index as expected. However when the user clicks on a navigation link to navigate to another page (which is restricted) the user is redirected to the login page. When they login for a second time, every and any page can be accessed properly.
I tried printing out the session id and did a dump of the session array. I noticed when the user goes to the login in page a first they have session id "x", then they are redirected to the index page where they still have the session id "x". However when they try to navigate to another page on the site they are redirected to the login page and have the session id "y". When they login for a second time every pages shows them having session id "y".
What can be causing the session id to be changed after the user is redirected?
Here is my login script.
session_start();
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string(md5($_POST['password']));
$submit = $_POST['submit'];
$error = '';
if(isset($submit)){
// Check if fields are filled out
if($username == '' or $password == ''){
$error = 'Please enter a Username and Password';
}else{ // Proceed with login process
// See if user exists
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
if(mysql_num_rows($query)<1){
echo 'Invalid Username/Password Combination';
}else{ // Grab user's information
$user = mysql_fetch_assoc($query);
if($password == $user['password']){//Login Success, Redirect and set Session Vars
$_SESSION["loggedIn"] = true;
$_SESSION['username'] = $user['username'];
$_SESSION['name'] = $user['first'];
$_SESSION['auth'] = $user['authorization'];
session_write_close();
header("Location: home.php");
exit;
}else{
$error = 'Invalid Username/Password Combination';
}
}
}
}
and the page restriction script:
session_start();
if(isset($_SESSION["loggedIn"])){
echo '<div align="right" id="user">Welcome '.trim($_SESSION['name']).'! Sign Out | Edit Account</div>';
}else{
header("Location: login.php");
}
Try setting the session variables on the restricted page.
session_start();
$_SESSION["loggedIn"]
$_SESSION["loggedIn"];
$_SESSION['username'];
$_SESSION['name'];
$_SESSION['auth'];
for debugging purpose please set print_r($_SESSION) on each page and see if it is printing correctly... you can set a value and see if it is carrying cross pages...
I was having very similar problem and discovered that having GET parameters in the link to the page that was not recognizing set session values was the problem. Although session_start() was the first line on the page script causing a need to log in a second time, the GET parameters in the link on the previous page were being processed as the first lines on the requested page (at least that is my guess as to why).
I have tried a session.php script which runs at the head of each page in my website to verify that the user has logged in before they can browse the site. However, now the process_login script won't load the secure landing page and it just reloads to the login page. I believe that my secure session is not being set correctly. Can someone further explain how this works to me?
This is the script, process_login, which executed when a user clicks login:
<?php
// Initialize session
session_start();
// Require database connection settings
require('config.inc');
// Retrieve email and password from database
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string(md5($_POST['password']));
$query = "SELECT * FROM $table WHERE email='$email' AND password='$password' LIMIT 1";
$result = mysql_query($query);
// Check email and password match
if(mysql_num_rows($result)) {
// Set email session variable
$_SESSION['email'] = $_POST['email'];
// Jump to secured page
header('Location: home.php');
}
else {
// Jump to login page
header('Location: index.php');
}
?>
and this is the session.php script which is in the head of each page that requires a user to be logged in:
<?php
if (isset($_SESSION['email']) == 0) {
// Redirect to login page
header('Location: index.php');
}
?>
You need to include the code
session_start();
in the your file session.php to access your session variables
Or you should make sure that session auto start is enabled on your php configuration.