Session variable not set at first try - php

I am using a session variable to check if the user is logged in. But the first time you submit the login form the session variable is somehow unset, but ONLY the first time.
If I submit the login form twice it works.
Or let's say I have submitted the form twice in order to log in. Then log out. Now I only need to submit the form once to log in.
Here is the code im using to log in the user:
<?php
session_start();
define('DB_NAME', 'madsanker_dk_db');
define('DB_USER', 'madsanker_dk');
define('DB_PASSWORD', '');
define('DB_HOST', 'mysql43.unoeuro.com');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Could not connect: ' .mysqli_error());
}
$db_selected = mysqli_select_db( $link, DB_NAME);
if (!$db_selected) {
die('Could not connect: ' .mysqli_connect_error());
}
$username = $_POST['username'];
$password = $_POST['password'];
$username = mysqli_real_escape_string($link,$username);
$password = mysqli_real_escape_string($link,$password);
$password = md5($password);
$sql = "SELECT * FROM mainLogin WHERE username = '$username'";
$result = mysqli_query($link, $sql);
$count=mysqli_num_rows($result);
if($count==1){
$row = mysqli_fetch_assoc($result);
if ($password == $row['password']){
SETTING THE VARIABLE HERE --> $_SESSION['login'] = $username;
echo "<script> window.location.assign('http://www.madsanker.dk'); </script>";
return true;
}
else {
echo "<script> window.location.assign('http://www.madsanker.dk/loginpage'); </script>";
return false;
}
}else{
echo "<script> window.location.assign('http://www.madsanker.dk/loginpage'); </script>";
return false;
}
mysqli_close($link);
?>
I am sure that the variable is being set the first time, because if I echo the variable and do exit(); right after it has been set it show up correctly.
The page I am redirecting to looks like this:
<?php
session_start();
$_SESSION['activePage'] = "home";
?>
<!DOCTYPE html>
<html>
<head>
<title>Madsanker</title>
<link rel="stylesheet" href="main.css" name="pageStyle" type="text/css">
<?php include "nav-bar.php"; ?>
</head>
<body>
<h2>Welcome to Madsanker.dk</h2>
<?php include "chatIframe.php" ?>
</body>
</html>
Even if I put var_dump($_SESSION['login']); exit(); at the top of the document it says NULL the first, and the second time it displays the username correctly.
I have been trying to fix this for about an hour now and I really can see why this is not working.

Please check if you are accessing the first time to your site without www. because the second time your are redirecting to www.madsanker.dk so the are two different domains.
Hope that helps :D

Related

Admin link does not having access to admin links its shows to all others users to onyl admin role can see admin links

