Better to get value from PHP variable or from cookie? - php

Assume that there is a PHP variable:
$variable = 'username';
cookie value = 'username'
Which one is better to access? get_cookie() or just use $variable?
I have a lot of code using get_cookie('cookie_name') (a CodeIgniter function) instead of using variables.
Will it increase performance if I change it to access $variable instead of cookie?

Cookies are passed from the user's browser to the server every page load, whether you use them or not.
There's really going to be very little performance difference.
What you may want to investigate is whether the data that is being stored in cookies (if you say it's a lot) should be there or not. Many people have cookies turned off, so you only want to store nonessential information (and information that doesn't have to be secure) in them.

Yes, it will, but the increase will be infinitesimally small.

Not only the $variable is somewhat faster, but also consider that a user may simply not accept cookies of any kind, so in general the $variable approach is much better.
I've been developing web apps for a couple of years and never had have to use cookies for anything. I know a lot of people would not agree with me on this, but I've been doing great for now without them.
Regards.

Related

Simple, quick encryption for setting cookies in PHP (Symfony2)

I'm setting some cookie values where the values are slightly sensitive, but nothing too serious.
Basically I would like to encrypt the value, but just a very quick, basic method.
I'm thinking base64 but that seems to return a really long string.
It just needs to be really quick and simple. Quick being low processing time.
Something like this is too much: http://crackstation.net/hashing-security.htm
I'm using Symfony2 but I don't think there's anything in there to help me (e.g. built-in cookie encryption).
The NelmioSecurityBundle can encrypt cookies. https://github.com/nelmio/NelmioSecurityBundle#encrypted-cookies
If the data you want to store in the cookie are sensitive, you should not store them in cookies in the first place.
I recommend using sessions. This way the data will not be transferred to the user but will still be accessible by your PHP scripts on the server.

why is ouputing html through php security risk using cookie?

