PHP - How To Prevent Session Spoofing And Session Hijacking?
I'm making a simple login system with MySQL and PHP (very simple, I'm just starting with PHP). The MySQL portion is done, but I need to ensure only people who are logged in can see certain content.
To check if people are logged in, my website checks that they have the $_SESSION['user'] variable set. If it is set, then it lets them continue through the website, if not, it tells them to login. Is that enough security, or can people simply inject a session cookie into their browser to spoof that they are logged in? My idea was to generate a session key cookie when they login (just a random string of letters and numbers) and store that in the database, then on every page, check to make sure their session key is the same thing that's in the database. Is this necessary? It seems expensive. Similar TutorialsI have my script protected against all types of sql injection, XSS injection, cookies and bots. But now i want to know whats the best way of preventing session hijacking? I know nothing can be 100% secured but i want to know how to prevent it And u know it: prevention is better than cure! which is the best place to put this code : Code: [Select] if(isset($_SESSION['last_ip'])===false){ $_SESSION['last_ip']=$_SERVER['REMOTE_ADDR']; } if($_SESSION['last_ip']!==$_SERVER['REMOTE_ADDR']){ session_unset(); session_destroy(); } like this : Code: [Select] class session { public $user_on=false; public $user_id; function __construct(){ //make sure that javascript can not access session variable ini_set('session.cookie_httponly',true); session_start(); //set the last ip the user has logged on with if(isset($_SESSION['last_ip'])===false){ $_SESSION['last_ip']=$_SERVER['REMOTE_ADDR']; } if($_SESSION['last_ip']!==$_SERVER['REMOTE_ADDR']){ session_unset(); session_destroy(); } $this->check_login(); } private function check_login(){ if(isset($_SESSION['user_id'])){ global $user; $this->user_id=$_SESSION['user_id']; $this->user_on=true; $user->find_by_id($this->user_id); } else { unset($this->user_id); $this->user_on=false; } } } OR : Code: [Select] function __construct(){ //make sure that javascript can not access session variable ini_set('session.cookie_httponly',true); session_start(); $this->check_login(); } private function check_login(){ if(isset($_SESSION['user_id'])){ global $user; [b]//set the last ip the user has logged on with if(isset($_SESSION['last_ip'])===false){ $_SESSION['last_ip']=$_SERVER['REMOTE_ADDR']; } if($_SESSION['last_ip']!==$_SERVER['REMOTE_ADDR']){ session_unset(); session_destroy(); }[/b] elseif($_SESSION['last_ip']===$_SERVER['REMOTE_ADDR']){ $this->user_id=$_SESSION['user_id']; $this->user_on=true; $user->find_by_id($this->user_id); } } else { unset($this->user_id); $this->user_on=false; } } } Hello everyone, I am trying to use only cookies so that session fixation is not possible. Unfortunately I can still log in when I disable cookies in Internet Explorer. Am I doing something wrong? Or do I misunderstand the concept? This is my code: Code: [Select] <?php class Session{ private $username; public function createSession($username){ $this->username = $username; ini_set("session.use_only_cookies", 1); session_start(); $_SESSION['username'] = $this->username; return $this->username; } } ?> I was asked to make new thread for this, so how do I use a session or something to restrict access to a page.....like if accounttype=Admin, stay here, all others go away......do you need to see code, or can you just give me an example....... in this page http://maximaart.com/newscp/ i have this problem Code: [Select] Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/maximasy/public_html/newscp/index.php:1) in /home/maximasy/public_html/newscp/index.php on line 2 my source code is <?php session_start(); include_once("config.php"); include_once("functions.php"); $errorMessage = ''; if (isset($_POST['txtUserId']) && isset($_POST['txtPassword'])) { if ($_POST['txtUserId'] === "$user" && $_POST['txtPassword'] === "$pass") { // the user id and password match, $_SESSION['basic_is_logged_in'] = true; require("main.php"); exit;?> I am trying to create an index page which contains registration and login field the problem that i get is on successful login a warning is displayed session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\xampp\htdocs\Eventz.com\index.php:116) in C:\xampp\htdocs\Eventz.com\index.php on line 235 This is the login part of my index.php this tag is inside an html table below the login form I also have a registration form and its php code above the login form Code: [Select] <?php if (isset($_REQUEST['pass'])) { $id=$_POST['id']; $pass=$_POST['pass']; $conn =mysql_connect("localhost","root",""); if (!$conn) { die('Could not connect: ' . mysql_error()); } /* checking connection....success! */ $e=mysql_select_db('test', $conn); if(!$e) { die(''.mysql_error()); } else { echo 'database selected successfully'; } if (isset($_REQUEST['id']) || (isset($_REQUEST['pass']))) { if($_REQUEST['id'] == "" || $_REQUEST['pass']=="") { echo "login fields cannot be empty"; } else { $sql=mysql_query("Select email,password from login where email='$id' AND password='$pass'"); $count=mysql_num_rows($sql); if($count==1) /* $count checks if username and password are in same row */ { session_start(); $_SESSION['id']=$id; echo "</br>Login Successful</br>"; } else { echo "</br>invalid</br>"; echo "please try to login again</br>"; } } } } ?> Any help or suggestion would be appreciated I am having trouble resolving an error. Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/s519970/public_html/header.php:27) in /home/s519970/public_html/admin/login.php on line 2 What I can gather is I can't use "header (Location: 'admin.php')" after i've used session_start(). I have tried to replace the header (Location: 'admin.php') with this: echo "<script>document.location.href='admin.php'</script>"; echo "<script>'Content-type: application/octet-stream'</script>"; I've been trying to read up on solutions but haven't been able to get it sorted. If anyone can offer some advice that would be greatly appreciated as im new to php. Code: [Select] <?php session_start(); if(isset($_SESSION['user'])) echo "<script>document.location.href='admin.php'</script>"; echo "<script>'Content-type: application/octet-stream'</script>"; ?> <div id="loginform"> <form action="dologin.php" method="post"> <table> <tr> <td><span>Username:</span></td> <td><input type="text" name="username" /></td> </tr> <tr> <td><span>Password:</span></td> <td><input type="password" name="password" /></td> </tr> <tr> <td colspan="2" align="right"><input type="submit" name="login" value="Login" /></td> </tr> </table> </form> </div> I have tried using require_once('yourpage.php'); before my <head></head> tags in the header document where I've specified the html information but this doesn't seem to work. I've been advised to use ob_start("ob_gzhandler"); but I am not sure how to implement this. Any advice is greatly appreciated! hi everyone. i'm wondering what the best way is to create a session variable and pass it to an iframe. i need to do something along these lines, but it doesn't seem to pass the ID. Any hints on how i should accomplish this? Code: [Select] session_start(); $_SESSION['ID']=$_GET['ID']; // id from previous page $ID=session_id(); <iframe src="iframepage.php?ID=<?php echo $ID; ?>" style="width:680px; height:200px;" noresize="noresize" frameborder="0" border="0" scrolling="Yes" allowtransparency="true" /> </iframe> Evening! I've been iffing and ahhing over this and well im not too sure, hence the post. Code: [Select] // Redirects if there is no session id selected and echos the error on the previous page if(!isset($_GET['get']) || ($_GET['getget'])){ header("Location: #.php?error"); } So it should simply check if get is set if it isnt then see if getget is set? If not redirect and show the error. Now ive tried it and even when get/getget is set it still redirects, probably something silly. Care to share anyone? Harry. Just curious how other people feel about this. I am working on an application where a lot of info is pulled from MySQL and needed on multiple pages.
Would it make more sense to...
1. Pull all data ONCE and store it in SESSION variables to use on other pages
2. Pull the data from the database on each new page that needs it
I assume the preferred method is #1, but maybe there is some downside to using SESSION variables "too much"?
Side question that's kind of related: As far as URLs, is it preferable to have data stored in them (i.e. domain.com/somepage.php?somedata=something&otherdata=thisdata) or use SESSION variables to store that data so the URLs can stay general/clean (i.e. domain.com/somepage.php)?
Both are probably loaded questions but any possible insight would be appreciated.
Thanks!
Greg
Edited by galvin, 04 November 2014 - 10:30 AM. what is the problem here? $sql="INSERT INTO comment (linkid, text, anvid) VALUES ('$_POST[link]','$_POST[comment]','$_SESSION['user'];')"; hello all, What I want to do is, make the session ID clickable in a url here Code: [Select] Login Successful <a href="user.php">Conitnue</a> so when a user logs in, his ID gets in the link of Continue so he can only see his information so for example, if his id is 10, then the url would be ....user.php?id=10 Pls tell me what is wrong? <?PHP include("dba.php"); function hvataj ($trazi, $id) { $upit = mysql_query ('select * from administrator where member_id = '.$id.''); return ( $row = mysql_fetch_assoc ($upit) ) ? $row[$trazi] : mysql_error (); } ?> I have parse error here on this line when I want to echo it: <?PHP echo "<img src='images/korisnik_slike/".hvataj('slika',$_SESSION['member_id']."' />"; ?> Hello everyone I have the following code $num = 1; $query = mysql_query("SELECT * FROM people"); while($row = mysql_fetch_array($query)) { $nums = $num++; $_SESSION['equal'.$nums.''] = $row['name']; $_SESSION['total'.$nums.''] = $row['age']; } which basically returns me SESSION names by increasing by 1, so it could produce the following session names Code: [Select] equal1 total1 equal2 total2 equal3 total3 equal4 total4 instead of setting those as sessions, I simply want to set them as vars, so instead of $_SESSION['equal'.$nums.''] = $row['name']; $_SESSION['total'.$nums.''] = $row['age']; it would look like $equal.$nums = $row['name']; $total.$nums = $row['age']; I have tried $equal.$nums = $row['name']; $total.$nums = $row['age']; but it doesn't seem to work any ideas? thanks Hello I keep having this issue with sessions. I have an login feature on my website that uses sessions. When i do like this: 1. Login 2. close browser 3. open browser again 4. try to log in It fails, actually nothing happens, so I manually need to go to logout.php to reset and then I can log in again. Why is this happening and how do i solve it? I am building an app (PHP and MySQL)and I had been using a lot of GET calls to get info from URLs, but the more I thought about it, the more I didn't like the possibility of people being able to mess with the URLs. So I am in the process of changing everything to use SESSION variables to store data across pages, rather than GET. The way I see it, SESSION variables are completely behind the scenes so they seem to be the better option. Am I right, or is GET better than SESSION for some reason? Hi guys help please Code: [Select] foreach($_SESSION['cart'] as $id => $value){ } is this valid? im getting error Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\shopping cart\new_cart.php on line 48 Many thanks giving me Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in /home/enriquec/public_html/admincenter.php on line 6 this is my code Code: [Select] <?php require "header.php";?> <?php if ($_SESSION['username']) echo "Welcome, "."$_SESSION['username']."; else die("You must be logged in!"); ?> <?php require "footer.php":?> Why is my SESSION not getting set in the code below?! Code: [Select] <?php // Initialize a session. session_start(); // Initialize Logged-In Status. $_SESSION['loggedIn'] = FALSE; // Display Logged-In Status. echo '<p>$_SESSION[\'loggedIn\'] = ' . $_SESSION['loggedIn'] . '</p>'; exit(); When I run this I get... $_SESSION['loggedIn'] = Debbie |