PHP Session for login - doesn't recognise - php

I'm writing a login code for my control panel for my website. I've made the login script. But for some reason the session doesn't save, here is the parts of my code I use:
index.php
session_start();
if(isset($_POST['username']) && isset($_POST['password'])) {
require('scripts/validateLogin.php');
}
if($_SESSION['login'] == 1) {
$loginOkay=1;
echo "Logged in";
} else {
$loginOkay=0;
echo "Not logged in";
}
validateLogin.php
require('mysql_connect.php');
$username = htmlspecialchars(strtolower($_POST['username']));
$password = md5(htmlspecialchars($_POST['password']));
$result = mysqli_query($con, "SELECT username,password FROM tb_mods WHERE username = '$username';");
while($row = mysqli_fetch_array($result)) {
if ($row['username'] == $username && $row['password'] == $password) {
$_SESSION['login'] == 1;
}
}
I call session_start(); before I load my loginValidation.php so session_start(); is active in both pages.
I keep getting: Not logged in as result.

I think the line $_SESSION['login'] == 1; is wrong, you need only one equal character to add value to the session variable. I hope it will help.

Related

Cookies not saving (PHP)

My cookies are not saving, I am using PHP 5.
Code:
require 'dbcon.php';
$sql = "SELECT * FROM accounts";
$result = $conn->query($sql);
$username = $_POST['username'];
$password = $_POST['password'];
$row = mysql_fetch_row($result);
setcookie("ID6", $row['ID'], time() + 60*60*24*31*12, "/") or die("Cookie could not be set. <a href='index.php'>Try again!</a>");
if(!isset($_POST['username']) || !isset($_POST['password'])) {
header("Location: index.php");
exit();
}
while($row = mysqli_fetch_assoc($result)) {
if($username == $row['username']) {
if($password == $row['password']) {
if($row['accdel'] == 1) {
echo("You are banned.");
exit();
}
echo "Logged in with cookie:" . $_COOKIE['ID6'];
exit();
}
else {
echo "The account does not exist, or you have put in the wrong log in.";
exit();
echo"That's not an account name though...";}
}
}
?>
Please help. Is the selected sql even a settable cookie value? (Please make it simple. I do not know much about php nor cookies.
https://www.jqueryscript.net/other/E-commerce-Cart-Plugin-For-jQuery.html
I tried save cookies with PHP many days never work.
Maybe try jquery.
The ID wasnt got from the database because it was not in the while loop.

.php file security using MAMP

I have generated a php file that has information stored in a database. To access this a person must use a login in page.
However, when you are using MAMP how can you prevent someone from accessing the file through writing the IP address and php file name e.g. 123.456.78.00:80/fileone.php. I want this fileone.php to be hidden and for them to only access it through a login page.
Thanks in advance.
<?php
session_start();
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
mysql_connect("localhost", "root","root") or die(mysql_error()); //Connect to server
mysql_select_db("first_db") or die("Cannot connect to database"); //Connect to database
$query = mysql_query("SELECT * from users WHERE username='$username'"); //Query the users table if there are matching rows equal to $username
$exists = mysql_num_rows($query); //Checks if username exists
$table_users = "";
$table_password = "";
if($exists > 0) //IF there are no returning rows or no existing username
{
while($row = mysql_fetch_assoc($query)) //display all rows from query
{
$table_users = $row['username']; // the first username row is passed on to $table_users, and so on until the query is finished
$table_password = $row['password']; // the first password row is passed on to $table_users, and so on until the query is finished
$table_id = $row['id'];
$page_id = $row['page'];
}
if(($username == $table_users) && ($password == $table_password)) // checks if there are any matching fields
{
if($password == $table_password)
{
$_SESSION['user'] = $username; //set the username in a session. This serves as a global variable
//echo $table_id;
//echo $page_id;
redirect ($page_id); //take the user to the page specified in the users table
}
else
{
echo "Login Failed";
}
}
else
{
Print '<script>alert("1. Incorrect Password!");</script>'; //Prompts the user
Print '<script>window.location.assign("login.php");</script>'; // redirects to login.php
}
}
else
{
Print '<script>alert("Incorrect Username!");</script>'; //Prompts the user
Print '<script>window.location.assign("login.php");</script>'; // redirects to login.php
}
function redirect($page_id)
{
/* Redirect browser */
header('Location: ' . $page_id);
/* Make sure that code below does not get executed when we redirect. */
exit;
}
?>
Login check
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] === true) {
"Your script"
}
If you have a profile for your users, like a normal user = 0 and an admin = 1 you can do it like this
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] === true && $_SESSION['profile'] == 1) {
"Your script"
}
Set sessions
To set set the sessions to true you need this
if(isset($_POST['submit'])) {
$_SESSION['loggedIn'] = true;
// for set a profile
$_SESSION['profile'] = 1;
}
Maybe I didn't understand you good, but to be sure I will explain something:
You said attached checklogin.php, but you can't use that to deny access for non members. If they know that the file exists, they can type it in the URL and still read fileone.php. The first coding block need to be in your fileone.php.
Session time
Search in your php.ini for 'session.gc_maxlifetime'. There will be a number and that is the time in seconds.

