How to add security while using GET and POST method? - php

I developed a small application Contact Manager and while updating the contacts, the contact id is being sent using GET method. But a user can change the Id and edit any contact, how can i add security to it?
<td>
Update
</td>
http://localhost/contmanager/home.php?action=update&contactid=1
If i change the id to some other number, another contact will show up.

You can't control what the client asks the server to do.
If you want to add restrictions on who can modify particular contacts then you need to Authenticate (username + password, client SSL cert, OpenID, etc) users and then check if they are Authorized (this will depend on the business logic you decide on) to modify the entry in question.

As Quentin pointed out, your logic is going wrong here, data like these should be stored inside sessions and shouldn't be passed using $_GET or $_POST, unless and until required, if you still need to pass for some reason, than you can read my answer ahead for a solution.
Store the user id in a session, so when the user updates, just compare the session id and $_GET id, if it matches, update the entry else throw an error.
When the user logs in
$_SESSION['user_id'] = $db_data['col_name'];
Now, before the entry is updated...
if(!empty($_GET['user_id'])) {
//First validate, you can check whether the id is only numeric, is valid db entry etc
$user_id = $_GET['user_id']; //Store the id in a variable
} else {
//Invalid
}
if($_SESSION['user_id'] == $user_id) { //Compare the ids
//Process
} else {
//Not Valid
}
Note: Make sure you use session_start() at the very top of the page,
before you start writing anything.

You need to use session and to store the data inside like this:
<?php
session_start();
$_SESSION['contact_id']=$contact->contact_id;
<td>Update</td>
?>
use it like this:
http://localhost/contmanager/home.php?action=update
and when you need to use contact_id(after the GET) :
session_start();
if(isset($_SESSION['contact_id']) && !empty($_SESSION['contact_id'])){
$contact_id=$_SESSION['contact_id'];
}
A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.
PHP Session Variables
When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state.
A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database.
Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.

Related

How can I make a username change and also update the session?

I've got my login sorted, which sets an array of around 15-20 different database items, the user can change some of these and admins can change all of them.
Obviously for a general user, it would be silly having to reset the entire session when they change something on their account. For example their name. My code DOES work with the database, it is inputting the name after the user changes it.
$username=$this->session->userdata("logged_in");
if(strlen($name)>=1){
$databasename = $row->firstname;
if($name != $databasename){
$input_array['first']= $name;
$this->session->unset_userdata($username['name']);
$this->session->set_userdata($username['name'],$name);
}
}
To add some background to my code, the input array is defined outside of the if statements, and is the added to if the name is NOT equal to the database name and if the name has been changed.
All it does, is save the data to the database, and does not change the session variables. Ideally they need to change, they do change if i log off then back on, however this is impractical.
If i understood your correctly, you want to make sure that the user always get's displayed the up to date data, even when the admin did some changes to it, e.g. to his username. If so, then there are 3 ways to do this.
The first one
Only store the userid in the session as well as any data that does not need to be up to date. You then select the needed data, e.g. the username from the database when a request has been made. That will ensure that everything is always up to date.
The second one
Store the userĀ“s session id in the database when it will be created. To get the session id use the session_id function. You then use the session_id function again, but this time with the id from the sesison you want to destroy as the first parameter. e.g
session_id($old_session_id);
session_start();
session_destroy();
This will crerate an empty session (and therefore kill the existing one), and destroy is right after that. and then the user has to log in again when he visits your site the next time.
The third one
Let PHP store the sessions in the database, that way you can modify them or simple remove them and force the user to relog. I would however be careful with this solution at it might be an overkill, the first one tho is a very common one, the second one is also a great way.
Explanation
The reason why it does not work otherwise, is the fact that the session does still contain the old data which has been set previously. If the user updates his username himself then you can also set it at the session, but if the admin does it (or any other one except for the user himself), the username (just as a example, it can of course be anything else) in the session won't change.
Maybe because you get variable $logged_in and try to put back another variable with name "username". If i right understand your problem you need save logged_in:
$username['name'] = $name;
$this->session->unset_userdata('logged_in');
$this->session->set_userdata('logged_in',$username);