This first is panel.php file and second is session file and 3rd is login.php file file. I want panel.php file shows only if logged user is administrator then show only admin links and if other then show other links. i don't know what happened with this code i tried but it showing all links to all users . kindly find the error please
panel.php file
<?php
include('session.php');
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
if($_SESSION['role']=='Administrator')
{
?>
<li>Add Publisher</li>
<?php
}else{
?>
<li>Mailbox</li>
<?php
}
?>
</body>
</html>
session.php file
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("simple_db", $connection);
session_start();// Starting Session
// Storing Session
$user_check=$_SESSION['login_user'];
$role_check=$_SESSION['role'];
// SQL Query To Fetch Complete Information Of User
$ses_sql=mysql_query("SELECT * FROM simple_db WHERE email_n='$user_check' ", $connection);
$row = mysql_fetch_assoc($ses_sql);
$login_session =$row['email_n'];
if(!isset($login_session)){
mysql_close($connection); // Closing Connection
header('Location: login.php'); // Redirecting To Home Page
}
?>
login.php file
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['email_n']) || empty($_POST['email_p'])) {
$error = "Email or Password is invalid";
}
else
{
// Define $username and $password
$email_n = $_POST['email_n'];
$email_p = $_POST['email_p'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "root", "");
// To protect MySQL injection for Security purpose
$email_n = stripslashes($email_n);
$email_p = stripslashes($email_p);
$email_n = mysql_real_escape_string($mail_n);
$email_p = mysql_real_escape_string($email_p);
// Selecting Database
$db = mysql_select_db("simple_db", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = mysql_query("SELECT * FROM simple_db WHERE email_n='$email_n' AND email_p = '$email_p' ", $connection);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$email_n;
$_SESSION['role']=$row->Role;
// Initializing Session
header("location: panel.php"); // Redirecting To Other Page
} else {
$error = "Email or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
?>

how to call a function $_SESSION[usr]->logout() inside <a>

I have a class named User which has a function named logout(). I create an instance of this class in index.php and i pass it's value to $_SESSION[usr] before i call memberspage.php . In memberspage.php i have a link named logout which when clicked i want the logout() function to run and also send the user to index.php. For this purpose i've done something like this.
Log out
I know that -> causes the problem but i don't know how to fix it. thnx for your time.
The following code worked for me
Log out
but there is a problem. If i go to the page(memberspage.php) where the above code is and i press the back arrow (not logout link) the logOut() function will still be used(the session is destroyed and i will have to log in again to access memberpage.php) . I don't get it because i thought that the only way to call the logOut() function was to click on Log out link.
If $_SESSION[usr]->logout() is working for you as you said in your comment. I don't know how.
But here is just for calling a php function inside anchor tag.It's totally depend on your function response.
<?php
function usr(){
return "abc";
}
?>
Log out
First i suggest that you change your use of session you can create a page for example session.php where all your session is place, it can also be the re directory page of your login page.
like this one named login.php
create in your form make action redirect to session.php
i also suggest that all your php codes of login are inside the session.php then make this one.
<?php
session_start();
$host = "localhost";
$uname = "root";
$pass = "";
$db = "mydb;
//database connection
$conn = mysqli_connect($host, $uname, $pass, $db);
mysqli_select_db($conn, $db);
if(!$conn){
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST['username'])){
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
//$username = mysqli_real_escape_string($username);
//$password = mysqli_real_escape_string($password);
$sql = "SELECT * FROM table WHERE username = '" .$username. "' AND password = '".$password."' LIMIT 1";
$res = mysqli_query($conn, $sql);
if(mysqli_num_rows($res) > 0){
if($data = mysqli_fetch_assoc($res))
{
$_SESSION['type'] = $data['type'];
if(isset($_SESSION["login_user"]))
{
if($data['type'] == 'admin'){
header('location: admin.php');
}
else if($data['type'] == 'customer'){
header('location: customerhome.php');
}//header('location: uservalidation.php');
}
}
}
else{
//header('location: #');
echo '<script>';
echo 'alert("Invalid no?")';
echo '</script>';
header('location: logind.php');
}
}
?>
then create another page which is logout.php
put this code inside:
<?php
session_start();
header('location: index.php');
session_destroy();
?>
then save put the a link your page for logout.php
Add file logout.php and put into them your logout implementation:
<?php
header('Content-Type: application/json');
$_SESSION[usr]->logout();
echo json_encode(['message' => 'ok']);
And call this file with AJAX:
<script>
function logout() {
$.ajax({
url: '/logout.php'
}).then(function (res) {
window.location.href = '/';
});
}
</script>
Log out

Needing guidance on how to redirect a user if not logged in on admin panel

At the moment I have an extremely basic admin login system. I am able to login in through my admin_login.php page which has a script from my login.php page I can update records from the admin_control_panel.php. My main concern is the fact that anyone can type these URL's straight into the address bar and bypass the login procedure.
My code at the moment isn't based around security (I am just trying to get all my basic functionality and features up and running, I will then focus on security).
I know that I have to use sessions to track if the user is logged in or not but I am becoming a bit confused as to where I will implement these session.
My questions is: What pages do I include the code in?, where on the pages do I include these sessions? and what do I include in these files?
What I want is to be able to redirect the user back to the login page if they are not logged in.
admin_login.php
<?php
$dbhost = 'x';
$dbuser = 'x';
$dbpass = 'x';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $con )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('x');
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/master.css">
</head>
<body>
<form method="post" action="login.php">
User:<input name="username" type="text">
Pass:<input name="password" type="password">
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>
login.php
<?php
$dbhost = 'x';
$dbuser = 'x';
$dbpass = 'x';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $con )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('x', $con);
$query = "SELECT username FROM members ".
"WHERE username=\"$_POST[username]\" ".
"AND password = \"$_POST[password]\"";
$result = mysql_query($query, $con);
mysql_data_seek($result, 0);
if (mysql_num_rows($result) == 0)
header("Location: admin_login.php");
else
header("Location: admin_control_panel.php");
?>
admin_control_panel.php
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 3</title>
</head>
<body>
<?php
include('./upload.html');
?>
</body>
</html>
Thank you in advance.
Best way to do that is with sessions.
In the login.php do something like this
if (mysql_num_rows($result) == 0) {
header("Location: admin_login.php");
} else {
header("Location: admin_control_panel.php");
session_start();
$_SESSION['user'] = $_POST['username'];
}
Now in the admin_control_panel.php at the top of the file, just add this php code to check if $_SESSION['user'] exists.
<?php
if (! isset($_SESSION['user'])) {
header("Location: admin_login.php");
}
?>
Basically with this code you will create session with user data if login is correct. If it's not, he will by default get redirected to the login page.
Now when someone tries to access admin_control_panel page, we will first check if session is set. If it's true, he can access the page, if not, he will get redirected to the login.
For more read about session:
PHP.net Session manual and w3schools.com Session manual
*Note. To logout, you gotta destroy session, to do that use session_destroy(); function.
Include session_start(); at the top of your script and then you would do something like this:
if (mysql_num_rows($result) == 0){
header("Location: admin_login.php");
} else {
$_SESSION['permission'] = 'admin';
header("Location: admin_control_panel.php");
}
You then need to implement a function to check if the admin is logged in.
function verifyAdmin() {
if(!isset($_SESSION['permission']) || $_SESSION['permission'] != 'admin'){
header("Location: admin_login.php");
}
}
Now, on the top of each admin page just add verifyAdmin();. Remember to add session_start(); to the top of any page the uses sessions.

