I have two forms. One is for the registration form and the other is the login form. My login form is already working but when I try to access the registration from in localhost instead of prompting me the login page, I can still be able to access the registration from which is wrong.
It should prompt me to the login form first because I am not yet logged in.
How would I do it?
Here's one approach.
I assume you have a library script that's loaded by your pages. Somewhere in there, define a session on every page:
session_start();
Then, when the user logs in with valid credentials, save some information into the global $_SESSION array. For example, if you had a login($username, $password) function that returned a row from your user database (or a user object):
if ($user = login($username, $password)) {
$_SESSION['user'] = $user->id;
// Probably store some other stuff about the user here too
}
To check if you're logged in:
if (!empty($_SESSION['user'])) { /* .. */ }
And to log out:
$_SESSION['user'] = false;
Or
unset($_SESSION['user']);
Obviously this is simplistic, and you'll probably want to look at things like:
Changing the default session ID with the session_id($id) function
Creating an object or a series of functions around your session
Auto-populating and refreshing information about your user
But this is a start.
Also see:
The PHP session functions: http://us3.php.net/manual/en/ref.session.php
How this is done in a real life PHP social networking engine: https://github.com/Elgg/Elgg/blob/master/engine/lib/sessions.php
Take a look at PHP Sessions. You can use $_SESSION to store peristent information about user, whether they have already registered or not.
You should check which form was submitted in your php code using the name attribute of your forms. So if your login form has the name="loginForm" and registration has name="regisForm"then in your code do this
if(isset($_REQUEST['loginForm'])) {
...//do something with loginForm
}
else if(isset($_REQUEST['regisForm'])) {
..//do something with regisForm
}
You have to store the information on whether the user is signed in or not in a way that enables you to check for it on every subsequent page. Usually this is done using the so called sessions - details would be too much for this anwer here - I strongly suggest you learn about sessions in PHP. Another (simpler) way would be to store the fact that the user is signed in in a cookie, but this is usually not as good as it can be tampered easily. But using cookies might be the quick and dirty approach until you learn the details of session variables. In any way you have to learn more for accomplishing your goal here. You might find that the easy looking tasks can become quite complex when you start implementing them. The easier things are for your users, the more work the coder has to do. But that's also what makes coding interesting in the long run... Don't give up.
Related
I have a website where members have to login but I noticed after logging out they can simply enter any page url in browser and go back in without using the login form, how do I prevent this.
What I mean is I believe there is a way for me to check if the session is valid on all pages. Even non users can put the url in their browsers and enter without logging in.
Use the SESSION variable in PHP.
session_start();
$_SESSION['login'] = true;
This basically creates a SESSION variable called 'login' which can be used to verify whether a user is logged in.
Now, all you have to do is check the variable like this :
if($_SESSION['login'] == true){
/*GOTO USER PAGE*/
}else{
/*REDIRECT SOMEWHERE ELSE */
}
To create a logout button, to ensure users can't copy-paste the URL again and enter,
session_destroy();
will work just fine.
What you need to do is create a proper login system using something like a session. There are countless tutorials you'll find about this by googling "php login tutorial with session". Here is one of those results.
At the heart of all of these are PHP Sessions, which allow you to store information for a specific client throughout their browser session. To understand sessions in php, here's a basic tutorial
Let me know if these make sense or if you have any questions :)
Sorry for the newbie question! I'm making a small website that allows users to create their own accounts. It's not a banking system, and it's unlikely that someone would want to hack it. That said, I am trying to make it reasonably secure, as there are plenty of bored script kiddies out there.
Could someone describe a basic workflow for a user logging in and having a cookie set that will keep them logged in for 30 days?
At the moment I have the following:
Validate and sanitize inputted data.
Check supplied credentials against bcrypt hashed password in DB.
If correct then call "Login" function.
Login function:
a. Delete any session data from DB with userID (table with two columns: SessionString and UserID).
b. Add new session data to DB (newy random generated string and UserID).
c. Write random generated string and UserID to cookie.
d. Set $_SESSION("UserID") with $userID.
But although the two cookies are being created and written to, the $_SESSION("UserID") remains blank... I'm guessing because I can't write to $_SESSION any time I like?
And even once that's fixed, how do I use the data stored in the cookie to log a user in? I'm guessing I don't want to go to the DB on every page load. And it will still require me to create a database object to see if the credentials in the cookie are ok. Is this the right way to this?
Once again, apologies for the newbie question!
UPDATE:
Yes, I do understand the difference between $_SESSION variables and a cookies. I also have session_start() at the top of every page (right after <php with no blank lines). $_SESSION("UserID") just remains blank.
Here's the code from the top of the page:
<?php
session_start();
if(!isset($_SESSION['initiated'])) {
session_regenerate_id();
$_SESSION['initiated'] = true;
}
Thanks for the help.
First off, there is an important difference between a session and a cookie. When you use the $_SESSION[".."] you are creating a session (which lives on the server, compared to a cookie which lives on the client), even though the browser uses a cookie to keep track of the session id. To create a cookie you would use the setcookie() method.
That said, I would recommend you to read through this article which is a step-by-step guide on how to create a secure login script, with persistence using a cookie for a "Remember me"-feature. Describe how to do it in detail would be to extensive for an SO answer im afraid.
Side note:
To be able to write to the session, you might have to call session_start(); prior to getting or setting a session variable using $_SESSION[".."].
Did you write a custom session handler that has your session-files stored in the db? I guess you don't.
If you want to use $_SESSION you have to also do session_start(). When using PHP sessions the cookie to identify the user will be set for you. You will also get session files created in your /tmp directory. That's the location your variables and anything you assign to $_SESSION will be stored.
Unless you define a custom session handler, that will manage the location of the session files, you won't need to query your database. Just save the users credentials in $_SESSION.
See this Tutorial on how to use PHP sessions.
PS: You access arrays like this: $_SESSION["UserID"], not with ().
you might want want to look at this article in which i have already discussed about various types of session hijacking and how you could avoid it.
session security in php
Is there an option to set Duplicate user login in PHP? When im logged in one tab and if i open another tab. It must display duplicate user or user already logged in. Kindly send me suggestions or the ways in which i can handle Duplicate user Login.
Well, store the user info in _SESSION vars
And at the top of page
<?php
check_login();
And on check_login() function
function check_login()
{
session_start();
if(isset($_SESSION['is_logged']))
{
echo "user is already logged";
}
else
{
echo "user is not logged";
}
}
I am sure if you put this on top of every page, you will be able to do it so.
This will work for same browser. But for different browser, it will not work.
I'm afraid you can't do it since (as far as i see) e.g. Google's dupe login can't do the trick too. When you switch account within Google they actually switch the user but you can't login with two different identities in the same browser. Maybe somehow you can trick the browser but probably that will come with a security issue.
Btw, have you tried tricking cookies to do it?
Update:
build a database backend for manage (dupe) logins
use cookies beside sessions (store a unique value to differentiate each login)
on every page request compare your cookie > session > database to decide who requested the page
Note: this is a rough outline for the task, you'll need to take care of unique session_id's, etc.
Hey, I'm trying to get my php website to basically "log out" (session_destroy()) when the same user logs in somewhere else. Is there a way to do this? To remotely destroy a specific session?
Thank guys!
Scott
It's certainly possible, using session_id. When the user logs in somewhere else, you can do this step before starting a new session for the new login:
// The hard part: find out what $old_session_id is
session_id($old_session_id);
session_start();
session_destroy();
// Now proceed to create a new session for the new login
This will destroy the old session on the server side, so when the other computer accesses your application again it will try to access a non-existent session and a new one will be created for it (in which the user is not logged in anymore).
The hard part is finding out what is the ID of the "old" session. There's no one-size-fits-all way of doing that; you need to have some mechanism in place to be able to tell that the session with id XXX belongs to the same user who is logging in now. If you are using database sessions this should be easy enough.
It's not necessary to create your own session handlers.
Simply store the session ID with the username in the database upon login.
Every time the user fetches a page, compare that user's session ID with the stored session ID.
If the session IDs don't match, it means the user has logged in somewhere else, and you should self-destruct.
I can imagine you could do this by using your own session handling. If you store you sessions in database, you could delete them from other app, if you needed to. You would identify the user by user name or something like that.
The best way is to create your own session handlers, if you have full control over how the sessions are stored/retrieved and controlled it's not that difficult to force a log out and it offers you a whole broad range of useful features. If you've got time.
But, for a quicker solution: Store the session ID from PHP in the database with the user, and check this in your isLoggedIn function - or whatever you use. If it doesn't match, force the logout.
Another thing you could do besides Jon's answer (which is great, +1), is initially check where the user came from (referer) and destroy the session if the user comes from another webpage than your own.
$referer = $_SERVER['HTTP_REFERER'];
$referer = parse_url($referer);
if($referer['host'] != "yoursite.com" || $referer['host'] != "www.yoursite.com") {
session_destroy();
}
source
I would like to suggest that what we can do is, get the time and add some addtional value (like manu1234567) and store in database when user log's in .
add that in session also.
now on each page compare both , and if that is equal then proceed , else forward to another page or give some msg .
now other part
when ever another user will login with same username and password, database will update
and for first person there will be error msg "some one logged in from some where else."
Note : time will always different . so there will be very very less chances that two values will be same.
I've scrapped all the tutorials that have never worked for one reason or another, and decided to roll out my own registration/login feature on my own, and to my surprise it actually works!
But what I don't get is how the logic behind keeping somebody logged in works! Like, once they've logged in, do I just $_POST their data to whatever other page they visit and once they're on the new page $_REQUEST that post data from the URL and display a message like: "yeah, you're still logged in"?
I'm a bit confused atm, so I hope this question doesn't confuse you too.
Let us have we have pages like login.php after_login_page1.php after_login_page2.php
You can follow these simple steps
Set $_SESSION['id'] = $userid //userid from db in login.php
always have session_start() in the successive pages like after_login_page1.php, after_login_page2.php
Check if(! isset($_SESSION['id'])){
header("Location: login.php");
}
at the logout.php page give $_SESSION['id']=''; and do a session_destroy()
The easiest imo is to use a session.
Basically this is PHP automatically setting a cookie (or adding a piece to the url, depending your configuration) on the user system and automatically loading it on each pageview. You can then add data to the session and as long as the cookie didn't expire (or was deleted) and/or you don't destroy the session, you will have that data at your disposal on each pageview the user does.
Take a look here for a small intro to sessions: http://www.htmlgoodies.com/beyond/php/article.php/3472581/PHP-Tutorial-Sessions.htm
Once they have logged in you generally have two options. Store their details or an authentication token (something that will help the PHP on the server know who is who) in a session or store it in a cookie. Both have their perks, but you will need to choose the one that works for you.
If you store data in a session, the user cannot access what you have stored, only your code can. This is helpful if you want to store say, their id or username. You can trust that it would always be their id and username, because they cannot modify it.
With cookies, the user can access and modify them because they are stored on their local machines. Because of this, you need to be a bit more sneaky and hash the users details, then verify who it is with some server-side logic. It's a little more complex.
A session implementation might look like this:
session_start(); //Make sure you call this at the top of EVERY page
if($passwordsMatch){
$_SESSION['user'] = $_POST['username'];
}
//Now we have access to $_SESSION['user'] on every page.
On another unrelated page:
session_start();
print "Welcome, ".$_SESSION['user'];
Easiest way is to "keep users logged in" is to use PHP sessions. When you run session_start();, PHP sets cookie with SESSION_ID in users browser so it can identify this user. After that, you can set any data in $_SESSION array which will be saved in session between page requests.