PHP $_SESSION for multiple users at once

I'm wondering about how the $_SESSION array works. If I have a lot of users using my site do I need to set a subarray for each user? For instance right now I have
$_SESSION['userid'] = $userid;
$_SESSION['sessionid'] = $sessionid;
$_SESSION['ipaddress'] = $ipaddress;
but in order to cope with more users do I need to make a multidimensional array?
$_SESSION[$userid]['sessionid'] = $sessionid;
$_SESSION[$userid]['ipaddress'] = $ipaddress;
Is the $_SESSION global handled per client or just overall? Will having $_SESSION['userid'] set on login kick the previous user out and instate the latest logged in user?
No. There is a seperate $_SESSION created for each user. This is all done by the server, you don't have to worry about it. When writing your code, treat the $_SESSION as if there was only one user on the site.
Edit: Actually, on thinking about it, it is a very good question to ask. It is good to ask these sorts of questions, it means you are seriously thinking about how your code truly works. Keep asking these things, and keep testing. I have a feeling that one day you will be writing some amazing code.
So on that note, here is some info from the apache site:
What is a session?
At the core of the session interface is a table of key and value pairs that are made accessible across browser requests. These pairs can be set to any valid string, as needed by the application making use of the session.
Keeping sessions on the server
Apache can be configured to keep track of per user sessions stored on a particular server or group of servers. This functionality is similar to the sessions available in typical application servers.
If configured, sessions are tracked through the use of a session ID that is stored inside a cookie, or extracted from the parameters embedded within the URL query string, as found in a typical GET request.
And from the PHP docs on Sessions:
Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site.
A visitor accessing your web site is assigned a unique id, the so-called session id. This is either stored in a cookie on the user side or is propagated in the URL.
The session support allows you to store data between requests in the $_SESSION superglobal array. When a visitor accesses your site, PHP will check automatically (if session.auto_start is set to 1) or on your request (explicitly through session_start() or implicitly through session_register()) whether a specific session id has been sent with the request. If this is the case, the prior saved environment is recreated.
well after searching alot and working on session i found my own way. i hope it works great for everyone here
this is the query for login page for my users:
here i am storing email as session from input field after matching data from mysql
<?php
include_once("dbcon.php");
$que=mysqli_query($con,"select * from agents where companyemail='$email' AND
pass='$password' AND post != 'Owner'");
$record = mysqli_fetch_assoc($que);
$_SESSION[$email]=$email;
header("Location:/dashboard/woresk/Dashboard_For_Agents/light/index.php?
&loginid=$agentid");
?>
and then in the dashboard for users there is a logout option where i used this method
<?php
session_start();
include_once("dbcon.php");
$sid=$_GET['loginid'];
$que=mysqli_query($con,"select * from agents where id='$sid'");
$recorde = mysqli_fetch_assoc($que);
$email=$recorde['companyemail'];
unset($_SESSION[$email]);
header('location:/dashboard/woresk/index.php');
?>
and to avoid users to enter dashbboard if they are not login or thier session is not set following code works great for me
<?php
session_start();
include_once("dbcon.php");
$sid=$_GET['loginid'];
$que=mysqli_query($con,"select * from agents where id='$sid'");
$recorde = mysqli_fetch_assoc($que);
$email=$recorde['companyemail'];
if(isset($_SESSION[$email]) && isset($_SESSION['alllogout'])){
}
else if(!isset($_SESSION[$email])){
echo
"<script>
window.location.href='/dashboard/woresk/index.php'
</script>";
}
else if (!isset($_SESSION['alllogout'])){
echo
"<script>
window.location.href='/dashboard/woresk/index.php'
</script>";
}
?>
i hope this works for others too. if any question please let me know

Is it safe to check user login Session with GET variable?

lets say i have a session called $_SESSION['id_user']
and it stores session of the user id. Lets say that the user profile is www.example.com/profile.php?id=123
if I want to check if that profile is the user and if i do something like
if(isset($_SESSION['id_user']))
{
if($_SESSION['id_user']==$_GET['id']){print something since this is the users own profile}else{print nothing}
}
Is the above code good enought? or is their any security problem? or is it wise to compare GET variable with SESSION variable? its not printing anything that will give user identity away or anything I just want to show a (edit profile button) for the user that is visiting his own profile.
Yes, it is safe - the session is stored on the server and a user cannot change the session data manually. Unless their session is hijacked, then only they will be able to see their own profile.
For piece of mind (and to prevent possible SQL injections I'd just cast the two variables as (int)s before using them (also cuts down on having to write $_SESSION['id_user'] multiple times. I would also use === which checks the variables without any type conversions.
As mentioned in the comments by Thomas, if you've got the users ID in the session already, then unless you need to (differentiate between profiles), just use that and don't send the user ID over GET.

List Php Sessions for a user and remotely log that session out

In php i create a session with the id of the user. So i do
$_SESSION['id'] = $id;
So say for user 3. Is there a way i could list all sessions for user 3? Also remotely kill the session(logging them out). I want to give users something like gmail where they can view sessions for their account. I also want to allow them to remotely log out sessions out for their user account. Most of my site is done but this is something i am very unsure of. I am not even sure if Php has support for this. I want to do this to beef up security. So say someone went to school or somewhere and forgot to logout they could just remotely do it from another computer with their account. Also i plan to store their IP in the session, also last time. So it can also list IP address, Last time. Have any clues on how to do this? Has anything like this been done with php sessions?
You can set up a session-handler, who writes the session data into a database. Then you can analyze that table to find other session with the same id.
http://php.net/manual/en/function.session-set-save-handler.php
Thats the session-way. But I would suggest to implement this on your own, because the session-data is serialized, so you must read all sessions, deserialize it and search for the one key "id".
You can create a table with (lets say) session-id, user-id, ip and time. Every time a user logs in you put a record into that table and on every request you should update the time (its something like "last seen").
If you want to know if there are other users with one id, simply select over the user-id column. The "legal" user can be identified by the session-id.
Next, if you want "remote logout" a session you can add a column "force_logout" or something. Now on the next request (of the "illegal" user) you read this flag and kill the session, if its set.
You can keep session_id (get it by session_id() function while user login) in the data base and for remote session termination (by REST for example) by user id use next function:
public function drop_session($session_id) {
if ($session_id) {
session_id($session_id);
//session_start();
session_destroy();
session_commit();
}
}

Are sessions modifiable by the client/user?

In my PHP Web-App I use sessions to store the user's data. For exmaple, if a user logs in, then an instance of the User class is generated and stored in a Session.
I have access levels associated with each user to determine their privileges.
Store the user in a session by:
$_SESSION['currentUser'] = new User($_POST['username']);
For example:
if($_SESSION['currentUser'] -> getAccessLevel() == 1)
{
//allow administration functions
}
where getAccessLevel() is simply a get method in the User class that returns the _accesslevel member variable.
Is this secure? Or can the client somehow modify their access level through session manipulation of some sort?
No, the client cannot modify their access level. The only thing stored on the client is the session key which is either propagated via cookie or GET parameter. The session key ties to a corresponding session record which is a file stored on the server side (usually in a temp directory) which contains the 'punch'.
What you don't want, is for a session key to get leaked to a third party:
A leaked session id enables the third
party to access all resources which
are associated with a specific id.
Take a look at this: http://www.php.net/manual/en/session.security.php
The session information is stored on the server and the user only has access to a key. In practice I have used something of this sort, with extra steps. After validating the user details and storing the User object, I would have a query that is run when viewing any of your protected pages to validate what is in the session is okay with what they're trying to view.
In the top of your page.php
if(!validUser($user)){
// Relocate the user
}
where
validUser(User $user)
{
// Some query to verify the information in the session
// Return the results of verification
}
I thought the only way for the user to manipulate something like that was if it was stored in a cookie on the users computer.
Is the getaccesslevel stored to a cookie or is it called from the server only after checking the login cookie and not stored on the users computer?
I would assume that if it is called on the server only after the user is logged in then they would not be able to easily manipulate that other than through other means of security holes.
Just my guess tho, im not that great with security myself yet. I will keep an eye on this to see what others have to say and maybe I can learn something.

Categories