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>
Related
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)) {
?>
After user first time register and login, if user do not logout, then when user visit next time, how can I log in user automatically, so he do not need to login again. I think it can be handled via session, but how can i do it? Please help me or provide some tutorial. Thanks in advance
You need to set a cookie on the users PC php.setcookie
First of all if you just need login then session is enough but if you mean that user shouldn't be asked for login again then you might wanna go for cookies.
For session
Validate User And Set Session variables
For each request check if corresponding session values exit.
For Cookies
When the user logs into your website.
Store a cookie on his/her system.
For each user login first check if there is any cookie on user's system that you already stored.
For tutorial check this link
On login function validate & then create
$_SESSION['isLogged'] =1
or you can assign username too, as session is stored in server there is no harm in doing that
$_SESSION['username']=$username;
then in login page simply use :
if( $_SESSION['isLogged'] ==1)
header("Location: dashboard.php");
Example login.php
<?PHP
session_start();
if( isset($_SESSION['isLogged']) && $_SESSION['isLogged'] ==1)
header("Location: dashboard.php");
if(!isset($_POST['user'])){
?>
<form method="post" action="">
<input name="user" type="text"/>
<input name="password" type="password"/>
<input name="login" type="submit"/>
</form>
<?PHP
}else{
if(isValid($_POST['user'],$_POST['password'])){
$_SESSION['username']=$_POST['user'];
$_SESSION['isLogged'] =1;
header("Location: dashboard.php");
}else{
echo "incorrect !";
}
?>
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.
Hello i am having problems holding sessions from page to page, code worked on my previous servers running php5 but not on my recent server, i am wondering whether its a bug?
<?php
session_start();
$_SESSION['session'] = $_POST['session'];
header("location: www.mysite.com/page1.php");
?>
<?php
session_start();
echo "Good morning" . $_SESSION['session']; //returns empty session always.
?>
ANy ideas? session is held on first page but not on the second.
In case you missed it, make sure you do a session_start() at every page you're using the $_SESSION variable.
You should check your php.ini file and see what's going on.
Make sure session.use_cookies = 1 and session.save_handler = files.
Use this test page to see whether it's a general PHP problem or just your code.
<?php
session_start();
if(isset($_SESSION)){
echo "Session variable exists<br/>";
if(!isset($_SESSION['test'])){
$_SESSION['test'] = "Success!";
echo "Variable has been set, refresh the page and see if stored it properly.";
}else{
echo $_SESSION['test'];
}
}else{
echo "No session variable has been created.";
}
?>
If that worked, then it's got to do with your code.
If you're setting your session variable to $_POST['session'] am I to assume you submitted a form with an input with the name session?
This setup should work.
index.php
<form action='page0.php' method='POST'>
<input type='hidden' name='session' value='SPAAAAACE' />
<input type='submit' />
</form>
Page0.php
<?php
session_start();
$_SESSION['session'] = $_POST['session'];
header("location: www.mysite.com/page1.php");
?>
Page1.php
<?php
session_start();
echo "Good morning" . $_SESSION['session'];
?>
For completeness and debugging purposes
In case you are using cookie-less sessions, you have to manually add the SID (session id) to the header redirect like this
header("location: www.mysite.com/page.php?".htmlspecialchars(SID));
If the problem still persists, it could be a permission issue.
Maybe you're not allowed to read the session file stored on the server?
Update: OP commented that it was a permission issue and the problem is now resolved
Turn on error reporting temperately with:
error_reporting(E_ALL) This may spit out an error related to your problem. Most likely an undefined index session notice.
You should always have a check in place on Super Globals.
<?php
session_start();
$_SESSION['session'] = (isset($_POST['session']))?$_POST['session']:null;
header("Location: www.mysite.com/page1.php");
die;
?>
Your code seems correct though I'm pretty sure $_POST['session'] is empty.
You should try this :
<?php
session_start();
$_SESSION['session'] = 'John Doe';
header("location: www.mysite.com/page1.php");
?>
<?php
session_start();
echo "Good morning" . $_SESSION['session']; //returns empty session always.
?>
To see if this works or not. I guess it will.
IF not, take a look at your cookies, maybe they are disabled.
Then, if it works, I probably because $_POST['session'] is null or empty, are you sure you posted something like <input type="text" name="session" /> ?
You need to pass the session id with the redirect.
Also make sure you use session_start() at the top of EVERY page that needs a session
First try using
<?php session_start();
instead of
<?php
session_start();
If the problem still exists, then open your script in Netbeans editor and see whether any unexpected characters found at very beginning of the the script.
In addition, please make sure that $_POST['session'] has a value to assign in $_SESSION['session'].
You will have to call
session_start();
on the first line of every page you want to retain the session in
I'm having a strange issue with sessions in PHP. Basically, when a user submits a contact form, the processing script sets a session on completion ( $_SESSION['action']='sent'; ). The user is then sent back to the page they sent the form from and a message is displayed using the following code:
$action = $_SESSION['action'];
if ( $action == 'sent' )
{
echo '<p>Thank you for contacting us, we will be in touch with you ASAP.</p>';
unset($_SESSION['action']);
}
The session is unset so if they refresh the page or navigate away and come back the message won't be displaying any more.
Basically the problem is that when the session is unset it seems to unset it from the very beginning of the script so that the message doesn't display. The if statement is obviously running as the session is being unset, but the message isn't displaying.
I've used this exact same script many times before and it works absolutely perfectly on other sites (on the same server, with all the same settings).
Any help/advice would be appreciated!
Are you initialized a session?
session_start(); before output something in browser?
Try to do a session_destroy(); instead of unset($_SESSION);
Could you give us the part where you start the session and where you set the "action" to "sent"?
Hi Tom are you making sure the script that start the session is in the same directory - eg are the commands accessing the same session
- could be on under one is under https, and one is under http
OR if One is under /, another is under /dir1, and /dir1 was run first . The cookie created by the session is for /dir1 and deeper, so the other script can't read it; it sees no session so it starts a new one.
I'm not brill at this sessions stuff but it might be worth a check. - Dad
The code you have is correct. And since the session is being unset, we know that the statements in the if block are being executed. May be the output is actually being displayed by echo, but is just not shown by the browser (this can happen if your css code is configured so). So, just check the source of the output page and check if the source contains the out put message.
In other way, you can put a javascript alert box in your echo and see if it displays an alert box.
echo "<script type='text/javascript'> alert('Hi'); </script>";
This should override any hiding css code.
Old thread, but I'll add that I would prefer isset() in this situation:
<?php
session_start();
if(isset($_SESSION['sent'])){
echo "Successfully submitted form!";
$_SESSION = array();
session_regenerate_id();
session_unset();
session_destroy();
exit;
}
if(isset($_POST['submit'])){
//validate input & process form
$_SESSION['sent'] = 1;
header("location:form.php"); // name of this file
exit;
}
echo "Enter your email<br />
<form action='' method='post'>
<input type='text' name='email' />
<input type='submit' name='submit' />
</form>";
exit;
?>