PHP - Prevent Session Fixation
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; } } ?> Similar TutorialsI'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. I 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! 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 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! 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 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. Hello Guys, Iam making a new ad serving script. In that site every publisher can register & they will get a url to serve ads. When a user click on that url the publisher will get earnings. But my problem is someone using something like this <iframe src="http://my-site.com/adserve.php" width = "100" height = "100"></iframe> & it will helps to get earnings without clicking on that url. I want to prevent this type of cheating & how it can be possible ?? I hope a expert will replay for me. As the title says, I would like to know how exactly CSRF can be 100% (or close to it) prevented.
One of the most recommended solutions is to create a token and insert it into a hidden field, but I've tested it on another domain and you can just do a cURL request and retrieve the token then make another request with it included. Proof:
<?php $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "URL"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 10); $response = curl_exec($ch); curl_close($ch); $exploded = explode('type="hidden" name="token" value="', $response); $token = substr($exploded[1], 0, 64); echo $token; // ebd9ab96d40bdb21bbaa2e1a18d657be2e413105ae86ecc14def6137f38a1571 ?>I would hate to include captcha on all my forms, so how exactly does one prevent CSRF? Is this a correct approach to prevent email injection? $to: me@mydomain.com, myPartner@mydomain.com, $emailer; //then the rest of the stuff. $emailCheck = $_POST["emailer"]; if (eregi("(\r|\n)", $emailCheck)) { die("Why ?? "); } mail($to, $subject, "", $headers); Hi is there any way we can prevent suppose <textarea></textarea> when page reload it refresh and set default text i wanted to know is there any way to prevent certain things not to get refreshed is there any method in php which prevent to reload this ! <?php echo "<textarea > Enter your favorite quote!</textarea> \n" ; Code: [Select] if (isset($_GET['edit']) && $_GET['edit'] == 'textupdate'){ } <a href= \"{$_SERVER['PHP_SELF']}?page=1&edit=textupdate \" >Click</a>?> Based on the comments on my previous question, took some tutorials on how to avoid injections on query. Does the code below prevents against it in any way.? Secondly, can you recommend a good article that writes well in how to secure input data by users. Please be kind with your comments.😉😉. Thankks in advance.
The code works fine. <?php include 'db.php'; error_reporting(E_ALL | E_WARNING | E_NOTICE); ini_set('display_errors', TRUE);  if(isset($_POST['submit']))  {     $username = $_POST['username']; $password =  ($_POST['password']); $sql = "SELECT * FROM customer WHERE username = ?"; $stmt = $connection->prepare($sql); $stmt->bind_param('s', $username); $stmt->execute(); $result = $stmt->get_result(); $count =  $result->num_rows;   if($count == 1)              { while ($row = $result->fetch_assoc())  {   if ($row['status'] == 'blocked')  {  echo'your account is suspended'   session_destroy();   exit();  }  else if($row['status'] == 'active') { if($username !== $row['username'])  { echo '<script>swal.fire("ERROR!!", " Username is not correct. Check Again", "error");</script>'; } if($password !== $row['password']) {  echo'<script>swal.fire("ERROR!!!", "Your Password is Incorrect. Check Again.", "error");</script>';     } if($username == $row['username'] && $password == $row['password']) { header('Location:cpanel/'); else { } }//if count }//while loop }//submit ?>  I am loading a link with ajax. When the link pops on the screen and I click it, I get redirected to my 404 page and my lightbox doesn't load. If the link pops in and I refresh my browser, then I click the link my lightbox will show up. How can I do a prevent default on the <a href> in pure JS? No frameworks please. Will this prevent a SQL injection? I am guessing the answer is no because it is too simple. // retrieve form data ========================================== $ama = $_POST['ama']; // Check for alphanumeric characters ===================================== $string = "$ama"; $new_string = preg_replace("/[^a-zA-Z0-9\s]/", "", $string); // echo $new_string; // Send query =========================================================== $query = "SELECT * FROM members WHERE ama='$new_string'"; if (!mysql_query($query)){ die('Error :' .mysql_error()); } How can I prevent the less than and greater than signs in the username field, and message on the post? As well as slashes. / \. Code: [Select] <form method="post" action="" id="reply"> <script type="text/javascript"> function hi(id){ var val = id.options[id.selectedIndex].value; var text = id.options[id.selectedIndex].text; if (val.length != 0){document.getElementById('user').value = text;hide('passrow');} else { document.getElementById('user').value = ''; document.getElementById('passrow').style.cssText = ''; } } </script> <div id="userpass" style="background: #000;"> <table style="border: 2px solid #252564; background: #1F1F5D;" width="100%" cellpadding="0" class="quick_userpass"> <tr> <td background="/images/bg3.jpg" height="26px"><font face=arial size=2 color="white"> <b>Your Name or Nickname</b></td> </tr> <tr> <td><input size=50 name="user" id="user" value="" style="margin-left: 10px;"></td> </tr> <tr><td background="/images/bg3.jpg" height=26px></td></tr> </table> <div id="passrow" style=""> <p> <table width=100% cellpadding=0 class="quick_userpass" style="border: 2px solid #252564; background: #1F1F5D;"> <tr><td background="/images/bg3.jpg" height=26px style=""><font face=arial size=2 color="white"> <b>Password (optional)</b></td></tr> <tr><td style=""><input size=50 name="pass" id="pass" type="password" style="margin-left: 10px;" value=""></td></tr> <tr><td background="/images/bg3.jpg" height=26px></td></tr> </table> </p> </div> <p> <table width=100% cellspacing=0 cellpadding=4 class="quick_userpass" style="border: 2px solid #252564; background: #1F1F5D;"> <tr bgcolor="#121236"><td><font face=arial size=2 color="white"><b>Enter your message here</b></font></td></tr> <tr><td><center><textarea id="quickreply" name="message" rows=10 cols=50 wrap="VIRTUAL" ></textarea></center></td></tr> </table> <div id="preview" style="display: none;"></div> </p> <br /> <center> <font face=arial size=2>When you're happy with your message, click:</font> <div id="javano"><input type="submit" value=" Post Message "></div> </center> <input type="hidden" name="tid" value="<?php echo $_GET["tid"];?>" /> </div> </form> That is the code I'm using for User/Pass/message fields. $_POST['user_name'] = "CLUEL3SS"; $_POST['user_pass'] = "test123"; $_POST['confirm_pass'] = "test123"; $_POST['user_email'] = "user@email.com"; $_POST['confirm_pass'] = 'user@email.com'; function testFunc($inputVars){ foreach($inputVars as $key=>$value){ $escapeData[$key] = mysql_real_escape_string($value); } return $escapeData; } var_dump(testFunc($_POST)); I'm trying to make a user system for my site and I want to make sure its secure enough to void off injection attackers. Any useful advice and and suggestions would be greatly appreciated! Thanks! Hello all, A simple question: I have a HTML application from which a php script is executed. 'GET' method is used and no form is submitted. I was wondering if there is a way to prevent users from run this php script directly in the browser. Thank you all for your suggestions, Mamer I have my template files and some functions in my server which are available for direct reach. like ; my "index.php" file includes "loginpage.php" form which is ok when I enter www.site.com/index.php but also when I enter to www.site.com/loginpage.php it works and shows me just login page. So this is what I dont want. How can I prevent to reach the files directly like this, I want them to work just for other pages of my website, not for directly seeing. By the way can this problem also be solved by hosting settings or mod_rewrite ? |