PHP: Sending a constant through a form and auto-sending it - php

For a website, I need to route users to their own page. I have a login form, which sends data to a PHP file to check if the user's information is correct, and if so, forwarding the user to their page. The only problem is that I need to validate the user on arrival, to check if they logged in or just typed out the URL. I plan to use this with a POST, but how can I auto-send the constant (i.e. "logged-in")? Is there a way to do that through an HTML form (outputted from an echo) and sending it when the page loads? Thanks in advance!
EDIT 1: I understand that I must use Sessions, but whenever the page redirects it clears the session. The whole reason I was asking this was because I needed a way to keep the session active. How do I redirect in a way that doesn't clear the session?

In the PHP file that validates their credentials, start a "session". You can then apply session variables that can be called at any time while the session is valid. You can do this with POST, which is sounds like you're using, or by querying a database upon validation.
For example, upon validation:
session_start();
$_SESSION['username'] = $_POST['username'];
$security_check = mysql_query("SELECT * FROM userList WHERE username = '$username'");
$row = mysql_fetch_assoc($security_check);
$_SESSION['userId'] = $row['userId'];
$_SESSION['userFullName'] = $row['userFullName'];
On subsequent pages, you can put the following code at the top to check if the user logged in. If not, it will kick them back to the index page; otherwise the $_SESSION variables will be maintained.
<?php
session_start();
if (!isset($_SESSION['userId'])) {
echo "<script> window.location.replace('index.php?login=no') </script>";
}
?>
As suggested in the comments, I would recommend doing some further research on sessions to get a full understanding of how they work.

Related

PHP SESSION Conflicts

I have this in my $_SESSION setting script:
<?php
//----------------------// Start session----------------------
if(!isset($_SESSION))
{
session_start();
}
//------------------------------------------------------------
//------------------// Check if Username $_SESSION is set------------------------------------------
if (!$_SESSION['Username']) { // If not current User
header("Location: ./logout.php"); // Session destroy file that leads to session logout landing page
exit();
}
//------------------------------------------------------------
?>
Now, what I basically do is just check if Username SESSION is set. But, I have come to notice something strange while putting another user through:
If we click the same link at the same time and arrive on the landing page same time, I noticed I can see my Username displayed as his Username and his personal data like email and phone replaced mine in my very own PC! This is really strange to me as we do not even live in the same country or even share same PC.
So, it is obvious I have not secured my SESSION and I have used a lame approach without thinking about security and this can be abused with SESSIONS hijacked.
How do I resolve this conflict? How do I restrict each logged in user to a particular session without conflicts if two or more users access the same resource at the very same time? I need help. I can't sleep since I found this.
After reading your responses, I will now show a snippet of the functions.php file which outputs Use data from DB.
First, I get the UserName value from session using:
$UserName = $_SESSION['Username'];
With this value, I query DB to get more user details:
//------------Get User Info -- All user column
$Get_User_Info = mysqli_query($conn,"SELECT * FROM customers WHERE User='$UserName'");
/************************************************************/
/************************************************************/
$Get_User_Info_row = mysqli_fetch_array($Get_User_Info,MYSQLI_ASSOC);
/************************************************************/
//---- Now list all user rows
$GLOBALS['Skype'] = $Get_User_Info_row['Skype'];
$GLOBALS['Jabber'] = $Get_User_Info_row['Jabber'];
$GLOBALS['ICQ'] = $Get_User_Info_row['ICQ'];
$GLOBALS['Join_Date'] = $Get_User_Info_row['Join_Date'];
$GLOBALS['Join_Date_Time'] = $Get_User_Info_row['Join_Date_Time'];
$GLOBALS['Balance'] = number_format($Get_User_Info_row['Balance'],2);
The above is what is contained in the functions.php which I require with each page I need protected.
As you can see, I barely see where I have done too much wrong there.

Whats the best way to keep a user signed in after their session ends?

