I lose my session with PHP - php

I have a problem with a project I'm working on. I'm trying to code a simply login system using PHP + Sessions. But I lose my session, and I don't really know why, the code:
index.php
<?php
session_start();
if(!isset($_SESSION['logedin'] == True)){
<form action = "login.php" method = "post" id="login-form" class = "login-form">
<input type = "text" name = "username" maxlength = "100"/>
<input type = "password" maxlength = "50" name = "password"/>
<button type="submit">Sign in</button>
</form>
}else{
echo "Loged in.";
}
?>
login.php
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if(!isset($_SESSION['logedin'] == True)){
if($username == 'username' && $password == 'password'){
$_SESSION['logedin'] = True;
header("index.php"); // Loged in
}
}
?>
The real code is not this one, because it's too long to put here, but this is a simply resume about the code... I'm losing my head, because if I open a session into index.php, it works, but if I go out of my page (in this case, login.php through form), when I back to index, session just vanish...
I got to say I don't use any frameworks or something, it's a simply form, all done with PHP.

Your parens on the first line are going to be a problem:
if(!isset($_SESSION['logedin'] == True)){
Change to:
if(!isset($_SESSION['logedin'])) {
Why are you doing a double negative on this condition? Instead of doing !isset == true, just do isset == false. This is just likely to add confusion to your code, and the more intuitive (and simplistic) your code, the better.
In your login.php you also have that line:
if(!isset($_SESSION['logedin'] == True)){
You are basically saying isset(true) == false which should always return false. Because $_SESSION['logedin'] == true is true. Change it to if (isset($_SESSION['logedin'])) which will be true if you're logged in.
Let's break this condition down a little further to see what you're doing
if (false == isset(
$_SESSION['loged'] == true // will be true if you're logged in
) // isset will return true, but you're expecting a false
)
Your isset is always going to return true. Whether $_SESSION['logedin'] == true returns true or false it will be "isset". Isset will only return false if the return value is null or the var does not exist. "False" is a value and exists. Does that make sense? Sorry if this is confusing. Basically, don't use conditions in your isset! :). Use the isset as a part of a condition, but don't pass them into the isset parameter.

Related

setting and unsetting a session though an URL

Hi,
I need to create a session as soon as the visitor enters my page. Then by clicking on a link that takes to an URL like this example.org/page?no_redirect=true the session must be destroyed but the session should be created again if they click on a link to this URL example.org/page?no_redirect=false.
I did it like this:
session_start();
$_SESSION['redirect'] = "false";
if($_GET['no_redirect'] == "true")
{
$_SESSION['redirect']="true";
} elseif ($_GET['no_redirect'] == "false") {
$_SESSION['redirect']="false";
}
if ($_SESSION['redirect']!=true) {
$redirect = <<<EOF
<script type='text/javascript'>DM_redirect("mobile/$page");</script>
EOF;
}
but its not working. What could it be?
Thank you.
The check if ($_SESSION['redirect'] != true) makes no sense, because you are comparing a non-empty string to a boolean. Non-empty strings always evaluate to true, so your check is really if (true != true), which means the content inside the block will never be executed.
A more sensible approach would be to unset your session once its purpose has been served instead of setting it to "true" / "false".
Code:
session_start();
# Check whether the session should be unset.
if ($_GET['no_redirect'] == "true") {
unset($_SESSION['redirect']);
}
# Check whether the session should be set.
else if ($_GET['no_redirect'] == "false") {
$_SESSION['redirect'] = "true";
}
# Check whether the session is set.
if (isset($_SESSION['redirect'])) {
$redirect = <<<EOF
<script type='text/javascript'>DM_redirect("mobile/$page");</script>
EOF;
}

Where is the words in ' ' located?

I am learning php, (absolute beginner) and want to know where the words in '' are located. I downloaded a code from online for a login system and am trying to learn how it works. Here is the code portion:
<?php
// any HTML input *must* be HTML-escaped to prevent the user from injecting malicious JavaScript code
function html_escape($raw_input, $encoding)
{
return htmlspecialchars($raw_input, ENT_QUOTES | ENT_SUBSTITUTE, $encoding);
}
/* Displays user information and some useful messages */
session_start();
if ($_SESSION['logged_in'] != 1) {
$first_name = 'Guest, Please Login or Sign Up to Play!';
$last_name = '';
}
else {
// Makes it easier to read
$first_name = $_SESSION['first_name'];
$last_name = $_SESSION['last_name'];
}
?>
So where it says, "if ($_SESSION['logged_in'] != 1) {", when it says logged_in, where would that be defined? Is it defined in another file with the $logged_in, or what?
Also, i found some file where it says "$_SESSION['logged_in'] = true;" but i don't know if it means something, if it does please tell me!
Thanks so much.
(i'm a beginner so go easy on me please)
You can store data in $_SESSION variables after session_start(); and assign values to it with:
$_SESSION['keyname'] = 'value';
You can write apostrophe (') or double quote (") to save string variables.
More informations here: http://php.net/manual/de/reserved.variables.session.php
Your code if ($_SESSION['logged_in'] != 1) is just a boolean check if $_SESSION['logged_in'] is set to 1 (true) or 0 (false).
So it checks your $_SESSION array with the key logged_in if 1 is set or not.
I hope I could help you with that?
In the code you shown, this is the check login step in login process. In login process, there is two step we need to do:
Check login: determine that current session is logged in or not. If not, shown/redirect to login page.
Login page: is used to input username & password and check inputed value. If username & password is correct, we save a value to $_SESSION to flag this user is logged in.
To find how the $_SESSION['logged_in'] is set, you must find in your downloaded code the check login section.
In general this can be simple as:
if ($_POST['username'] == 'abc' && $_POST['password'] == 'xyz') {
$_SESSION['logged_in'] = 1;
// some code to refresh or redirect to main content
}
I hope this will help you!
Assume you have form with field 'username' and 'password' at HTML:
<form action='login.php' method='post'>
<input type='text' name='username'>
<input type='password' name='password'>
<input type='submit' value='Login'>
</form>
after clicking 'Login' button you will run login.php:
<?php
$allowedUser = 'johnny';
$allowedPass = 'mypassword';
session_start();
if (($_POST['username']!= '') && ($_POST['password'] !=''))
{
if (($_POST['username'] == $allowedUser) && ($_POST['username'] == $allowedPass))
$_SESSION['is_loged'] = 1; // session variable will be set when you have allowed credentials
}
?>

How to use sessions in PHP with loginfunction?

I have used a hash encryption of the password for the user so in the login i check with password_verify if the passwords match and that part of the code seems to be working. And everything inside of the if statment besides something with the sessions. The header Location works but i just get sent back and in the errorlog it says; Undefined index: authorized in C:\xampp\htdocs\portfolio\admin.php on line 22. And authorized is the session im trying to create for checking if the user is logged in.
So my question is partly what I'm doing wrong and partly how a good way to work with sessions in an loginfunction is? My admin.php is supposed to only be accessed if the user is logged in. I will paste the important parts of the code below.
My login.php page:
In the top of the document:
// Error log
ini_set('log_errors', 1);
ini_set('error_log', 'logs/error_log.txt');
//Session
session_start();
session_regenerate_id();
// Includes
include_once 'actions/login_action.php';
?>
In the body:
<div id="login">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" autocomplete="off">
<p><input type="text" name="user" placeholder="Username" maxlength="30" required/></p>
<p><input type="password" name="pass" placeholder="Password" maxlength="30" required /></p>
<input class="green" name="login" type="submit" value="Log In >>" />
</form>
</div>
<?php
}else{
echo "You are already logged in.";
}
?>
My login_action.php page:
The loop that fetch the result and checks the password:
// Fetch the result
while($stmt->fetch()) {
$pass_crypt = $password;
// Checking password & making sessions
if (password_verify($pass, $pass_crypt) == $pass_crypt) {
$_SESSION['authorized'] = true;
$_SESSION['username'] = htmlspecialchars($user);
// Successful signin logs in logs/success_signin_log.txt
$successLog = fopen("logs/success_signin_log.txt", "ab");
$txt = 'Successful login preformed ' . $date . ' by ' . $user . "\r\n";
fwrite($successLog, $txt);
fclose($successLog);
// Sends to myplace.php
header("Location: admin.php");
}else {
$user = "";
$_SESSION['authorized'] = false;
$errlogin = "Invalid login";
$error = "Login failed, please try again.";
}
}
My admin.php page:
In the top of the document:
// Error log
ini_set('log_errors', 1);
ini_set('error_log', 'logs/error_log.txt');
// Session
session_start();
session_regenerate_id();
// If the session is not set your not logged in or empty user will be sent back to the login page.
if (!isset($_SESSION['authorized']) || $_SESSION['authorized'] == false) {
header ("Location: login.php");
}
?>
This is just a logical error because of how you coded the if condition in your admin.php file
!isset($_SESSION['authorized']) && $_SESSION['authorized'] == false
The isset() method in PHP returns false if the index does not exist in the array. So in your case when !isset($_SESSION['authorized']) evaluates to true the other part of the AND condition still needs to be evaluated in order to execute the code inside the if-statement. The error you get appears at this moment because you use $_SESSION['authorized'] as part of your second condition and the key 'authorized' might not exist.
You need to rewrite the condition for example like:
!isset($_SESSION['authorized']) || $_SESSION['authorized'] == false
In this case this means that if the 'authorized' index does not exist your first part of the condition will evaluate to true and as true || whatever will always evaluate to true the second part does not need to be evaluated and you will not get the PHP error. The second part will only be evaluated when the first one evaluates to false which actually means the index exists so you will be fine anyway.
Of course you can build this condition in many other ways which might be easier to understand / read such as:
!isset($_SESSION['authorized']) || ( isset($_SESSION['authorized']) && $_SESSION['authorized'] == false)
Always when writting this kind of conditions try to keep in mind what you really want to cover. In this case:
Session key does not exist
Session key exists but the value is false
Then, build your Boolean expression step by step and finally try to reduce it by applying Boolean Algebra or simply by using tricks like the one I mentioned above: If PHP already assumes a condition evaluates to true or to false it will never finish evaluating the expression in order to faster.

Page should show exist instead of blank page

I made login.php file by following video tutorial and I am trying to make so that the page will show exist instead of blank page. I know that user exists because I made user with my name on phpMyAdmin.
Her is the code
<?php
include 'core/init.php';
if (user_exists('Denis') === true) {
echo 'exists';
}
die();
if(empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) === true || empty($password) === true) {
$errors[] = 'You need to enter a username and password';
} else if (user_exists($username) === false) {
$errors[] = 'We can\'t find that username. Have you registered?';
}
}
?>
Init.php
<?php
session_start();
error_reporting(0);
require 'database/connect.php';
require 'functions/general.php';
require 'functions/users.php';
$errors = array();
?>
you are calling the die() function at line 7
this function terminates the running script
Clearly user_exists('Denis') is returning false, since it's getting past the echo 'exists'; line and hitting the die() call.
Depending on how you are returning your boolean, you might try two "==" signs rather than three. It might not be able to type cast.
You can try:
if (user_exists('Denis')) {
echo 'exists';
}
As long as user_exists('Denis') evaluates to true (i.e. is not empty or 0), you will "exists" will be echoed.
If that doesn't work, try to figure out why user_exists() is getting a falsy value. There may be something wrong with the logic to check if a user exists.

Check session and cookie not working in PHP

I have this code that makes sure your are logged in, and then making sure you are on the right page by checking a cookie set at login. This code works on a page in a directory underneath the login in script, however in a page in a directory below that it always takes you to accessdenied. Any ideas?
<?php
session_start();
if(!isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')) {
header("location: http://mywebsite.com/member/accessdenied.html");
exit();
}
$_COOKIE["verify"] = $verify;
if( $verify != file_get_contents("name.txt")) {
header("location: http://mywebsite.com/member/accessdenied.html");
} else { }
?>
And it seems like just the bottom part, the part that checks the cookie, isn't working. Again, any ideas?
I think you have your cookie assignment backwards:
$_COOKIE["verify"] = $verify;
Should be
$verify = $_COOKIE["verify"];
And that should be:
$verify = isset($_COOKIE["verify"])?$_COOKIE["verify"]:false;
As if the cookie was not previously set, well it would give a notice error.
<?php
$verify = $_COOKIE["verify"];
if( $verify == file_get_contents("name.txt")) {
echo $verify . 'is equal to the content of name.txt'
} else {
echo $verify . 'is NOT equal to the content of name.txt'
}
?>
Try debugging the code with this. See if the content of your variable is what you want. But I find it unusual that a variable would be a file.
are you sure you always get the content from file_get_contents? I could imagine it's found in one directory but not in the other!
antoher idea: cookies can be set to be relevant for a particular directory only. I just realize, what we're missing here, is the part where you set the cookie in the first place.

Categories