User login using PHP

I haven't been able to trace what's wrong with this code. I am trying to login the user by taking his username and password. Here is what I am trying to do.
index.php:
This file checks if the username cookie is set and displays the file accordingly. This file submits the username and password to a file called validate.php.
validate.php:
<?php
session_start();
include("connector.php");
$var=connect();
if($var==10)
{
$valid=false;
$row= mysql_query('select * from users where username="'.$_POST["username"].'"');
if($row['password']==$_POST["password"])
$valid=true;
if($valid)
{
$_SESSION["username"]=$_POST["username"];
$_SESSION["userid"]=$row['userid'];
echo "<script>document.location.href='./session_creator.php'</script>";
}
else
{
echo "invalid";
}
}
?>
connector.php==>
<?php
$connection=0;
function connect()
{
$dbc = mysql_connect('localhost:3306','root','root');
if (!$dbc)
{
die ('Not connected:'. mysql_error());
return -10;
}
else
{
$connection = mysql_select_db("citizennet",$dbc);
if(!$connection)
{
die("Not connected: ". mysql_error());
return -20;
}
}
return 10;
}
?>
session_creator.php:
<?php
session_start();
setcookie("username",$_SESSION['username'],time()+3600);
setcookie("userid",$_SESSION['userid'],time()+3600);
echo "<script>document.location.href='./index.php'</script>";
?>
the redirected index.php file reports that the cookie is not set. I am newbie, please correct me if the process I am following is wrong.
I am adding index.php that verifies if the user is logged in:
<?php
if(!isset($_COOKIE["username"]))
echo '<a id="login_button">login</a> <div id="login_box_pane"><form action=validate.php method="post">Username: <input type="text"/> Password:<input type="password"/><input type="submit"/></form></div>';
else
echo "<a>".$_COOKIE["username"]."</a>";
?>
When you set your cookie on your page it should be like this:
<?php //login page
session_start()
$username = $_POST['username'];
$password = $_POST['password'];
/*
Check authentication with database values
*/
//if login successful set whatever session vars you want and create cookie
$_SESSION['username'] = $username;
setcookie($username, $password, time()+3600);
?>
Prior to this you will have check the users credentials and log them in or deny them. Once logged in you set the session variables. Then to create the cookie you use the code above.
$user = mysql_real_escape_string($_POST['user']);
$pass = mysql_real_escape_string($_POST['pass']);
$sql = "SELECT * FROM users WHERE username='$user' AND password='$pass'";
$result = mysql_query($sql);
That will take care of your sql injection vulnerabilities and also get you the correct account only if both the username and password are correct
Now you can use your conditions to set the cookies and sessions

PHP Session value changing from page to page

