I am using html and javascript for client, php for server. Each user, after signing up, will have a userID generated by server, and stored in database.
In server I am using setcookie so that user don't have to log in every time he goes to another page.
My first question is, should I just store the userID in the user's cookie for validation? How secure is that?
My second question is how do I check for cookie every time a user open a page. Do I make a 'invisible' ajax call (sending its cookie by using getCookie("userID") in javascript) to server every time user open a page?
Ever since I finished school, I never know if I am doing things the right way, or if my codes are crap. How do you guys determine if your code is the 'right' way to do it, or is it just base purely on experience?
No, it would not be secure at all - cookies can be set and modified by the user.
If you're using PHP (I think you are as there's a tag "PHP"), you should use SESSIONS.
Check the documentation:
http://www.php.net/manual/en/book.session.php
Quick example:
<?php
session_start();
var_dump($_SESSION['user_id']);
$_SESSION['user_id'] = 123;
On first request it would print something like null, on other request - 123. It works by generating random value and setting to cookie, that is not easy to guess, then stores all session data to files or other storage by that generated key.
Related
I need to store data in a session and make it available for other users.
I thought about to store that data in an Session, generate a random Link, which user 1 can send to user 2. The Session should expire after 3 Month.
The session name is the random code I generate which is simluar to the code I send with POST to receive it on the Secretlink with $_GET.
Is this working in general or am I on the wrong track?
Can I store a Session even when the user 1 left the website or will the session be terminated?
I also need to set the session via jQuery, but I couldn't find anything about expiration time of a session.
I already did it with a cookie, but of course that's not working with user 2.
Sessions are actually files, stored on the server. PHP sets a cookie with the session id, named PHPSESSID. You can also use the PHPSESSID GET parameter, but you would have to change that in the server's PHP settings. Using the GET parameter, you could pass that link to another visitor to let him use the session. You would also have to extend the session expiration time.
However, I wouldn't recommend sharing sessions with GET parameters. It could be a security risk when you are storing personal data in those sessions. I recommend that you write a small script that stores data in a database and that can be accessed (for reading and writing) by requesting an url or any url with a special GET or POST parameter.
One last thing, sessions are never accessible from jQuery directly. You would have to write a small script that requests data on your server via AJAX.
1 year ago, I've made a PHP social network which works pretty well. Via browser, once the user logs in, i use the $_SESSION variable to store credentials and remember the user through all pages. Everything works well.
Now i'm trying to build the app version of the website, using Phonegap and jQuery Mobile. At first glance i tried to use the same approach: to manage user login i implemented a simple form with Email and Password, which sends an ajax request to a "check_login.php" file.
If email and pw are correct, i "login the user", which simply means i store everything in the session variable, as i always did.
What i noticed, which is driving me crazy, is that using this approach data are not being stored into the $_SESSION variable. Using my app, each time I send an AJAX request to the server, the $_SESSION variable is gone and it looks like login data are not stored. Like i never logged in. (Of course, i've put session_start() at the top of each page). Moreover, each time i send an AJAX request to the server, the session_id() changes.
Is that normal? Does this mean with Phonegap i can't rely on $_SESSION variable or I am just missing something?
If yes, why?
The largest problem with this approach is that a pure PHP session will expire in a short period of time (the default is 24 minutes). So you're making inconsistently spaced calls that could cross that boundary of time.
There's a couple of ways around this
First would be to change your session handler to save the sessions in something more long term (like a database). More overhead but you could retain the session ID for a longer period and store it within your localStorage.
The second would be to directly tokenize your logins. So a user logs in and gets some random hash back (i.e. md5(uniqid(mt_rand(), true))) that serves as their token. Then your app contacts a special page and passes that token and you can check it in your token table. This would afford you more control over your logins. You could expire the tokens at will and would not be at the same mercies of PHP sessions.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Cookie VS Session
PHP: How do Cookies and Sessions work?
I'm trying to learn PHP. I have a project website where numbers are constantly being generated, and changed and stored in javascript variables. There is very little php involved except in storing these variables to a database when the user hits the "store to database" button. Today I was using the site, navigated to another website and went back and all my data was gone as i had not stored it to the database first. I would like to save that data so it repopulates if I leave the page. what would be the best method of doing this? php sessions, cookies, or javascript cookies? please advise, thanks in advance!
php sessions, cookies, or javascript cookies?
There is either a session or cookie so there are two things not three.
Now a session is also a cookie but is saved on server unlike simple JS cookie which is saved in user's machine.
I would like to save that data so it repopulates if I leave the page
If it is sensitive information, always use database to store it and if it is not sensitive data:
Use cookies or localStorage but it can be deleted by user
Use session which can't be deleted by a user but will expire based on php.ini settings
On the other hand, to save it permanently, use the database instead.
PHP and Javascript cookies are the same thing, they are just data stored client side, php and javascript are the technology used to store them, nothing more.
Since PHP cookies can only be set before an output is sent to the page, it seems Javascript cookies would be best.
You would use cookies instead of a session because you mention you would leave the page, in which case the session would terminate and you would lose your data.
Use sessions when you want to temporarly store some data (for one session - until user closes his browser).
Use cookies when you want to store data for longer (like login cereditials).
You should also have on your mind that user can change value of stored cookies, but can't for sessions, since sessions are stored on a server, but cookies are stored on client's computer.
I believe cookies is the answer you need, as php session is only stored between page loads, so you are effectively sending the data back to the server already (not what you want) and as far as I know, javascript cookies are just cookies set with javascript.
So to clarify, I think you should set a cookie (by using javascript) every time some data is created - which will store locally on the browser (still fairly volatile) until the user presses the save button, where it will be sent back to the server.
PHP cookies if you want to store long term, but don't care whether the user changes the values or not.
PHP sessions if you don't want the user to have the ability to change values but don't need long term storage (this sounds like what you want)
Both session and cookies if you want to store long term and don't want users to have access to changing the values. You would want to use a database with this so that you could check the cookie information with the database to see if it was correct, and then store the data in sessions for easy access.
This is how many sites 'remember users'.. They store a cookie with the username and password, and then when the user visits the site (if a session is not set) they check the username and password with the database and then if it is correct, they create a session specific to that user.
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
I'm making a forum for learning mostly but hopefully it will have a couple of users some day.
What im wondering is should you use sessions or cookies for user authentication?
A cookie is a short piece of arbitrary data that the server sends through a header; the client stores it locally and sends it back on the next request. This mechanism can be used to maintain state from one request to the next even though HTTP itself is a stateless protocol. Cookies have two disadvantages: They offer only very limited amount of space (4 kB), and because they are sent back and forth in plain, a malicious client can fiddle with the contents before sending it back to the server, effectively making cookie data untrusted.
A session is a file on the server, identified by a unique ID which is sent back and forth between client and server so that the server can identify the client. The most popular way of sending the session ID is through the cookie mechanism, but it is also possible to pass the session ID through the URL (this is why you often see links that contain the URL parameter 'phpsessid'). This solves the two problems with cookies mentioned above: A file on the server can be as large as required, and the client cannot access the data other than through your own scripts.
Authentication is typically solved using cookie-based sessions; once authenticated, a new session is created, and the user ID is stored in it, and when logging out, the session is cleared and a new session ID is generated. Alternatively, you could store username and password in the session, and check them on every request.
Use a session.
A session is identified by a cookie, true, but not the same as storing user auth info in the client cookie, which is bad for security. A session cookie stores a guid or a hash in the cookie, then identifies the session (either database or file system based, depending on your server's php settings) based on that.
I recommend you store the primary key from your user table, not any other info, then look up the user info every time - this allows you to change their validation status, or security level on the fly while they are logged in; otherwise they will have to log out and back in before your administrative changes take effect for them - IE. you can't boot them.
Also, don't store the username/password, because that requires a less efficient query than by the indexed primary key (even if they are indexed as well).
They are essentially the same, working hand-in-hand. When you create a session..say through PHP, a cookie is created to store the session id too. On the other hand, you would create another cookie if you want to implement a "Remember Me" option to prevent your users from logging in every time.
I'm not a PHP expert, but Session and Cookie are related. In other programming languages you have the option of creating "Cookie based session" or "Cookie-less session". I'm not sure about PHP though so maybe you are referring to different concepts.
I feel using session is much more safe and easy then using cookies. The reasons are as follows:
1) In cookie we can only store a single piece of information, whereas in a session we can store as many information as we want.
2) Being stored on hard disk of user, cookies can be played with. Being a person interested in hacking, I have done that and gathered useful information about the user. Sessions cannot be used for such a thing.
If its a small amount of data (just one variable), I would use a cookie. Here is the code...
setcookie("cookie name", "cookie value or variable name", time+ 3600, "\");
this code sets a cookie that is readable for any of your webpages. It also will delete its self in one hour.
You can also see if the cookie exists like this (to see if it has deleted its self).
if (isset($_COOKIE['cookiename']))
{
}
to collect a value from a cookie...
$value = $_COOKIE['cookiename']; //makes a variable for this cookie for your program