I'm working on a simple login page for a class and was planning on using cookies to keep users logged in (if they choose) after closing their browser. I used a checkbox input button as a case to set a cookie. After a user goes to the login page and signs in I send them to a script to check for valid username and passwords where I also check if the button was used
#QotD.php
if(isset($_GET['signed_in'])) #check box value
if($_GET['signed_in']=="on"){
if(isset($_GET['username']))
$username = $_GET['username'];
setcookie('username',$username,time()+10000);#cookie set with username
}
What I thought to do was to have a conditional statement at the beginning of the login page file checking whether a cookie is set and if it is go directly to the main page.
#QotD_homepage.php
if(isset($_COOKIE['username'])){
header("Location: main_page.php");
exit();
}
The problem is that it seems to keep the user signed in whether they check the box off or not. I tried adding a button to unset the cookie but it didn't work. Is there a more efficient way to handle cookies in this manner?
Firstly, for signing in a user, you are going to want to use the POST action method as it hides the information from the url. The GET method contains the information in the url and can be easy copied and hacked.
Secondly, you if statements should look like this
if(isset($_GET['username']))
{
$username = $_GET['username'];
# do something with username...
if(isset($_GET['signed_in']) && $_GET['signed_in']=="on")
setcookie('username',$username,time()+10000);
}
}
To solve your question regarding why user is being logged in every time, even when you don't set the cookie, the reason is probably because you have not unset the cookie. This is usualy done via a logout page.
Create a logout page with the code:
setcookie('username', null, 1);
Then run this page every time you wish to unset the cookie to test the login without ticking the checkbox.
Hope it helps :)
If conditional statement is wrong.Fix it by ending it with end if or using {} brackets. Use the code below
<?php
if(isset($_GET['signed_in'])) { #check box value
if($_GET['signed_in']=="on"){
if(isset($_GET['username']))
$username = $_GET['username'];
setcookie('username',$username,time()+10000);#cookie set with username
}
}
?>
OR
<?php
if(isset($_GET['signed_in'])) : #check box value
if($_GET['signed_in']=="on"){
if(isset($_GET['username']))
$username = $_GET['username'];
setcookie('username',$username,time()+10000);#cookie set with username
}
endif;
?>
Hope this helps you

how to assign post globals on a redirected page?

I have a login form which sends 3 post values from username, password and submit button. But my form processor has 3 pages one is validation.php which validates the field second is read.php which checks the posted values against db and third is login.php which is a result of login success. All redirect to each other respectively on success. Problem here is that when I try to access the user posted values from form in read.php (redirected page) not validate.php (action page) I get an error of undefined index.
I really don't see why you are doing all those redirects, but if you want to make the data more persistent you could use a session variable, because the $_POST superglobal is only set for the current request.
firstfile.php
<?php
session_start();
$_SESSION['posted_data'] = $_POST;
other file
<?php
session_start();
var_dump($_SESSION['posted_data']);
However as already stated you may really want to reconsider doing all the requests.
UPDATE
Besides the fact that you will loose your data you are also doing multiple (unneeded) requests to simply sumbit the form. The only redirect that should happen is to the successpage when you have done all you work. See this for more information: http://en.wikipedia.org/wiki/Post/Redirect/Get
If you are look to keep you code clean you could always just include the other files or go for an OOP approach.
You should do one page only that will do all the work. That doesn't seem too complicated of a script, so I would advise putting everthing together on one page.
You did not provide any code so I'll show you a general example. I just typed it without rereading so it's not pure PHP syntax, just the spirit:
<?php
$login=$_POST['login'];
$pwd=$_POST['pwd'];
$dbcheck = mysql_fetch_array(mysql_query("SELECT COUNT(1) FROM table WHERE user =$login and pwd = $pwd"))
if($dbcheck[0] > 0) {
//Login success
//Setup your session variables, cookies, etc
//Then you can do your redirect here
} else {
//Page for wrong login
}

How do I fix this security hole?

