PHP - Session Security Isn't Forwarding To Login
I'm trying to create a simple session on a form page that determines if you've signed in. If you haven't, it kicks you to the login page. But for some reason, what I have isn't doing that. When I open the page, it loads, but only prints the url on a blank page, instead of actually going to the url.
Code: [Select] <html> <title>form</title> <link rel="stylesheet" type="text/css" href="style.css"> <body> <?php session_start(); if(isset($_SESSION['id']) && is_numeric($_SESSION['id'])) { if (isset($_POST['submitted'])) { $errors = array(); if (empty($_POST['scientific_name'])) { $errors[] = 'you forgot to enter the scientific name'; } else { $sn = trim($_POST['scientific_name']); } if (empty($_POST['common_name_english'])) { $errors[] = 'you forgot to enter the common name'; } else { $cne = trim($_POST['common_name_english']); } $description4 = trim($_POST['common_names_spanish']); $description5 = trim($_POST['common_names_french']); $description6 = etc. etc. if (empty($errors)) { require_once ('3_z_mysq1_c0nn3ct.php'); $query = "INSERT INTO plantae (scientific_name, common_name_english, etc.) VALUES ('$sn', '$cne', '$description4', '$description5', '$description6', '$description7', etc.)"; $result = @mysql_query ($query); if ($result) { if(isset($_POST['scientific_name'])) { $plant_id=mysql_insert_id(); } exit(); } else { echo 'system error. No plant added'; echo '<p>' . mysql_error() . '<br><br>query:' . $query . '</p>'; exit(); } mysql_close(); } else { echo 'error. the following error occured <br>'; foreach ($errors as $msg) { echo " - $msg<br>\n"; } } // end of if } // end of main submit conditional echo '<form action="insertaplant1.php" method="post"><fieldset><legend><b>Enter your new plant here</b></legend> form fields here. </form>'; } else { $url = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']); if((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) { $url = substr($url, 0, -1); } $url .= '/login.php'; echo $url; exit(); } ?> Similar TutorialsHi This is the senario: User logs in, if successful connection details for his database are stored in a session variables which are used to access information. Are there any precautions I need to make sure the data in the sessions are safe? Thanks Hi all ! Hi, I have just started learning about sessions to use with a login system with SQL Now I was wondering if my method is secure? When login in before setting the $_SESSION variables I use the session_regenerate_id() function. All passwords and ids are stored as SHA-256 hashes in the MySql DB. I use the mysql_escape_string() and htmlspecialchars() functions to sanitize the input values of all DB query's and SESSION variables. Also the login page can only have 3 wrong attempts before the user is locked out. with a captcha after the first attempt. Once the user logs in on each 'protected' page it checks the variables in the $_SESSION variable against the DB value on each page if they do not match then it brings the user to login page. Also on start of each page: if (isset($_REQUEST['_SESSION'])) {die('No Hacking');} Just wondering am I missing something? Thanks, mme What is the best method to prevent session hijacking / fixation and all the nasty bugs that come with using session_start(); I am looking at implementing session_start() on a member site, to handle logins if registered. How would I protect the session information? I have a business social network site on hosting server. I am wondering if sessions are enough secure. ini_set('session.use_only_cookies', 1); //this prevent Session Fixation? session_start(); if($_SESSION['loggedIn'] && $_SESSION['userIP']==$_SERVER["REMOTE_ADDR"]) // extra security //user is logged in, assign all data to this profile from session else //user is not logged in, no data are assigned Would you consider that as enough secure? Hi, I'd like to know the security of assuming session variables and using them for secure membership systems. Could a malicious user not create a session, then change the session username to another user and effectively login as that user? As I see it, no. Because session data is stored on the server and only a session id is stored on the client by way of a cookie. But what if we used cookies? What is the solution to this? Because I know I could easily change ANY variables within a cookie. I guess storing cookie data via db would help. But what is the best practice solution? I see a lot of code which simply checks for a cookie with the variable 'logged_in' to true. It then manages the user by username or userid which are stored within the cookie but which can be changed with ease by a malicious user. I have issues with a user being logged in and staying logged in, When logging in I create these $_SESSION variables Array ( [usr_login] => username [usr_fname] => first [usr_lname] => last [usr_email] => email [ses_usrid] => 1 [loggdin] => Yes [loginremember] => ) And after login it looks great till I refresh the page or go anywhere else on the site. All variables above are gone. Consequently, this works with no issues on the prod server, just not on my machine. Code I've been playing with since it started, specifically the setting of the cookie. (this code runs before anything else) // ================================================================= // Sesssion start // ================================================================= session_set_cookie_params( 0, "/; SameSite=Strict", ".killgorack.com", true, true ); session_start(); // ================================================================= // Security stuff // ================================================================= header("strict-transport-security: max-age=31536000"); header('X-Frame-Options: sameorigin'); header("X-XSS-Protection: 1; mode=block"); header('X-Content-Type-Options: nosniff'); header("Content-Security-Policy: default-src BLA BLA BLA "); header("Feature-Policy: vibrate 'none'"); header("Referrer-Policy: no-referrer"); header("Access-Control-Allow-Origin: https://www.MYWEBSITE.com/"); header("Expect-CT: max-age=86400, enforce"); header_remove("X-Powered-By"); // ================================================================= Any ideas? Edited May 19, 2019 by KillGorackHi guys,
I would like to have a security measure in place to prevent unauthorized access to my site without a valid log on.
At the moment, it would let anyone in without destroying the session and redirecting to index page.
What would i "use" that's created in the session? what's the "best" practice
My understanding is that the session variable is stored in the browser, after a successful log in, that session variable is like baton or a key that's "passed" onto the next page.
- if someone tried to bypass the log on with the session then access is denied or redirected away.
So on my index page to start i have:
<?php session_start(); /* clear all session variable */ $_SESSION = array(); /* set a session variable for later use */ $_SESSION['what_page'] = "admin00"; ?>What do i need to have to use the session against unauthorized access? my guess is: if(!isset($_SESSION['what_page']) || $_SESSION['what_page'] != "index.php") { $_SESSION = array(); session_destroy(); header("Location: index.php"); exit(); }So to me that means; - if 'what_page' is not set from the index page, don't go any further, re-direct (back to index) If i remove this and use a known username and password, i am able to log into the correct page, but this session validation is the bit that's not working please could you help? Can someone please help to find the most important login precautions in terms of security. For example, I'think the most important is: 1. string escaping, prevent SQL injections 2. 3. ... I know It's hard to find and consider all of them, that's why I'd like to have a list of the most important. i just discovered a hole in my scripts relating to access . 1. have a simple login form 2. based on the type of user , he is directed to a page for his options . 3. I now realise that altho each page therefter checks for sessions of the user , he can easily change the url to that of another user and there is no way to prevent it. 4. How can i make sure that each time a page is accessed it is only by the user whom it is meant for. Relevant code snippets below . Thanks ! Swati login.php --------- <?php //error_reporting(E_ERROR | E_PARSE | E_CORE_ERROR); //Process this if statement only if form was submitted if($_POST['submit']){ session_start(); $username=$_POST['username']; $password=$_POST['password']; include ("link.php"); // contains db info //Test for login success $sql = "SELECT * FROM Users WHERE Username='$username' AND Password = '$password'"; $result = mysql_query($sql); if ($myrow = mysql_fetch_assoc($result)){ // echo $sql; $login_success = 'Yes'; $userid = $myrow["Userid"]; $usertype = $myrow["UTID"]; $status = "On"; $url = $PHP_SELF."?".$_SERVER['QUERY_STRING'];; $logout = 'logout.php'; $_SESSION['id']=session_id(); $_SESSION['userid']=$userid; $_SESSION['usertype']=$usertype; $sql2= "insert into Log (Sessionid,Userid,IP,Date,File, Status) values('$_SESSION[id]','$userid','$ip','$tm', '$url', '$status')"; $result2 = mysql_query($sql2) or die ('no access to database: ' . mysql_error()); // echo mysql_error(); } } } ?> Each subsequent page has this header ============================== <? header("Cache-Control: public"); include ("log.php"); //db info for DB along with session start if(!isset($_SESSION['userid'])){ echo "<center><font face='Calibri' size='2' color=red>Sorry, Please login and use this page </font></center>"; exit;} ?> The url of each page : Code: [Select] www.abc.com/example/type1.php?Userid=USER1ID and such a user can easily change the url to Code: [Select] www.abc.com/example/type2.php?Userid=USER1ID and access all the options of type2.php I am a bit concerned about using this code here, is there anyway of better authenticating a user? Just concerned about the usual ones like session hijacking, not really SQL injection (as I have put mysql_real_escape_string function below), but also XSS attacks etc, how would I go about improving this script? <?php ini_set('display_errors', 0); require_once 'header.html'; require_once 'db.functions.php'; require_once 'config.php'; $message = 'To login please enter your user information below'; $database = dbConnect($host, $username, $password, $database); // should output 1 or nothing at all! if($database == true) { if(array_key_exists('submit',$_POST)) { if($_POST['username'] != '' && $_POST['password'] != '') { // carry on with logging in process: $username = mysql_real_escape_string($_POST['username']); $password = mysql_real_escape_string(sha1($_POST['password'])); $sql = "SELECT username, password FROM users WHERE username = '$username' AND password = '$password'"; $result = mysql_query($sql); if($result) { // query worked now try and log them in: $result = mysql_num_rows($result); if($result == 1) { // do a query to retrieve users information: $sql = "SELECT username, password FROM users WHERE username = '$username' AND password = '$password'"; $result = mysql_query($sql); $user = mysql_fetch_array($result); session_start(); $_SESSION['login'] = 1; $_SESSION['username'] = $user[0]; header("location: index.php"); } else { $message = 'You entered a wrong username or password please try again'; } } else { $message = 'Could not query database for some reason, please try again later'; } } else { // output an error message to the user: $message = 'You did not enter all the required fields to login, please retry'; } } } else { $message = 'Could not connect to database, please try again later'; } printf("<p>%s</p>",$message); echo <<<USER_LOGIN <form id="login" name="login" method="post" action="{$_SERVER['PHP_SELF']}"> <p><label for="username">Username: </label> <input type="text" id="username" name="username" value="{$username}" /> </p> <p><label for="password">Password: </label> <input type="password" id="password" name="password" value="" /> </p> <input type="submit" id="submit" name="submit" value="Login" /> </form> USER_LOGIN; require_once 'footer.html'; Works quite well to be honest, but just wondered if there's anything I can do to improve my example blogs security, any suggestions are helpful, Jez.
I am trying to install a script on my OpenSuse Webserver, and I managed to resolve most of the errors except of one: The value for session.save_path (/tmp) is not writable for the web server. Make sure that PHP can actually save session variables.
That seems to be the problem.
session.save_path: writeable You need set permission for your var directory.
well - i guess that the default ownership may be incorrect on the session folder: Example; php on some Linux-Server defaults to apache user. If using nginx or other need to switch the folder ownership. Also as a note you have to change the user/group setting in www.conf.
chown -R root:nginx /var/lib/php/7.0/ sed -i 's/apache/nginx/g' /etc/php-fpm-7.0.d/www.conf service php-fpm-7.0 restart
But wait: what about the security - is it save to make the session.save_path writeable!? my server-admin says that this is a big big hole and makes the server unsecure. love to hear from you yours dil_bert by the way: years ago i have had this issue on the server. but the question is - is this a securitiy risk!? I need to know this. Look forward to hear from you Edited March 21, 2020 by dil_bertI have a login system that uses a flat file database. The flat file is in a directory outside the public_html. My questions; 1- Is is still possible to hack into that file? Currently I do not encrypt the passwords as I have been told that having the file outside the public_html makes the file unavailable to the public. This allows me the advantage of sending the Username and Password to the user in an email if they forget there password or username. Otherwise- I would have to set up a more complicated method to allow them to change their password to re-gain access to the site. I have an SSL on the site also so I am not worried about packet sniffing. Thanks If you are a PHP expert, then I really your help. I have a question regarding PHP sessions and their security. So here is my story ... I created a login script (login.php) for my website. When a user goes to the login.php page, they see a login form that they must fill with their username and password to login to the members' area and view their profile, etc. On that login page, when the user enters their username and password and then clicks the "Login" button, my script filters the data, sends MySQL query and checks if the login is valid. If the login is NOT valid, then they get a "Login Failed" message. If the login is valid, I register their username and the password in sessions and redirect them to the members.php page. Here is some of my code for my login.php page after mysql confirms the login is valid <?php $query = mysql_query('SELECT * FROM `users` WHERE username='$user' AND password='$pass'"); $numRows = mysql_num_rows($query); if ( $numRows ) { // login is valid $_SESSION['username'] = $user; $_SESSION['pass'] = $pass; // redirect user to members area header('Location: /members.php'); } else { // login is invalid echo "Login failed"; } ?> My question is ... is this login script secured? I mean, I am not generating any session id or any cookie. I am just storing the username and the password in two session variables and those are the things that i will use to display the user's profile, etc. Can attackers attack this script? Is this secured or is there any other way I can make it stronger? This should be really simple, but I just can't figure out why it isn't working. It's my first time using sessions, so I'm probably doing something silly. It's just a login to an admin page. It's for a photo gallery, that's why the database is called "photo". This is the login page: Code: [Select] <?php session_start(); if(isset($_POST['user']) && isset($_POST['password'])){ $user = $_POST['user']; $password = sha1($_POST['password']); $photo = new mysqli('localhost', 'user', 'password', 'photo'); $login = $photo->query("select user, sha1(password) from settings where user = '$user' and sha1(password) = '$password'"); if($login->num_rows > 0){ $_SESSION['login'] = 1; ?> <META HTTP-EQUIV="Refresh" Content="0; URL=admin.php"> <?php } else { $badlogin = 1; } } ?> <html> <head> <style> body {margin-top: 50px;} td {text-align: right;} input {width: 200px;} </style> </head> <body><center> <?php if(isset($badlogin)){ ?> <span style="color: red;">Oops! Wrong login.</span><br><br> <?php } ?> <table> <form action="admin.php" method="post"> <tr><td>User:</td><td><input type="text" name="user" /></td></tr> <tr><td>Password:</td><td><input type="password" name="password" /></td></tr> <tr><td></td><td><input type="submit" value="Login" /></td></tr> </form> </table> </center></body> </html> And this is the admin page: Code: [Select] <?php session_start(); if($_SESSION['login'] != 1){ ?> <META HTTP-EQUIV="Refresh" Content="0; URL=login.php"> <?php } else { ?> <html> <head> </head> <body> Admin stuff here. </body> </html> <?php } ?> Im trying to make sessions work with my script, its finding the user/pass in the database and redirects me to the homepage after but the parts that are supposed to show when the session is set are not showing. My code: <?php // Login Logic $username = ""; $err = ""; $err_style = ""; $err_style2= ""; //Checks if there is a login cookie if(isset($_SESSION['username'])) { //if there is, it logs you in and directes you to the members page $_SESSION['username'] = $username; $_SESSION['password'] = $password; //$username = $_COOKIE['user_id']; //$pass = $_COOKIE['pass_id']; $check = mysql_query("SELECT * FROM users WHERE username = '$username'")or die(mysql_error());$quer++; while($info = mysql_fetch_array( $check )) { if ($pass != $info['password']) { } else { header("Location: index.php"); } } } //if the login form is submitted if (isset($_POST['submit'])) { // if form has been submitted // SANITISE $username = sanitize($_POST['username']); $pass = sanitize($_POST['password']); $red = sanitize($_POST['red']); // makes sure they filled it in if(!$_POST['username']) { $err = 'You did not fill in a required section'; $err_style = "style='border: 1px solid #CC0000'"; $show_login = 1; } if(!$_POST['password']) { $err = 'You did not fill in a required section'; $err_style2 = "style='border: 1px solid #CC0000'"; $show_login = 1; } // checks it against the database if (!$err) { $check = mysql_query("SELECT * FROM users WHERE username = '".$username."'")or die(mysql_error());$quer++; //Gives error if user dosen't exist $check2 = mysql_num_rows($check); if ($check2 == 0) { $err = 'User not found - please try again!'; $err_style = "style='border: 1px solid #CC0000'"; $show_login = 1; } while($info = mysql_fetch_array( $check )) { $info['password'] = stripslashes($info['password']); $pass = $pass; //gives error if the password is wrong if ($pass != $info['password']) { $err = 'Incorrect password, please try again.'; $err_style2= "style='border: 1px solid #B02B2C;'"; $show_login = 1; } else { session_start(); $_SESSION['username'] = $username; $_SESSION['password'] = $password; // if login is ok then we add a cookie //$hour = time() + 3600; //setcookie("user_id", $username, $hour); //setcookie("pass_id", $pass, $hour); //then redirect them to the members area if (!$red) { header("Location: index.php"); } else { header("Location: $red.php"); } exit; } } } } ?> And: <?php session_start(); //checks cookies to make sure they are logged in if(isset($_SESSION['username'])) { $_SESSION['username'] = $username; $_SESSION['password'] = $password; //$username = $_COOKIE['user_id']; //$pass = $_COOKIE['pass_id']; $check = mysql_query("SELECT * FROM users WHERE username = '$username'")or die(mysql_error()); $quer++; while($info = mysql_fetch_array( $check )) { //if the cookie has the wrong password, they are taken to the login page if ($pass != $info['password']) { header("Location: login.php"); } //otherwise they are shown the admin area else { // Update some info session_start(); $_SESSION['username'] = $username; $_SESSION['password'] = $password; //setcookie ("user_id", $_COOKIE['user_id'], time() + 3600 ); //setcookie ("pass_id", $_COOKIE['pass_id'], time() + 3600 ); // Get some basic user details, so we can use these later! $uname = $info['username']; $uID = $info['user_id']; $email = $info['email']; $loggedin = 1; $admin_user = $info['admin']; } } } ?> Hi guys, I have a loggin page which works fine except it doesnt pass the session, could someone help me to see what mistake im making? once users login they will be diverted to another page where is their profile page, i have echoed the session in member page but it doesnt read it. i have attached both codes (member page and login page) below, thanks in advance for your help code is below: login page code: Code: [Select] <?php //connect to database include '../include/db.php'; //we start a session here to help us pass the user login variable to other pages of the webs application while user is logged in. session_start(); //php login // if post has been successfully sent, do the action below if ($_POST['login']){ // get data from form fields $email=strip_tags($_POST['email']); $password=strip_tags($_POST['password']); // check if email (username) and password have been inserted, if not show an error if($email == "" || $password == "") echo "Please enter your email address and postcode"; else { //check if email exists $checkemail=mysql_query("SELECT * FROM member WHERE EmailAddress='$email'"); //if exists we get the information from database if ($getrows=mysql_num_rows($checkemail)>=1){ while ($row=mysql_fetch_array($checkemail)) { $myemail=$row['EmailAddress']; $mypassword=$row['Password']; } //convert the password to md5 $pass=md5($password); //now we check if entered email and password match our database record if ($myemail==$email && $mypassword==$pass) { $_SESSION['emailaddress']=$myemail; //update the loggedin to 1 so we users go to next page, our website will compare if users is logged in or not $update=mysql_query("UPDATE member SET loggedin='1' WHERE EmailAddress='$email'"); //if details exist we get the users first name our database to pass this information along with our sessions $getuser=mysql_query ("SELECT * FROM member WHERE EmailAddress='$email'"); while($row=mysql_fetch_array($getuser)) { $firstname=$row['FirstName']; } echo "Welcome $firstname, <a href='profile.php'>Click here</a> to be directed to your profile"; } } else { echo "This user doesn't exists"; } } } ?> and this is the member page so far Code: [Select] <?php //connect to database include '../include/db.php'; //we start a session here to help us pass the user login variable to other pages of the webs application while user is logged in. session_start(); echo "Welcome ".$_SESSION['emailaddress'].""; ?> OK when i go to my website and login i stay login in intill i sign out but when im stilled loged in and click new tab and type my website i see the login table but im already loged in so i have to click on my logo to time to make the login table go away why if you need the login code i would be happy to give it to use I'm trying to implement sessions into my website. At the moment index.php contains a login form that posts to AccountManagement.php. AccountManagement.php then checks the database to see if they have entered a correct username/password combination. This all works fine, however I would like the site to remember that a user has logged in, and not tell them that they have entered an invalid password every time they come to this page by any means other than index.php's login form (e.g. a back button on a page that follows from AccountManagement). I have tried for days to get this to work using a for loop that checks if the session is started, but I can't seem to get the placement/syntax correct. Any help would be greatly appreciated. AccountManagement.php: Code: [Select] <?php include ("Includes/database.php"); include ("Includes/htmlheader.php"); dbconnect ("localhost", "xxxxx", "xxxxx", "xxxxx"); $query=sprintf("SELECT wowUsername, Password, UserID FROM Users WHERE (((wowUsername)=\"%s\") AND ((Password)=\"%s\"));", $_POST['Username'], $_POST['Password']); $result=mysql_query($query); if (!$result) { $message = 'Invalid query: ' . mysql_error() . "\n"; $message .= 'Whole query: ' . $query; die($message);} if (mysql_num_rows($result) !=1) { $errormessage= "Incorrect Username or Password, please try again."; include ("Includes/error.php"); } else { $row=mysql_fetch_assoc($result); $CustomerID = $row['UserID']; $query2=sprintf("SELECT CustomerID, FName FROM Customers WHERE CustomerID=$CustomerID"); $result2=mysql_query($query2); $row2=mysql_fetch_assoc($result2); $_SESSION['UserID']=$CustomerID; ?> <form action="index.php" id="home" name="home" style="width: 8em"></form> <h1> Account Management </h1> <p><h3 align="center">Welcome <?php echo $row2['FName'];?>, use the buttons below to manage your subscriptions.<h3><br /> <h2> <form action="Subscription.php" id="subs" name="subs"> <p> <input class="button5" name="Setup" type="submit" value="New Subscription" align="center" /></p> </form></h2> <form action="AccountUpdate.php" id="remove" name="remove" style="width: 8em"> <p> <input class="button5" name="NewDetails" type="submit" value="Update Details" /> </p></form> </p> <p> <form action="AccountCancel.php" id="remove" name="remove" style="width: 8em"> <input name="Logout3" type="submit" class="button5" value="Cancel Account" align="right" /> </form> </p> <p> <br /> <form action="index.php" id="remove" name="remove" style="width: 8em"> <input class="button5" name="Logout" type="submit" value="Log Out" /> </p> </p> <?php } ?> </div> </body> </html> </form> htmlheader.php: Code: [Select] <?php error_reporting(E_ERROR | E_WARNING | E_PARSE ); if(!isset($_SESSION)) { session_start(); $_SESSION['UserID']=0; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head><link rel="stylesheet" type="text/css" href="CSS/Styles.css"/> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Account Management</title> </head> <body> </form> <div id="content"> I don't know how to solve this error;
Parse error: syntax error, unexpected '$db' (T_VARIABLE)
code:
|