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.
Related
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
}
?>
I am building a website and i would like to secure it against Session Hijacking. Reading for this i came across someone saying that:
A general rule of thumb is to generate the session ID each time a user changes his access level.
1.When a user log in
2.When a user log out
3.When a user get administrative access
For what is worth, my website will be seperating the access levels into users logged-in and users logged-out. All forms are submitted using the POST method.
index.php
<?php
session_start();
//Setting the variable initialy to false
$_SESSION['LOGGED_IN'] = FALSE;
//to use SSL
$serverport = $_SERVER['SERVER_PORT'];
$server_http_host = $_SERVER['HTTP_HOST'];
$server_request_uri = $_SERVER['REQUEST_URI'];
if (headers_sent())
{
die("HTTP headers have already been sent ");
}
else
{
if($serverport != '443')
{
ob_start();
exit(header('Location: https://'.$server_http_host.$server_request_uri));
}
}
if(isset($_POST['SUBMIT']))
{
if(isset($_POST['TOKEN']) && $_POST['TOKEN'] == $_SESSION['TOKEN'])
{
//Open database connection
require_once('connect_db.php');
//Calling functions.php that includes all custom functions
//ErrorHandler()
require_once('functions.php');
$email = $_POST['EMAIL'];
$password = $_POST['PASSWORD'];
$statement = $DBH->prepare("SELECT * FROM user_details WHERE email=:email AND pwd=:password ");
$statement->bindParam(':email',$email);
$statement->bindParam(':password',$password);
$statement->setFetchMode(PDO::FETCH_ASSOC);
try{
$result = $statement->execute();
$rows = $statement->rowCount(); // shows how many times the user is available in the user_details table
$data = $statement->fetch(); //fetches the data related to that user from user_details table
}
catch(PDOException $e)
{
//this is custom function
echo ErrorHandler($e);
}
if($rows == 1)
{
//this means that the user has inserted the correct credentials
//regenerate session_id each time there is a change in the level of privilege to mitigate SESSION FIXATION
session_regenerate_id(true);
//turning logged in variable to true as soon as it finds a match
$_SESSION['LOGGED_IN'] = TRUE;
//saves the email into a session so it can be used in mainpage.php
$_SESSION['EMAIL'] = $email;
//redirect to main page
header('Location:https://www.example.com/mainpage.php');
}
else
{
echo "<br />Wrong username or password!<br />";
}
}//closing *if(isset($_POST['TOKEN']) && $_POST['TOKEN'] == $_SESSION['TOKEN'])*
}//closing *if($_POST['SUBMIT'])*
//creating a random token to inject in our HTML form
$token = base64_encode(openssl_random_pseudo_bytes(32));
//store the random token in the session variable so we can later compare it to the one in the HTML form
$_SESSION['TOKEN'] = $token;
?>
<form action="index.php" method="POST" accept-charset="UTF-8">
<p>Email: <input type="email" name="EMAIL" /> </p>
<p><input type="hidden" name="TOKEN" value="<?php echo $token; ?>" /></p>
<p>Password <input type="password" name="PASSWORD" /> </p>
<p><input type="submit" name="SUBMIT" value="Submit" /></p>
</form>
The script accepts input email and password from the user,checks the database and if it finds a match it redirects the user to the mainpage.php.
mainpage.php
<?php
ob_start();
//the code to set the header must be called before output begins
session_start();
$serverport = $_SERVER['SERVER_PORT'];
$server_http_host = $_SERVER['HTTP_HOST'];
$server_request_uri = $_SERVER['REQUEST_URI'];
if (headers_sent())
{
die("HTTP headers have already been sent ");
}
else
{
if($serverport != '443')
{
ob_start();
exit(header('Location: https://'.$server_http_host.$server_request_uri));
}
}
if(($_SESSION['LOGGED_IN'] == TRUE) && isset($_SESSION['LOGGED_IN']))
{
$email = $_SESSION['EMAIL'];
echo $email;
//Calling functions.php that includes all custom functions
//LogOut()
require_once('functions.php');
if(isset($_POST['LOGOUT']))
{
//its a custom function that is used for logging out
LogOut();
}
echo '
<form method="POST" action="mainpage.php">
<p><input type="submit" name="LOGOUT" value="Log Out" /></p>
</form>
';
}
else
{
echo "Please login in order to use example.com";
}
?>
Is there a way for me to check if the way i have built these 2 scripts really regenerate the Session ID? I am using Firefox's extension LIVE HTTP headers but i am not sure if i am reading it correctly.
Also, i cannot find a way to track down and read the content of COOKIES stored while using my browser (either Chrome or Firefox or even IE11). How can i do that?
Another question that is related with security:
Implementing an anti-CSRF token:
Do i need to implement an anti-CSRF token for each form in my website [i guess the answer is Yes but i want to confirm it]? Should each token be different than the token used in a previous form? For example the token in index.php to be different than the token used in mainpage.php if it had a form as well.
Does the token technique prevent against any other kind of attack?
I would be glad if you indicate wrong programming in the code above, so i can correct it and learn at the same time.
Thanks!
I'm going to focus on your questions and not necessarily a thorough code review, since I think your questions are the main reason you're posting.
A simple way to check your current session id or PHPSESSID is to check under Chrome's Developer Tools > Resources > Cookies. You'll see the (initially-generated) session ID. You can check this value before and after a user logs in. If the value changes, your session id has actually been regenerated.
You can also view cookies in Firefox by right-clicking the current page, going to View Page Info and using the Cookies tab.
On CSRF (prevention) tokens, the answer varies. People use different methods to go about them. I would say a majority of websites set a token in $_SESSION upon any regenerate of the session id. So for the duration of the current session, the CSRF token will remain the same and check against hidden inputs for that CSRF token.
On the other hand, I've also heard of regenerating a CSRF token for every single form that is client-facing. Your way of doing it is up to you. Nothing is 100% bulletproof, but getting as close to 100% as you can is the idea.
Take a few minutes to read up on CSRF tokens and the Synchronizer Token Pattern.
Best of luck!
I have 3 pages:
index.php
login.php
display.php
index.php
Sets up AngularJS using the ngRoute module to navigate my pages.
login.php
Loaded by default and sets PHP $_SESSION variables.
display.php
Echos the contents of $_SESSION.
I navigate to display.php from login.php using a link setup with ngRoute.
Problem
display.php does not show $_SESSION variables no matter how many times I navigate to and from it. It will only display them if I manually navigate to the page such as refreshing the page or entering the address in the browser.
I know the php code is executed because I can echo other things to the screen it just doesn't access the $_SESSION variables.
Why is this?
I think i might see where your problem is. You try to access php session in your single page angularJS HTML templates am i right? like:
<div ng-repeat="n in <?php $_SESSION['someSessionArray'] ?>">
That is not how it works. Your $_SESSION will never be available in your templates.
What you can do, is use an ajax request for your login authentication and have that request give you a session id.
Then use that session id when starting your session in further ajax requests (as already mentioned).
Then, when you want to store something to the php session, access the data via ajax request and php service.
a VERY, VERY, VERY, simple Example:
inside getFromSession.php
session_start($_GET['session_id']);
$key = $_GET['key']
echo json_encode($_SESSION[$key]);
inside storeToSession.php
session_start($_GET['session_id']);
$key = $_GET['key'];
$value = $_GET['value'];
$_SESSION[$key] = $value;
inside your login.php
$user = yourAuthMechanism($_GET['username'],$_GET['password']);
if($user) {
session_start();
echo json_decode(array('status' => 'success','sid' => session_id()));
}
else { ... error handling
inside anywhere in your angular where you need to access session data:
$promise = $http.get('pathtoyourphp/getFromSession.php?key=foo');
$http.set('pathtoyourphp/getFromSession.php?key=bar&value=4');
// now use promise to acces the data you got from your service
In general, no reason exists, why AngularJS apps, which request
PHP-based server-side stuff, won't be able to read $_SESSION.
That said, please provide at least the core concepts of of your AngularJS code, so we can provide further details.
Additionally, put just this in display.php:
<?
echo __FILE__
. '<br />' . date( DATE_RFC822 )
. '<br />' . var_dump( $_SESSION )
;
// intentionally skipped dangerous closing PHP-tag
Now run your AngularJS app and tell what comes out.
Make sure you start the session before reading the SESSION variables.
<?php
session_start();
echo $_SESSION["user9"];
?>
I don't think you're looking for angularJS.
I think you're looking for something more like this.
index.php:
<html>
<header>
<title>Login</title>
</header>
<body>
<form method="POST" action="login.php">
<input type="username" name="username" placeholder="username" />
<input type="password" name="password" placeholder="password" />
<input type="submit" value="Login" />
</form>
</body>
</html>
login.php
<?php
session_start();
if(empty($_POST)) {
die("You don't have permission to be here.");
} elseif(empty($_POST['username']) or empty($_POST['password'])) {
die("All fields are required.");
}
$username = "admin";
$password = "password";
if($_POST['password'] == $password && $_POST['username'] == $username) {
$_SESSION['loggedIn'] == "true";
header("Location: show.php");
} else {
die("Invalid login");
}
?>
show.php
<?php
if($_SESSION['loggedIn'] == "true") {
echo "You are logged in";
} else {
die("You don't have permission to be here.");
}
?>
I'm making a login system with php, and when I submit the correct information, it set's a cookie. the form action sends to the same page, wich has an isset cookie verification on top, but since cookies need a refresh after they're set, you need to refresh page another time so it can notice that cookies are there.
what's a workaround for it? here's my code (where username and password are "admin" just as a placeholder. when I get the system working, I'll pull values from database.)
<?php
if(isset($_COOKIE['user']))
{
echo "Hello, administrator.<br />";
echo "<a href=?logout=yes>logout</a>";
if(isset($_GET['logout']))
{
setcookie("user", $_POST['username'], time() - 3600);
}
}
else
{
if (isset($_POST['submit']))
{
if (($_POST['username']=="admin")&&($_POST['password']=="admin"))
{
setcookie("user", $_POST['username'], time() + 3600);
}
else
{
echo "empty field or wrong user/pass.";
}
}
else
{
echo "nothing submitted. show form.";
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table border="0">
<tr><td colspan=2><h1>Login</h1></td></tr>
<tr><td>Username:</td><td>
<input type="text" name="username" maxlength="40">
</td></tr>
<tr><td>Password:</td><td>
<input type="password" name="password" maxlength="50">
</td></tr>
<tr><td colspan="2" align="right">
<input type="submit" name="submit" value="Login">
</td></tr>
</table>
</form>
Unless you absolutely need to use a custom cookie, I would suggest to use the $_SESSION global instead. $_SESSION data is available as soon as you set it. But its more important feature is that the data is not stored on the client. What that mean in plain is that the user can never access its data. So it is harder to hack your login system. With a cookie, as other have pointed out, anybody can read and edit the data!
session_start();
if (isset($_GET['logout']))
{
unset($_SESSION['username']);
}
if ($_SESSION['username'] == 'admin')
{
echo "hello admin!";
}
else if (($_POST['username']=="admin")&&($_POST['password']=="admin"))
{
$_SESSION['username'] = $_POST['username'];
}
To use the $_SESSION globals, you need to put session_start() at the beginning of your script (before sending any data). It should solve your problem of redirection at the same time. Note that behind the scene, $_SESSION use a small cookie, but you don't really have to think about it. It only contain a small id.
more information on session
http://www.php.net/manual/en/book.session.php
PS : to be honest, I would still use a redirect here. When you POST a form and press the back button, the browser ask you to send the data again and its annoying. Using a redirect with header("Location: " . $newUrl); remove that annoyance. But just my 2 cents.
$loggedin = false;
if(isset($_POST['submit'])) {
// Do login checking and set cookies
$loggedin = true; // if the case
}else if(isset($_COOKIE['username']) && isset($_COOKIE['password'])) {
// Check if valid login
$loggedin = true; // if the case
}else{
// They are not logged in.
}
Then use the veriable $loggedin to see if they are logged in. I suggest making a user class though to handle this, so do you keep using the same code over and over again in your files.
You can make your own function to set cookies, ie:
function my_setcookie($name,$value,$expire){
$_COOKIE[$name] = $value;
return setcookie($name,$value,$expire);
}
But better idea is to redirect user after successful 'POST' request, so if the page is refreshed, browser won't complain about resending POST data.
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?