I have a website that currently works. It has a page that displays information, and another that lets you edit the information sources. Now when you login on index.php it posts the data to view.php through a form. The site doesn't use any cookies. When I click edit, it posts the username, passhash, and the submit request to edit.php. Currently, this button works well, but the current code for the edit button is as follows:
<FORM NAME ="form1" METHOD ="post" ACTION = "edit.php">
<p class="BodyText">
<INPUT TYPE = "Hidden" Name = "Username" Value = "<?php print($username); ?>">
<INPUT TYPE = "Hidden" Name = "PassHash" Value = "<?php print($password); ?>">
<INPUT TYPE = "Submit" Name = "Change" VALUE = "Edit">
</p>
</FORM>
I hadn't noticed before, but now I notice as I look through the code, that it prints the password. I don't really know how else to get the password to the edit page without this, but when I inspect the element in Chrome, I can see the password hash (SHA-1). Firstly, and I assume yes, is this a security hole? Secondly, how to I pass the passhash along to the edit.php page without sending the hash back to the end user. Thirdly, am I doing this wrong entirely? It seems OK to me to login through post, but is that security crazy? I'm kinda new at PHP, and new at security entirely.
This is not a good way to do this (hidden inputs in the form).
Learn about PHP Sessions.
Check out some of the examples from the PHP manual.
You'll want to preserve the user's access across their session between pages and you should never print out their passwords.
You can validate users' passwords to authenticate them, and have the session hold information on who the user is, and whether they are logged in for that session (rather than trying to validate passwords on every single page).
One example flow:
When authenticating (user logs in):
session_start();
// Authenticate user here with the password.
if (someAuthenticationFunction($_POST['user'], $_POST('password') === true) {
$_SESSION['user'] = $user;
$_SESSION['loggedIn'] = true; // Notice we're not saving the password into the session, only whether user is loggedIn.
}
On every other page where you would want to check user's authentication (most likely on edit.php page):
session_start();
if ($_SESSION['loggedIn'] === true) {
$user = $_SESSION['user'];
// Do the actual editing stuff here.
}
Once the user is ready to log out, use session_destroy() (most likely on a logout page).
u can save the password in the $_SESSION variable.
For it you have to write in the page where the login form gets processed:
session_start();//at top of the page
$_SESSION['user'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
After this is set you can get the username in every file where
session_start();
is written.
If you don't want to use cookies, you could use some kind of session ID passed in the URL (see php.net/output_add_rewrite_var) and store it in a database, but then you'd be opening a whole new can of worms to do with session hijacking. COokie-based PHP sessions are the way to go.

PHP, Prevent users from accessing a page while not logged in?

How can I prevent a user from accessing a page when they are not logged in? I want him to be redirected to the login page. I know it has something to do with sessions.
It works like this:
Start a session: session_start()
If Session["user"] == null, redirect to the login page, else continue.
In the login page, ask the user for password using a form
Post this form to the login page
Check against your authentication service (e.g. a table in mysql) if the user is authorized
If yes, Session["user"] = $userName, redirect the user to the page. If no, prompt for password again
Of course, this is all very, very simple. In your session, you could keep a complex user object, or anything. Good luck coding.
As Svetlozar Angelov pointed out the following code would work well:
if (!isset($_SESSION['nID']))
header("Location: login.php");
However.. this would not actually secure the page against users who really wanted access. You need to make some adjustments:
if (!isset($_SESSION['nID']))
{
header("Location: login.php");
die();
}
This prevents bots and savy users who know how to ignore browser headers from getting into the page and causing problems. It also allows the page to stop executing the rest of the page and to save resources.
Its also noteworthy that $_SESSION['nID'] can be swapped out for any other variable you are using to store usernames or id's.
When he logs - store a session variable. Then in the beginning of every page
session_start();
if (!isset($_SESSION['nID']))
header("Location: login.php");
If the login is ok
session_start();
$_SESSION['nID'] = 1; //example
Follow these steps:
Create a login.php page accessible to everybody where a user enters her username and password in a form. This form must be submitted to login.php itself. (action='login.php'). Also include a hidden variable in your form which tracks if the form has been submitted.
If the hidden variable is set, check if the username ($_POST['user']) exists in your DB, and that the password matches the username. If it does, store the username in a $_SESSION variable like this:
$_SESSION['username'] = $_POST['user'];
If it does not, reload login.php like this:
echo 'header("login.php")'; //You should not have echoed anything before this
Now include login.php in every user page you create. Suppose you were writing an email application, create an inbox.php like this
include ("login.php")
Now, login.php will check if the session variable 'user' is set and allow access to authorised users only.

Categories