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
}
?>
Related
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.
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.
I'm submitting a FORM to itself using action="" but what's odd is that my variables are updating after the submission.
<form action="" method="post">
<input type="text" name="username">
<input type="text" name="password">
<input type="submit">
</form>
Once this has been submitted and the user successfully logged in, the rest of the page doesn't seem to respond to the updated variables unless I hard refresh.
if ( isset($_POST['found_step_1']) ) {
global $wpdb;
// We shall SQL escape all inputs
$username = $wpdb->escape($_REQUEST['username']);
$password = $wpdb->escape($_REQUEST['password']);
$remember = $wpdb->escape($_REQUEST['rememberme']);
if ($remember) {
$remember = "true";
} else {
$remember = "false";
}
$login_data = array();
$login_data['user_login'] = $username;
$login_data['user_password'] = $password;
$login_data['remember'] = $remember;
$user_verify = wp_signon( $login_data, true );
if ( is_wp_error($user_verify) ) {
echo "Invalid username or password. Please try again!";
$current_step = 1;
} else {
//echo "<script type="text/javascript">window.location='". get_bloginfo('url') ."'</script>";
$current_step = 2;
}
$wpdb->flush();
}
When the page below renders... it's like it's rendering what WAS there before the POST ... the only way to get it to display what the latest data consists of is to hard refresh the page. It's really odd.
EDITED
You need to make the login process one of the first things your script does. I once had similar problems and then found out that I was making the login process too late in my script. I will put a practical pseudo-example that will NOT work as intended:
<?php
if (in_array("Maths",$Subjects) $MainSubject="Maths";
if ($_POST['name'] == "Admin" && $_POST['password'] == "MyCoolPassword!")
{
$Lang=en;
$Subjects = array ("Maths","Physics","English");
}
echo $MainSubject;
?>
This is a too simple code (and will throw some errors), so the mistake is easy to spot. But what if you are working with several includes, calling functions here and there and doing many things like this? Then the same mistake could occur at a large scale. Just one thought, but without more code from the OP we cannot really answer, just give some 'maybe it's this'.
Other thing that could go wrong is that cookies are set AFTER finishing parsing the php code, not at the instant that setcookie() is called in the code. A more throughout answer can be found here: php set cookie issue
what's odd is that my variables are updating after the submission. I guess you mean your variables are NOT updating right after the submission from the rest of the question, it's pretty unclear. Please post more code so we can help you better.
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.
I have the following php code below...
if ($username == 'fredk')
{ $fname = 'Fred'; }
else if ($username == 'arbonk')
{ $fname = 'Arbon'; }
else if ($username == 'arsalana')
{ $fname = 'Arsalan'; }
else if ($username == 'minhn')
{ $fname = 'Minh'; }
else if ($username == 'nathanielg')
{ $fname = 'Nathaniel'; }
$msg = "Hi $fname, your login was successfull. <p></p>";
All i want to do is pass the $fname variable onto the next php page. On the same page I also have a form and when the submit button is clicked it goes onto the next page.
Anyone have any ideas??
Look into sessions. They're used for the exact reason in your example (persistent login credential data + more).
session_start(); // Do this at the very start of your script (on both pages).
$_SESSION['your_key_here'] = 'blah'; // value may be an object as well.
on the next page you can access it:
print_r($_SESSION['your_key_here']);
Put it into the session.
Session is the way to do that...
Or you can put the variable into the form as a hidden variable
<input type='hidden' name='who' value='$fname>
but, this is just for completeness sake,
I would probably use a session myself.
use session variable and put the fname in session.
Looks like you need to use $_POST
for example if this is your form code:
<form action="page.php" method="post">
<input name="fname" type="hidden" value="$fname" />
</form>
On page.php you would retrieve the fname variable like so:
$fname = $_POST['fname'];
Where does $username come from? Could you perhaps write a function that takes $username as a parameter and returns $fname, and call it on both pages?