Allow content with $_Session - php

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!!!!!!!

Related

PHP session resets when i refresh page

Hi i'm a noob when it comes to PHP but im making a page where after you login you go to the homepage, but when im at the homepage logged in and refreshes the page i get logged out.
Here the code for my login.
`
session_start();
require('connect.php');
if (isset($_POST['username']) and isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM `user` WHERE username='$username' and password='$password'";
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
$count = mysqli_num_rows($result);
if ($count == 1){
$_SESSION['username'] = $username;
header("Location: index.php");
}else{
echo "Invalid Login Credentials.";
and the code for my index.php
<?php
require'connect.php';
session_start();
if (!isset($_SESSION['username'])){
echo" not logged in";
}else {
echo "logged in";
}
?>
your login page has:
session_start();
require('connect.php');
whereas your home page has:
require'connect.php';
session_start();
Try to be consistent. From the manual:
"To use cookie-based sessions, session_start() must be called before outputting anything to the browser."
Make sure you're calling session_start() first, in both pages. Make sure you don't have any white space or anything else being outputted first. For example:
correct:
<?php
session_start();
incorrect:
// white space above PHP tag
<?php
session_start();
That should solve your problem.
Looks like a small issues as not much of php code is involved here.
Try running this code without
require('connect.php');
If it still doesn't get resolved, I would recommend you to check with the code in connect.php file.

all the links redirects to index.php

I have a php script. Many of my customers are using it. But for few they say, they are able to login but when they click on any links from the menu, it just redirects to index.php
I have checked my code, menu links, folders... I have even checked users browser settings, antivirus, firewall... But no problem.
I am not getting why it is happening. here is my session file, while submitting login details i include this file
admin_auth.php
session_start();
if(isset($_SESSION['ADMIN']))
{
$_SESSION['name'] = $_SESSION['ADMIN'];
try {
$bdd = new PDO('mysql:host=localhost;dbname=nerp', 'root', '');
} catch(Exception $e) {
exit('Unable to connect to database.');
}
$m1 = "select * from users where username='".$_SESSION['ADMIN']."'";
$resultat = $bdd->query($m1) or die(print_r($bdd->errorInfo()));
//$m2 = mysql_query($m1) or die (mysql_error());
//$m3 = mysql_fetch_array($resultat);
$m3 = $resultat->fetch(PDO::FETCH_ASSOC);
$_SESSION['uid'] = $m3['id'];
$_SESSION['name'] = $m3['firstname'] ." ". $m3['lastname'];
$_SESSION['pos']= $m3['position'];
$_SESSION['department'] =$m3['department'];
$_SESSION['location'] =$m3['location'];
$_SESSION['password'] =$m3['password'];
$_SESSION['auth'] = md5( date('Ymd') . $_SESSION['password'] );
$_SESSION['email'] = $m3['email'];
}
else
if(!isset($_SESSION['ADMIN']) )
{
header("location:index.php");
}
login_submit.php
<?php
ob_start();
error_reporting(0);
session_start();
include("connect.php");
$user=$_POST['login_name'];
$pass=$_POST['login_password'];
$sql="SELECT * FROM users WHERE username='".$user."' AND password='".$pass."' ";
$query=mysqli_query($con, $sql) or die(mysqli_error());
$row=mysqli_fetch_array($query);
$username=$row['username'];
$count=mysqli_num_rows($query);
if($count==1)
{
$_SESSION['ADMIN']=$row['username'];
$_SESSION['name'] = $row['firstname'];
header("location:dashboard.php?user=".$_SESSION['ADMIN']."");
}
else
{
header("location:index.php");
echo "could not connect";
}
?>
is there any problem with this? . if not, why they are not able to open any links.
Based your code, and the symptom you described of those few users, it looks like those few users have disallowed cookies. So when a user with cookies disallowed goes to make a subsequent request after authenticating, they don't send the PHPSESSID cookie (here you can see an example)
So, what happens in your code is, the server sees isset($_SESSION['ADMIN']) is not set, and it drops them to the bottom of your code, which sends them back to index.php.
You can test this by disallowing cookies in your browser. A way to fix it (other than telling your users to enable cookies) is to attach some kind of ID to the URL and maintain an ID as your users move though the site. PHP can do this for you if you set:
<?php
ini_set("session.use_cookies",1);
ini_set("session.use_only_cookies",0);
ini_set("session.use_trans_sid",1);
session_start();
?>
Although I should mention this works with regular html links. It works by the PHP preprocessor adding its code to your links. Since you mentioned a menu, if your menu links are generated by javascript the PHP preprocessor won't know to add its code to the links there.

PHP session Login and Logout fails to proceed immediately

I have a PHP site with Login and Logout, using $_SESSION['userName'] to store the username of the logged in member.
But when people login, this does not happen immediately due to some reason. The same with the Logout script: It works, but not immediately. I have to try about 2-4 times before something happens.
Here is my Login code and Logout code:
Code: /login.php
session_start();
//=============Configuring Server and Database=======
$host = 'host';
$user = 'username';
$password = 'password';
//=============Data Base Information=================
$database = 'database';
$conn = mysql_connect($host,$user,$password) or die('Server Information
is not Correct'); //Establish Connection with Server
mysql_select_db($database,$conn) or die('Database Information is not correct');
//===============End Server Configuration============
//*******Form Information********
$userName=mysql_real_escape_string($_POST['username']);
$password=mysql_real_escape_string($_POST['password']);
$passWord=md5($password); // Encrypted Password
//*********retrieving data from Database**********
$query = "select * from users where userName='$userName' and passWord='$passWord'";
$res = mysql_query($query);
$rows = mysql_num_rows($res);
//**********if $userName and $passWord will match database, The above function
//**********will return 1 row
if($rows==1)
//***if the userName and password matches then register a session and redrect
//***user to the Successfull.php
{
$_SESSION['userName'] = $userName;
header("location: ../index.php");
}
else
{
echo 'Incorrect username or password.';
}
exit;
Code: /logout.php
session_name('userName');
session_start('userName');
session_unset('userName');
session_destroy();
header("Location:index.php");
I really hope you can help me with this issue.
Edit 1: Okay now the login works, and the logout can now log the user out of all pages EXEPT the page the user where on, when they clicked "logout" ... Any ideas?
In PHP, Whenever you need session variables on the page. you must start session first on the same page.
By adding
session_start();
before any output message or character to the browser, else it will show a warning message.
lets come to the later part logout function.
where you should use
session_destroy();
to kill all the sessions.
a) perhaps browser cache is working, try add the following instructions before doing anything:
header("Pragma: no-cache");
header("Cache-Control: no-cache");
b) notice: session_start does not seem to have any parameter supported

Login form always takes more then one try

I have a slight problem with my log in script in PHP. When a user logs in, it only works after the second try, there is no error but it just looks like the user entered the wrong password on the first attempt.
Sometimes when I've been testing the site, after i try log in in the first time it sends me back to the log in page. Then I manually enter the url of the home page it will let me go there sometimes. (There's some php at the top that checks if the user is logged in already so im guessing sometimes the log in script sets the SESSION to true)
Majority of the time it doesn't do that though. It will just redirect me back to the log in with out printing the error message. I believe the problem is at the top of the home page and not with the log in script because after removing the redirect if mysql doesn't return a row with a user/password match it will direct me to the log in page anyways.
Here is my login script
<?php
session_start();
// Include required MySQL configuration file and functions
// Check if user is already logged in
if (isset($_SESSION['logged_in'])) {
// If user is already logged in, redirect to main page
redirect('home.php');
}
else {
// Make sure that the user submitted a username/password and username
// only consists of alphanumeric Chars
if ( (!isset($_POST['username'])) || (!isset($_POST['password'])) OR
( !ctype_alnum($_POST['username'])) ) {
redirect('login.php');
}
// Connect to database
$mysqli = #new mysqli(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if (mysqli_connect_errno()) { printf ("Unable to connect to database %s",
mysqli_connect_error());
exit();
}
//Escape any unsafe characters before querying database
$username = $mysqli->real_escape_string($_POST['username']);
$password = $mysqli->real_escape_string($_POST['password']);
// construct SQL statement for query & execute
$sql = "SELECT * FROM peeps WHERE name = '" . $username . "'
AND pword = SHA1('" . $password . "') ";
$result = $mysqli->query($sql);
// If one row is returned, username and password are valid.
if ($result->num_rows == 1 ) {
// Set the session variable for login status to true
$_SESSION['logged_in'] = true;
$_SESSION['name'] = $username;
echo "successfull ";
redirect('home.php');
}
else {
echo "didnt return row<hr>";
redirect back to login page.
redirect('loginPage.php');
}
}
?>
And here is the code at the top of my home page..
<?php
// Start session
session_start();
// Include required functions file
require_once('functions.php');
// Check login status... if not logged in redirect to login screen
if (check_login_status() == false) {
redirect('loginPage.php');
}
$username = $_SESSION['name'];
?>
Any help would be appreciated, if you want to a little more clarification on what I mean you can sign up for gateKeeper and see what I'm talking about.
Also this is my first question so any comments on how I asked it would be appreciated.
Thanks!
Try debugging it by replacing
if (check_login_status() == false) {
redirect('loginPage.php');
}
with
if (!isset($_SESSION['name'])) { #could be any session variables that you like..
redirect('loginPage.php');
}
or do print_r($_SESSION) on top of your homepage.
I assume that the first page is the script that processes the form from loginPage.php (or loginPage.php itself) and the second one the page that you access after being authenticated.
If I'm not mistaken, the problem seems to be that sometimes you are not correctly identified and that's redirecting you to your login again. Can you show us how the code for the check_login_status() function?

How to make a secure session with php and mysql?

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.

Categories