im relatively new to php and was hoping you could help me understand why you should sanitize html when 'echo'ing , specially if data is from cookie..
i.e instead of
<h3>Hello, <?php echo $_COOKIE['user']; ?>!</h3>
you should do
<h3>Hello, <?php echo htmlspecialchars($_COOKIE['user']); ?>!</h3>
this is what i understand.
cookies are stored on client side, hence are a security risk since the data in them can be manipulated/changed by evil users (lol # evil) .
but since the cookie is stored on client side, it means a client can only change his own cookie, which means if he adds some kind of malicious code to $_COOKIE['user'] , when the cookie does run, the malicious code will only be shown to one user (who changed the cookie in the first place) and no one else!? so whats the problem?
You're assuming that the user changed his own cookie. Cookies can be changed by a third-party (Edit: Using additional software. Third-party websites cannot change the cookie directly). This would enable someone to inject malicious code into the user's browser, changing their user experience and potentially posing an additional security risk for your code.
Instead of just looking security aspect, there is a user experience aspect. The code you present is not really useful for security because risk are very poors in this case BUT if username can contains quote or < > signs, the user will not understand why its login is not displayed correctly.
Using such a code garanties that you will display correctly the username (and add extra security), no matter what kind of characters you allow during the registering process.
It's not really a risk in that situation - but this is rarely the actual situation. You should do it anyway.
Consistency - don't put it in now, and when you change it to something else, you might open up a security hole.
User experience - just because a cookie contains HTML doesn't mean it was an XSS injection attempt. What if somebody's name were &? I've been thinking of changing my name to &.
A user could inject a script into your page by changing the cookie. That fact alone should be enough to make you pause for thought.
Imagine you are creating a really by website where many data is stored in the user cookies.
Maybe some of the data in the cookie is used by your website to build an SQL statement, which could result in errors if the user or another website modifies your cookie in a bad way.
If you don't check the cookie data for injections, and even if, something could be written in the cookie that could harm your data consistence, e.g. a String in a varchar column where only hexadecimal numbers should be inserted.
The best way to deal with that problem is to either use Sessions where possible and only store the minimum amount of required data in the cookie as possible.
but since the cookie is stored on client side, it means a client can only change his own cookie, which means if he adds some kind of malicious code to $_COOKIE['user'] , when the cookie does run, the malicious code will only be shown to one user (who changed the cookie in the first place) and no one else!? so whats the problem?
Well, it depends on your implementation and what you use cookie's data for. An evil user could inject SQL through your cookies, change his permisions, impersonate another user, etc.
That's why you should always code thinking about the worst scenario

What steps should I take to securely manage and validate sessions on all my PHP pages?

I currently use PHP sessions (without database saving) to identify users on a small website. However, I would like to make it more secure by saving session data to a MySQL database along with using a cookie with PHP.
I'm thinking of having a PHP script which I will include on every page which will:
Try to validate a session based on a database entry
Create a session if needed
Set special session variables I might need
Is this the best way to go about things? Am I missing anything in my script?
Session automatically try to use cookies for session ID.
The common practice is to store everything important into $_SESSION on login (and check only for privileges change).
If you want to make it more secure you may store $_SERVER['REMOTE_ADDR'] and $_SERVER['USER_AGENT'] into session and check them on each request.
The last thing I can think of right now is checking 'life time of session' manually.
Anyway I think that using https instead of http would bring you much more safety than reinventing sessions.
Storing each request/session into DB would make sense only if you needed to have special handling for parallel request.
That's a pretty big question. You want to do a bit of research on learning the tools I'll provide you for the job. I cannot write every detail about them here, but I'll try to get you pointed in the right direction.
check the user cookie to see if they have your session id variable set. if it isn't, start them a new session and offer a login perhaps.
if they have the cookie, check if it is a valid session id
if it is, load that session.
You'll need tools like setcookie, session_id(), $_SESSION, $_COOKIE. Making a users table is a whole other topic really.
I work with MVC's all the time that do just exactly what your referring to. Its a real piece of junk setting it up that way, but it can be useful in certain situations.
But the most important thing you should know is that when combining the login to an active session, it won't really make it more secure unless you use 2 session identifiers. is this what you want to do?
This would also be useful if you wanted to track where users log-in from. Gook luck!

PHP Login System

I am creating a login system for a web application using PHP. My question is, is it safe to only store the user login information in the current session? For example, if a user named John logs in successfully to my site, can I just store $_SESSION['Username'] = 'John' and $_SESSION['LoggedIn'] = 1 then check that $_SESSION['LoggedIn'] is equal to 1 on each page to verify the user is actually logged in? Or is there a better way to do this? I am not aware of any problems this may cause off the top of my head, but I wanted to make sure I wasn't leaving a big hole in my site that would cause problems down the road.
Also, I am storing an md5 hash of the user's password + salt in the database, not their actual string password so that is one less thing to worry about.
Let me know if you need any more information or if this is not clear. Thanks!
That's a perfectly reasonable approach. Your visitors will never be able to edit the session data on your server (unless the server itself is insecure, in which case anything's fair game), so a LoggedIn=1 value in the session is perfectly safe.
However, do keep in mind the risk that one visitor hijacks the session of another (by stealing the session key). One way to help protect against this is to also store the visitor's IP address (from $_SERVER['REMOTE_ADDR']) in the session and then in later requests confirm that it hasn't changed.
There are a number of risks to consider:
Session hijacking: this is where someone steals the user's cookie and pretends to be them. Some will suggest IP filtering to counter this but that can have awkward side effects. People use Websites from mobile devices or on laptops that are used at work, home and at wifi hotspots and there are other cases where IP addresses can change. So my advice is only do this for highly sensitive Websites (eg online banking);
Your Site is Compromised: in this case the user will have access to your database anyway so there is no extra risk with storing authentication information in the session. They can just as easily change who they are by issuing UPDATE statements to your database;
A Co-Hosted Site is Compromised: if you use shared hosting, a completely unrelated site could put you at risk (with or without this scheme) because a bunch of sites are all running on the same Apache instance and can thus access each other's files (although it can be hard to figure out what site they belong to). So if a site you've never heard of is hacked it can impact your site;
A Co-Hosted Site is Malicious: similar to (3) except the threat is internal but is otherwise similar.
So I'd say it's fine (subject to (2)) but just be aware of the risks. Follow, at a minimum, these best practices:
Never store unencrypted passwords;
Use a strong hashing algorithm (SHA1 preferred or MD5 at least);
Make sure authentication cookies expire at some point. How long depends on your site. It could be a week or two or an hour or two of inactivity or both.
Consider SHA1 or an even stronger hash instead of MD5. You're salting it, though, that's good.
Back to your question: yes, that's fine. However, implement measures to make sure sessions are not hijacked. Wikipedia actually has a fairly good article on it.
In most of the systems I've written, I've included logic to verify the remote IP hasn't changed. You can store that in the session, too, since the session vars don't get passed to the user (only the session ID). If you really want to get creative, you can add other checks -- user-agent, and what not.
You also have to account for session attacks. Check referrers. If you have a disastrous operation, let's call it a POST to DeleteMyAccount, I can write a form submission plus javascript to hit DeleteMyAccount in a forum post on an unrelated site, counting on that session to be present in the user's information.
Sounds OK; you may want to think about setting an expiry time (so if someone walks away and leaves the browser open they're not in too much danger).
On the whole, you are definitely on the right track. I would recommend you use IDs for your users in the session rather than the username as IDs are a better unique reference inside your code.
Also, md5 is not considered strong enough for password hashing anymore: it's is too fast to hash and you don't want that in a check that an attacker will need to run over and over again (whilst a real user only needs to do it once). I wish I could find the reference, but leading edge wisdom is to do lots of rounds of a leading edge hashing algorithm, like sha512.
You can use COOKIE instead of SESSION variable. you may set COOKIE by following
setcookie('ID', $variable, time()+8*60*60);
You have to be aware about SQL Injection. When you Insert or Update your database where user textbox relates please be aware about SQL Injection. Insert / Update your values by htmlentities() function.

Is it possible to pass a variable to php without the users 'seeing it'?

I have a link on a page, and I would like to send a variable to a php file like this:
href = "php_file.php?qry=$query"
the $query variable contains a query which I would like to make to mysql, inside the php file.
My problem is, I don't want the users to 'see' what I am passing along. I would like to use $_POST but from what I know, that isn't possible.
Is there any other simple way?
Thanks
That is not possible. Even if you used POST it would be very insecure.
My suggestion would be to put the query in the $_SESSION variable and reference it back in php_file.php If you have multiple queries you could give them some kind of IDs and store the id=>query pair in session.
Quick example:
<?php
session_start();
$_SESSION["query1"] = "SOME QUERY";
$_SESSION["query2"] = "SOME OTHER QUERY";
?>
<a href='php_file.php?q=query1'>Execute first query</a>
<a href='php_file.php?q=query2'>Execute second query</a>
//in php_file.php
session_start();
$query = $_SESSION[$_GET["q"]];
Obviously this is very simplistic and you might want to add some more "security" to it (check for empty parameters etc.) but at least your query wouldn't be visible to the user.
Yes, as stated use a session: http://www.php.net/manual/en/book.session.php
Also, don't stick URI params into a SQL query: http://php.net/manual/en/security.database.sql-injection.php
You could use sessions, or a cookie. But if you're trying to have the client send you information that the client cannot know about, I think you need to rethink the problem.
I hope $query isn't SQL!
Aside from encryption (and even then) if there's data on the client side, there's no way to prevent the client from being able to determine it's value.
Definitely do not put queries on the client side! Store whatever it is in the $_SESSION. That way the actual data is on the server side. It's never sent to the client, so they will never see it.
You obviously want to prevent users from loading stuff like php_file.php?qry=DELETE+FROM+users in their browsers by hiding or obfuscating the SQL code. I suggest you reconsider the whole idea: you're asking to be hacked.
You can hardcode a list of operations in your server side code and just pass an identifier, e.g.:
php_file.php?qry=fetch-totals
and then
<?php
if( $_GET['qry']=='fetch-totals' ){
// ....
}
?>
Well if you don't want them to actually see the query parameters in a link try any URL shortening service (google will help). And when the user is redirected to you save this parameter to session and then do the redirect once again but without any query parameters. This solution will only work in case, once again, the link is just ugly and you don't want to leave it like that. As mynameiscoffey said savvy will still be able to figure it out.
As well as cookies, hidden forms, JavaScript and so on BTW.
You can, in theory, use encryption, and decrypt the value on the server. The overhead is huge, however. And a sophisticated enough user will get to it anyway. The plaintext of the value to be hidden will exist in a variable at some point; a debugger and a breakpoint at just the right time is all they need.
In this scheme, it does not matter how complex the encryption is. You don't have to go all the way with RSA or somesuch; something like XOR with key will suffice. You're protecting against casual snooping here, not against a determined attack.

Categories