I made a custom login script, and it works just fine. However, after it redirects to the homepage, the $_SESSION['username'] value is changed to 'root', no matter what value it had before hand. which 'root' is the username for my database login.
I have to type all of this in by hand, so it might have an obvious error or two-
main_login.php (php include_once on sidebar.php which is included on every page)
<?php
if(!isset ($_SESSION["username"])){
?>
<!-- Simple login form action="checklogin.php" method="post"-->
<?php
}else{
?>
<!-- Table to display welcome user, and logout link -->
checklogin.php:
session_start();
$db_name = "database";
$tbl_name = "users";
mysql_connect("localhost","root","password") or die("Cannot connect to SQL server");
mysql_select_db("$db_name")or die("Cannot select database.");
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$password = md5($password);
$sql = "SELECT * FROM $tbl_name WHERE username = '$username' and password = '$password'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count == 1){
$_SESSION["username"] = $username;
$_SESSION["password"] = $password;
header("location:login_success.php");
}
else{
echo "<script type='text/javascript'>\n";
echo "setTimeout('redirect();',2000);\n";
echo "function redirect(){\n";
echo "window.location = 'index.php';\n";
echo "}\n";
echo "</script>\n";
echo "Wrong Username or Password";
login_success.php:
<?php
session_start();
if(!isset($_SESSION['username'])){
header("location:index.php");
}else{
session_regenerate_id();
}
// Apply permissions - problem existed before all of this code
mysql_connect("localhost","root","password") or die("Cannot connect to database.");
mysql_select_db("database") or die("Cannot select database.");
$username = $_SESSION['username'];
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysql_num_rows($result);
mysql_close();
$_SESSION['username'] = mysql_result($result,0,'username');
$_SESSION['permissions'] = mysql_result($result,0,'permissions');
?>
<html>
<head>
<script type="text/javascripnt">
setTimeout("redirect();",4000);
function redirect(){
window.location = "index.php";
}
</script>
</head>
<body>
Login Successful.
<?php echo "Welcome ".$_SESSION["username"].".";
var_dump($_SESSION); // var_dump reveals that $_SESSION['username'] is still the login name.
?>
</body>
</html>
Once it goes through that whole process, everything is good. However, when it redirects to index.php, $_SESSION['username'] is now 'root'.
I'm asking to see if anyone has any idea why that might be happening (So I can understand the problem and prevent it in the future), and a fix to implement.
Thanks everyone.
The answer is very simple:
There is some code in your application which changes $_SESSION['username'] value to 'root'.
you have to investigate your code and find that place. Not a big deal
this part seems weird:
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysql_num_rows($result);
mysql_close();
$_SESSION['username'] = mysql_result($result,0,'username');
$_SESSION['permissions'] = mysql_result($result,0,'permissions');
try this:
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysql_query($result);
$_SESSION['username'] = mysql_result($result,0,'username');
$_SESSION['permissions'] = mysql_result($result,0,'permissions');
msql_close();
Why are you setting the $_SESSION['username'] variable again on login_success.php You're setting the variables on check_login.php, correct?
Here is what I would do
On login_success.php print out your session variables to see whats going on. I can almost gaurantee something is happening with your sql query. Set a condition to make sure you're actually getting results.
print_r($_SESSION);
if(!$_SESSION['username']) die('no session user name');
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysql_query($result);
if(mysql_num_rows($result) == 1){
$_SESSION['username'] = mysql_result($result,0,'username'); //why do you need this?
$_SESSION['permissions'] = mysql_result($result,0,'permissions');
mysql_close();
}
else die('no user found');
Also on your checklogin page change the if statement to look for an actual variable in $_SESSION['username'] not just if it is set, I try to stay away from isset().
For the love of god don't store plain text passwords, it doesn't cost anything to implement a secure password hashing scheme. Its super easy to leverage php's crypt() function, also check this out for an open source secure method. http://www.openwall.com/phpass/
Well,
Your comment sense is probably right, you are setting it to root without realizing it. I just realized, after 2 hours of troubleshooting, that's what I was doing!
No matter what I tried, $_SESSION['username'] was changing from a real username to 'root'.
I finally realized that $_SESSION['username'] was NOT actually changing anywhere, but $username was. Here is why:
<?php
if(!empty($_SESSION['username'])){
$username = $_SESSION['username'];
require_once '../includes/connect_to_db.php';
echo $_SESSION['username']. ' is correct but '. $username. 'is not.';
}
?>
Finally we see in the required file connect_to_db.php:
<?php
$host="localhost"; // Host name
$username="root"; // mysql username
$password=""; // mysql password
$db_name="BH_web_DB"; // Database name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect: ". mysql_error());
mysql_select_db("$db_name")or die("cannot select DB");
?>
Simple fix:
$db_username="root"; // mysql username
So I was in fact setting it too root =) hope this helps another.
I was having the same issue, turns out I didn't session start on the page where it displays 'root'.
if (!session_id()) session_start();
This helped!

Categories