loosing data on page refresh php session - php

I am posting data from one site to another, then turning that posted data into a session.
form from other site
<form action="https://www.122.co.uk/11/" method="POST">
<input type="hidden" name="userid" value="1010101">
<input type="submit" value="Go" style="font-size:14px; padding:20px;">
I then post this data to my new site where I turn it into a variable $userid
then checking that the variable is empty or not, if not show some code.
check variable is not empty
if (!empty($userid)) {
?>
<div class="container">
<?php
echo "<hr>";
echo "You Are Logged In,</br>";
echo "Your User ID is <strong>" . $_POST['userid'] . "</strong>.";
When I refresh the page with a button click I loose the session data, so the code in the check dose not show.
how do I have a button to refresh to page and keep session data ?
button to refresh
<button class="btn btn-primary hidebutton showbuttonv2" role="button" id="homebutton" onClick="history.go(0)">Home</button>
Full code spinet
<?php
session_start();
$_SESSION['userid'] = $_POST['userid'];
$userid = $_SESSION['userid'] = $_POST['userid'];
//$_SESSION["userID"] = $userid;
if (!empty($userid)) {
?>
<div class="container">
<?php
echo "<hr>";
echo "You Are Logged In,</br>";
echo "Your User ID is <strong>" . $_POST['userid'] . "</strong>.";

This is because you're always overwriting the session data with the POST data, even if there isn't anything in the $_POST['userid'] field.
I see that you are very new to programming (PHP), and as such I would recommend you to sit down and think a bit about what you want to do. Then try to write down short item lists of the steps needed to do these things. Remember to be really specific, as that is what you need to be when writing the code. This is called pseudo-code, and is a vital tool in programming.
Once you've done that, read through the code you've written, and really read what it does. Not just what you expect it to. Then you'll learn a lot about how programming works. ;)
Short example, based upon the code you've posted:
Start session.
If user submitted ID -> Store ID in session
If session contains user ID -> Show login confirmation.
: Else -> Show login form
Your code, in "English" form.
// Start the session
session_start ();
// Save the POSTed value from the form in the session array.
$_SESSION['userid'] = $_POST['userid'];
// Save the POSTed value fromthe form in the session array, and a variable of its own.
$userid = $_SESSION['userid'] = $_POST['userid'];
// If we have a (non-empty) value in the user ID variable.
if (!empty ($userid)) {
// Show the login confirmation.
}
As you can see, there is a discrepancy between your expected behavior and the code you wrote. :)
Remember: Details always matter in programming.
Also, using JavaScript's history to create breadcrumb isn't the best option. This will lead to somewhat unpredictable behavior for the users, especially if they come to your page from a web search. (It'll take them to the search engine again, instead of your home page.)
That is why I recommend using proper URLs instead. Either relative, or dynamically created full ones. That way you always have full control where the user ends up when clicking on your links. :)
Edit, Added #2:
Here's how I'd write the code, to perform the tasks outlined by the pseudo-code.
// Using sessions to persist data across page views.
session_start ();
// Check if user has tried to log in.
if ($user = login_user ($username, $password)) {
// He has. Use session to keep him logged in.
$_SESSION['user'] = $user;
}
// If the user is logged in, show confirmation message.
if (!empty ($_SESSION['user']['id'])) {
$page = 'login_confirmed';
} else {
$page = 'login_form';
}
See how the comments, and the code, aligns withe the pseudo-code from the bullet list? And how it describes exactly what you want, in detail? ;)

