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.
Related
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() ;
}
I'm trying to create a password protected area of a website.
I'd like to allow access by checking username and password from a MySql table, then start a session and allow access to a number of pages while the session is active. If someone tries to directly access one of these pages directly, I'd like to redirect them to login page.
My code for the login page is:
if (isset($_POST['submit']))
{
include("config.php");
session_start();
$username=$_POST['username'];
$password=$_POST['password'];
$passwordc=md5($password);
$query = "SELECT username FROM admin WHERE username='$username' AND password='$passwordc'";
$result2 = $conn->query($query);
if ($result2->num_rows != 0) {
$_SESSION["username"] = $user;
echo "<script language='javascript' type='text/javascript'> location.href='admin_view.php' </script>";
}else{
echo "<script type='text/javascript'>alert('User Name Or Password Invalid!')</script>";
}
}
It seems to work (correctly redirects if username and password matches, shows alert if not).
What I fail to do, is actually protect my pages from display if session is not active.
session_start();
if (!$_SESSION["username"]) {
header("Location: login.php");
}
I'm not a programmer or fully-educated web developer. I know HTML and CSS, and I'm barely able to use ready-to-use php and js scripts following readme files.
Any help would be greatly appreciated.
modify your login code as
if (isset($_POST['submit']))
{
include("config.php");
$username= $crud->escape_string($_POST['username']);
$password= $crud->escape_string($_POST['password']);
$passwordc=md5($password);
$query = "SELECT username FROM admin WHERE username='$username' AND
password='$passwordc'";
$result2 = $conn->query($query);
if ($result2->num_rows != 0) {
session_start();
$_SESSION["username"] = $user;
header("Location:admin_view.php");
}else{
$Message = urlencode("user name password invalid!");
header("Location:login.php?Message=".$Message);
}
}
if your values successfully stored in session then you can use like
session_start();
if(!isset($_SESSION['username']))
{
header("Location: login.php");
}
on everypage top
you must store name from query into session
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!!!!!!!
I'm trying to make a login and logout script for a page but for some reason its not working very well for me. it seems to work fine until I try to logout. it seems to destroy the session variables, but it still lets me view the page.
heres my login code:
Code:
login.php
<?php
// Use session variable on this page. This function must put on the top of page.
session_start();
////// Logout Section. Delete all session variable.
session_destroy();
$Name=$_POST['Name'];
$Pass=$_POST['Pass'];
// To protect MySQL injection (more detail about MySQL injection)
$Name = stripslashes($Name);
$Pass = stripslashes($Pass);
$Name = mysql_real_escape_string($Name);
$Pass = mysql_real_escape_string($Pass);
$sql="SELECT * FROM reg1 WHERE uname='$Name' and pass='$Pass'";
$result=mysql_query($sql);
if(mysql_num_rows($result)!='0') // If match.
{
session_register("uname"); // Craete session username.
header("location:loged.php"); // Re-direct to loged.php
exit;
}else{ // If not match.
echo '<script type="text/javascript">
window.alert("Wrong UserName And Password");
window.location="index.php"
</script>';
}
// End Login authorize check.
?>
logout.php
<?php
// Inialize session
session_start();
// Delete certain session
unset($_SESSION['uname']);
// Delete all session variables
session_destroy();
// Jump to login page
header("Location: index.php?msg=Successfully Logged out");
}
?>
thanks to every one...
You are setting the session, but you are not checking it any where that whether it is set or not. means you are not checking that user is logged in or not.. you need to do like this
if (!isset($_SESSION['uname'])) /*If uname not set then it is a guest*/
{
//page contents for guest user
}
else
{
//page for authenticated user.
}
session_register() is deprecated as of PHP 5.3.0. Replace:
session_register("uname"); // Craete session username.
with:
$row = mysql_fetch_assoc($result);
$_SESSION['uname'] = $row['uname'];
Log out with (replacing session_destroy()):
////// Logout Section.
unset($_SESSION['uname']);
The final result will look like:
<?php
// Use session variable on this page. This function must put on the top of page.
session_start();
// Logout Section
if (isset($_SESSION['uname']))
unset($_SESSION['uname']);
// Login Section
$Name=$_POST['Name'];
$Pass=$_POST['Pass'];
// To protect MySQL injection (more detail about MySQL injection)
$Name = stripslashes($Name);
$Pass = stripslashes($Pass);
$Name = mysql_real_escape_string($Name);
$Pass = mysql_real_escape_string($Pass);
$sql="SELECT * FROM reg1 WHERE uname='$Name' and pass='$Pass'";
$result=mysql_query($sql);
if(mysql_num_rows($result)!='0') // If match. {
$row = mysql_fetch_assoc($result);
$_SESSION['uname'] = $row['uname'];
header("Location: loged.php"); // Re-direct to loged.php
exit;
} else { // If not match.
echo '<script type="text/javascript">
window.alert("Wrong UserName And Password");
window.location="index.php"
</script>';
}
?>
Logout script (syntax error fixed and session_destroy(); since unnecessary):
<?php
// Inialize session
session_start();
// Delete certain session
if (isset($_SESSION['uname'])) {
unset($_SESSION['uname']);
}
// Jump to login page
header("Location: index.php?msg=Successfully Logged out");
?>
How to check if logged in:
session_start();
if (isset($_SESSION['uname']))
{
// logged in
}
else
{
// not logged in
}
In your page that you want to be accessed only by logged in user, do you check the value of $_SESSION['uname'] ?
I think only session_destroy(); function is good enough to log you out. You need not to unset the 'uname'. And for those pages that will come after user logged in then you must apply some session check functionality at the top of each page...
if uname is the value you use to validate if the user is logged you should try to put first:
session_destroy(); and then the unset($_SESSION['uname'])
I hope this works for you....