Logout script is not working

Please help with my logout script. I am sorry for dumb mistakes I am very new to php. Please provide me with details and examples of how to fix this. Thank you so much.
Login Page: There are 4 types of users. Each user will get a separate home page.
<?php
session_start();
require_once('common/config.php');
if(isset($_POST['username']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM `users` WHERE username='".$username."' and password='".$password."'";
$result = mysql_query($sql) or die(mysql_error());
$fetched = mysql_fetch_array($result);
if ($fetched['user_type'] == "admin")
{
header('location: adminhomepage.php');
}
else if ($fetched['user_type'] == "po")
{
header('location: pohomepage.php');
}
else if ($fetched['user_type'] == "pw")
{
header('location: pwhomepage.php');
}
else if ($fetched['user_type'] == "ps")
{
header('location: pshomepage.php');
}
else
{
header('location: invalid.php');
exit();
}
}
?>
Home Page: For instance this is the admin home page.
<?php
session_start();
if (isset($_SESSION['username']) && ($_SESSION['username'] !== 1))
{
header('Location: login.php');
}
?>
Logout Page
<?php
session_start();
$_SESSION['username'] =0;
?>
Logout Button
<form action = "logout.php">
<input id="logoutbutton" type="submit" value="Logout">
</form>
logout page
<?php
session_start();
unset($_SESSION['susername']);
$_SESSION['susername'] = "";
session_destroy();
header("location:index.php");
?>
login.php
session_start();
if (isset($_SESSION['uname']) == "")
{
require_once('index.php');
}
$user_name = $_POST['user_name'];
$user_pass = $_POST['user_pass'];
$_SESSION['susername'] = $user_name; // or other value
logout page -
<?php
session_start();
$_SESSION['username'] =0;
?>
you have to start the session first before accessing it.
In your logout.php please update this code...
<?php
session_start();
if(isset($_SESSION['username']))
{
unset($_SESSION['username']);
header('Location: login.php');
}
?>
use unset($_SESSION['susername']) or session_destroy
Edit:
With your new information, it's clear you never actually set the $_SESSION['username'] value.
if ($fetched['user_type'] == "admin")
{
$_SESSION['username'] = $username;
header('location: adminhomepage.php');
}
else if ($fetched['user_type'] == "po")
{
$_SESSION['username'] = $username;
header('location: pohomepage.php');
}
else if ($fetched['user_type'] == "pw")
{
$_SESSION['username'] = $username;
header('location: pwhomepage.php');
}
else if ($fetched['user_type'] == "ps")
{
$_SESSION['username'] = $username;
header('location: pshomepage.php');
}
else
{
header('location: invalid.php');
}
exit();
Your problem is your comparison.
if ($_SESSION['username'] != 1)
This is true if $_SESSION['username'] is not set, null, a string, false, etc...
This might be more what you are looking for.
if (isset($_SESSION['username']) && is_string($_SESSION['username']) && strlen($_SESSION['username']))
And you need to fix your SQL injection problem here
$sql = "SELECT * FROM `users` WHERE username='".$username."' and password='".$password."'";
Escape variables with mysql_real_escape_string or use PDO with proper prepared statements.
You should also store passwords as hashes with password_hash(). Fetch the user, compare stored hash to password with password_verify.
if (!password_verify($password, $fetched["password"])) {/* wrong password, show error or something */}

Text posted by 'echo' function still persists when refresh button is pressed.-- PHP

<?php
session_start();
$root = 'root';
mysql_connect('localhost',$root,'') or die(mysql_error());
mysql_select_db("test_create_database") or die(mysql_error());
$result = mysql_query("SELECT * FROM members");
$row = mysql_fetch_assoc($result);
$username="";
$password="";
$id="";
if(isset($_POST["submit"]))
{
if(isset($_POST["submit"]) && !empty($_POST["username"]) && !empty($_POST["password"]) && !empty($_POST["id"]))
{
if(isset($_POST["username"]) && isset($_POST["password"]) && isset($_POST["id"]))
{ $username = $row["username"];
$password = $row["password"];
$id = $row["id"];
if($username == "John" && $password =="1234" && $id =="1")
{
echo "you're in";
}
else
{
echo "you're out!";
}
}
}
elseif (isset($_POST["submit"]) && (empty($_POST["username"]) || empty($_POST["password"]) || empty($_POST["id"])))
{
echo "enter all fields please!!!!";
}
}
session_destroy();
?>
if at first all the fields are filled in correctly and the submit button is pressed, the text "you're in" is printed onto the webpage and the text in the fields disappears. but if I refresh the page again, the printed text "you're in" still remains even though I have invoked the session_destroy() function. I don't understand why the session has not been destroyed. Any help would be appreciated.
The bits about session_start() and session_destroy() do not influence the POST-variables. As BugFinder pointed out, refreshing the page often re-submits whatever data you've just submitted. That's why the 'you're in'-message is presented again.
A way of preventing this behaviour is by redirecting after the submitted data has been processed. You could then set a session variable to keep track of the message you still need to display (or, if the user is logged in or not).
Your code would look something like this:
<?php
session_start();
$root = 'root';
mysql_connect('localhost',$root,'') or die(mysql_error());
mysql_select_db("test_create_database") or die(mysql_error());
$result = mysql_query("SELECT * FROM members");
$row = mysql_fetch_assoc($result);
$username="";
$password="";
$id="";
if(isset($_POST["submit"]))
{
if(isset($_POST["submit"]) && !empty($_POST["username"]) && !empty($_POST["password"]) && !empty($_POST["id"]))
{
if(isset($_POST["username"]) && isset($_POST["password"]) && isset($_POST["id"]))
{ $username = $row["username"];
$password = $row["password"];
$id = $row["id"];
if($username == "John" && $password =="1234" && $id =="1")
{
//do stuff
$_SESSION['message'] = "you're in";
}
else
{
$_SESSION['message'] = "you're out!";
}
}
}
elseif (isset($_POST["submit"]) && (empty($_POST["username"]) || empty($_POST["password"]) || empty($_POST["id"])))
{
$_SESSION['message'] = "enter all fields please!!!!";
}
$selfLink = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$selfLink .= "?" . $_SERVER['QUERY_STRING'];
}
header('location: '.$selfLink);
exit;
}
if (isset($_SESSION['message'])) {
echo $_SESSION['message'];
unset($_SESSION['message']);
}
?>
Note that the redirecting to the page itself seems a bit forced (using $_SERVER['QUERY_STRING'] to fetch the current page's location). It works more intuitively if you know the file name or if you're redirecting to a different page after handling form input.
isset($_POST["submit"]) remove this check in elseif.
After submit form and explicit refresh of page $_POST["submit"] is set but if u go manually to that page $_POST["submit"] will not be set.

php sessions to authenticate user on login form

I have the following code designed to begin a session and store username/password data, and if nothing is submitted, or no session data stored, redirect to a fail page.
session_start();
if(isset($_POST['username']) || isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
}
if(isset($_SESSION['username']) || isset($_SESSION['password'])){
$navbar = "1";
$logindisplay = "0";
$username = $_SESSION['username'];
$password = $_SESSION['password'];
} else {
header('Location:http://website.com/fail.php');
}
$authed = auth($username, $password);
if( $authed == "0" ){
header('Location:http://website.com/fail.php');
}
Its not working the way it should and is redirecting me to fail even though i submitted my info and stored it in the session. Am i doing something wrong?
NOTE the authed function worked fine before i added the session code.
what about using this to setup session
session_start();
if( isset($_POST['username']) && isset($_POST['password']) )
{
if( auth($_POST['username'], $_POST['password']) )
{
// auth okay, setup session
$_SESSION['user'] = $_POST['username'];
// redirect to required page
header( "Location: index.php" );
} else {
// didn't auth go back to loginform
header( "Location: loginform.html" );
}
} else {
// username and password not given so go back to login
header( "Location: loginform.html" );
}
and at the top of each "secure" page use this code:
session_start();
session_regenerate_id();
if(!isset($_SESSION['user'])) // if there is no valid session
{
header("Location: loginform.html");
}
this keeps a very small amount of code at the top of each page instead of running the full auth at the top of every page. To logout of the session:
session_start();
unset($_SESSION['user']);
session_destroy();
header("Location: loginform.html");
First, don't store the password in the session. It's a bad thing. Second, don't store the username in the session until after you have authenticated.
Try the following:
<?php
session_start();
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$authed = auth($username, $password);
if (! $authed) {
header('Location: http://website.com/fail.php');
} else {
$_SESSION['username'] = $username;
}
}
if (isset($_SESSION['username'])) {
$navbar = 1;
$logindisplay = 0;
} else {
header ('Location: http://website.com/fail.php');
}
Just some random points, even though they may not actually pertain to the problem:
Don't store the password in plaintext in the session. Only evaluate if the password is okay, then store loggedIn = true or something like that in the session.
Check if the password and the username are $_POSTed, not || (or).
Don't pass password and username back and forth between $password and $_SESSION['password']. Decide on one place to keep the data and leave it there.
Did you check if you can store anything at all in the session? Cookies okay etc...?
To greatly simplify your code, isn't this all you need to do?
if (isset($_POST['username'] && isset($_POST['password'])) {
if (auth($_POST['username'], $_POST['password'])) {
$_SESSION['user'] = /* userid or name or token or something */;
header(/* to next page */);
} else {
// display "User credentials incorrect", stay on login form
}
} else {
// optionally: display "please fill out all fields"
}
Here are a few other things, which may or may not help you, by the way :
Do you have error_reporting on ? (see also)
Do you have display_errors on ?
Is session_start the first thing you are doing in your page ? There must be nothing output before
Are the cookies created on the client-side ?
header Location indicates the browser it has to go to another page ; it doesn't stop the execution of the PHP script. You might want to (almost always anyway) add "exit" after it.
Headers are not function calls. They put a directive into the HTTP headers, and the last one to execute is the one which will be processed. So let say if you have something like this
if ($bAuthed)
{
header("location: login.php");
}
// error case
header("location: error-login.php");
You will always be redirected to error-login.php no matter what happens. Headers are not function calls!
The solution to my specific problem above
session_start();
if(isset($_POST['username']) || isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
}
if(isset($_SESSION['username']) || isset($_SESSION['password'])){
$navbar = "1";
$logindisplay = "0";
$username = $_SESSION['username'];
$password = $_SESSION['password'];
$authed = auth($username, $password);
if( $authed == "0" ){
header('Location:http://website.com/fail.php');
}
} else {
header('Location:http://website.com/fail.php');
}
Don't use else section in second if statement.
session_start();
if(isset($_POST['username']) || isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
}
if(isset($_SESSION['username']) || isset($_SESSION['password'])){
$navbar = "1";
$logindisplay = "0";
$username = $_SESSION['username'];
$password = $_SESSION['password'];
}
$authed = auth($username, $password);
if( $authed == "0" ){
header('Location:http://website.com/fail.php');
}

Categories