You probably do not want to set $_SESSION['userid'] to the value of $_POST['userid'] if this last one is empty.
<?php
session_start();
// check that $_POST['userid'] is set
if (isset($_POST['userid'])) {
$_SESSION['userid'] = $_POST['userid'];
$userid = $_SESSION['userid'];
}
if (!empty($userid)) {
?>

Related

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

same php session name

I have two same php website(website A and B). The website as below.
php website
<?php
session_start();
if(isset($_SESSION['user'])){
echo "Welcome " . $_SESSION['user'];
}else{
if(isset($_POST['userName'])){
$_SESSION['user'] = $_POST['userName'];
}
}
?>
I post a value userName=Bear to A website by html form.
After i open the B website with same browser, it will output this
Welcome Bear
B website session is not set. But B still got A website session.
A website and B website in same computer.
How i can fix it?
Except change the session name or change browser.
Are there other ways to do it?
Thank you!
Session is maintained with the browser. When one user has logged in with the browser the other user cannot login with the same browser. Because the browser is already running one session.If u try to login it gives you the current session which is running. For that reason you get Welcome Bear when to try to login with Account B, whereas Account A is already logged in. Take an Example of Gmail you cannot login two Gmail accounts on the same browser simultanioulsy. So Better use different browser while logging with two accounts.
use Diffrent Browser.
You can use named sessions to achieve this, though it isn't full-proof since it relies on a GET variable. Here is an example of how you could implement using a get variable userName
if($_GET['userName']) {
session_name($_GET['userName']);
}
session_start();
Since session_name gets or sets a named session, depending on whether it already exists, the above would work as long as the session identifier is passed in with the request. If the URL is modified and the request is made without the identifier, you would want to handle that as you see fit (destroy any existing sessions and start a fresh one, fallback to session based on cookie, etc).
Also, I would imagine that having the actual session name be "bob123" might be a security risk, since it would be much easier to steal someone's session if you know it's always their user name, so you should research recommendations for how to reduce this risk.
EDIT #2
Try this then. This will check if the session is set and not empty.
<?php
session_start();
$_SESSION['user'] = $_POST['userName'];
if(isset($_SESSION['user']) && (!empty($_SESSION['user']))){
echo "Welcome " . $_SESSION['user'];
}
else {
echo "Sorry you do not have access.";
}
?>
Assuming your form resembles this:
<form method="post" action="session_file.php">
Username: <input type="text" name="userName">
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
OLD
As per your original question
sesstion_start(); is misspelled
Use session_start();
Plus you missed a semi-colon in $_SESSION['user'] = $_POST['userName']
Another reason is that you didn't assign your POST username to a SESSION name.
I.e.: (which I added below)
$_SESSION['user'] = $_POST['userName'];
PHP (session_file.php) as per the HTML form action below
<?php
session_start();
if(isset($_SESSION['user'])){
$_SESSION['user'] = $_POST['userName'];
echo "Welcome " . $_SESSION['user'];
}else{
if(isset($_POST['userName'])){
$_SESSION['user'] = $_POST['userName'];
}
}
// var_dump($_SESSION['user']); // for testing purposes
?>
EDIT (added session_destroy() if one exists already)
In conjunction with the following HTML form (PHP)
If a session already exists, for example Bear using the form below as shown, will not show it, because it will check if a session already exists, and if one does exist, it will destroy it and create a new one, which will echo the new name on the next page.
<?php
session_start();
if(isset($_SESSION['user'])){
session_destroy();
}
?>
<form method="post" action="session_file.php">
Username: <input type="text" name="userName" value="<?php echo $_SESSION['user']; ?>">
<br><br>
<input type="submit" name="submit" value="Submit">
</form>

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

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.

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.

How to check if username exists on the fly in a form?

I have a page with a register form.
"Username" is one of the fields filled out by users.
The form submits to another php page, which checks if the username is already taken or not.
If taken, then I need to go history.back() and at the same time set a session variable, so the previous page knows that the username exists, and display an error message.
Is this possible? Ie is php code executed when going back in browsers?
It would be alot of extra work if I had to use sessions and do a simple redirect, because then I would have to "Remember" all the other form-inputs as well, so the user doesn't have to fill the entire form out again.
OR
maybe there is another way of checking whether a username is busy or not.
I use MySql as DB, so thats where the usernames are stored.
Thanks
how about using AJAX?.. you wont need to reload nor change the page.
I have seen many sites that have a link next to the username input to validate the user name.. or you could do it automatically on keypress...
good luck
While you are correct in saying you'd have to 'remember' the form inputs, why do you not do the checks and output a block of JS that will redirect to the login page using the values posted if the username already exists. Then, have the login page pre-populate the login input with these values.
Using this method, you will be able to set your session variable, redirect the user back to the login page (with an error message if you wish) AND repopulate the inputs with the previously posted variables.
Using the back() function is definitely not the way to go about this. Avoid back() for things like this at all costs.
To answer your question regarding PHP being executed when you go back() - this probably depends on the caching policy of the page and the behavior of the browser. As such, this would not be a reliable way of sending data back to the form.
An alternative would be to use AJAX to check the username. That way you would not have to leave the registration page at all, as availability would be checked BEFORE submitting the registration form.
A good idea would be to process the form in the same script, above where your form is generated. That way, you can user $_POST global array. For example:
<?php
if (isset($_POST['submit'])) {
// do chat name check here
$chat_name = mysql_real_escape_string($_POST['chat_name']);
$sql = "SELECT COUNT(*) AS count FROM users WHERE chat_name = '$chat_name'";
$res = mysql_query($sql);
$row = mysql_fetch_assoc($res);
if ($row['count'] > 0) {
$chat_name_exists = true;
} else {
$chat_name_exists = false;
}
}
if ($chat_name_exists) {
echo '<p class="error">Sorry, but that chat name already exists</p>';
}
$chat_name = (isset($_POST['chat_name'])) ? htmlentities($_POST['chat_name']) : "";
echo '<form action="" method="post">';
echo '<input type="text" name="chat_name" value="' . $chat_name . '" />';
echo '<input type="submit" name="submit" value="Check" />';
echo '</form>';
This was written off the cuff, so don't copy-and-paste but integrate into your application as it best fits. You also eliminate the need to rely on JavaScript this way, too.

Categories