PHP Session ending automatically - php

I do a lot of work using PHP frameworks but I am now building a simple login system from scratch and I am stumped. I am using PDO for my database queries. I have a simple login form which points to the same page using $_SERVER['PHP_SELF']. Then I have this code...
<?php
//LOG IN
if($_POST['login_submit']){
$username = $_POST['username'];
$password = $_POST['password'];
//Query
$database->query("SELECT * FROM users WHERE username = :username AND password = :password");
$database->bind(':username',$username);
$database->bind(':password',$password);
$rows = $database->resultset();
$count = count($rows);
if($count > 0){
session_start();
//Assign session variables
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
$_SESSION['logged_in'] = 1;
} else {
$login_msg[] = 'Sorry, that login does not work';
}
}
When I login, its fine. It starts the session. But as soon as I go to another page the session is broken. I suspect maybe cause the session_start() is in the if($_POST['login_submit']) condition. But I could sware Ive done it like this before. Any help would be awesome..thanks!

The first line of your code...
if($_POST['login_submit']){
Only, if you submit your login form, the session is started.
And, on all other pages, you have to call session_start() ...

Related

$_SESSION not working

So i am not sure what to do anymore.
I've been trying to create a register/login system for my website. After a lot of struggeling my register now works but i can't yet login to it. I am pretty sure it is a $_session related problem.
So I have two files, one called get_users.php (i know it's a bad name) and one called cart.php. Neither of them has whitespace at the start.
What am i actually trying to do? I am trying to get my session to show up on cart.php.
get_users.php:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$con = new mysqli("localhost","root","","ismsite");
$query = ("SELECT name, comment FROM comments ORDER BY id DESC");
$result = mysqli_query($con, $sql, MYSQLI_BOTH);
session_start();
$_SESSION["user_id"] = $row["user_id"];
header('Location: cart.php');
exit();
?>
and at the start of cart.php
<?php
session_start();
include 'config/config.php';
echo $_SESSION["user_id"];
?>
I really am at my wits end here. I've searched this site but i could not find a solution to my problem. Anyone who knows what the problem is?
Additional info:
-Latest php installed
-I am running it on a virtual webserver that runs the latest ubuntu client with LAMP stack installed.
-Database works just fine
Thanks in advance
EDIT:
I changed $row["user_id"]; to $result["user_id"];
But it still doesn't show up
Try this
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
//for hashing passwords
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($db,$username);
$password = mysqli_real_escape_string($db,$password);
$password = md5($password);
//Check username and password from database
$sql="SELECT userid FROM users WHERE username='$username' and password='$password'";
$result=mysqli_query($db,$sql)
or die("Error");
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
//If username and password exist in our database then create a session.
//Otherwise echo error.
if(mysqli_num_rows($result) == 1)
{
$_SESSION['username'] = $username; // Initializing Session
}else
{
$error = "Incorrect username or password.";
}
But you will have to tweak according to your table structure.
May be $_SESSION["user_id"] not set. You can test $_SESSION array by
print_r($_SESSION) or print_r($GLOBALS);

Wrong session value when reading

I have got this strange problem. I wanted to make a page which uses a Username to identify which content should be displayed. It seems to work fine, except for one thing. The wrong value is read from the session on one specific page. I have checked the session value in my browser, but there the value seems to be correct. I'll show you the code:
this is my login function, using php:
<?php
//CONNECT TO DATABASE
$db = mysqli_connect("localhost","root","MyPassword","MyDBName");
if($db->connect_errno){
die('connection error: ' . $db->connect_errno);
}
//CHECK IF LOGIN DATA IS SUBMITTED AND IS CORRECT
if(isset($_POST['action'])){
switch($_POST['action']){
case "login":
$pw = $_POST['pw'];
$loginUn = $db->real_escape_string($_POST['loginUn']);
$result = mysqli_query($db,"SELECT `Password` FROM `accounts` WHERE `Username`='" .$loginUn. "'");
if(mysqli_num_rows($result) != 0){
$dbpw = $result->fetch_object();
$VI = explode("-",$dbpw->Password);
$dbpw = openssl_decrypt($VI[1],"blowfish","",0,$VI[0]);
if($pw == $dbpw){
$login = true;
$_SESSION['login'] = true;
$_SESSION['Username'] = $_POST['loginUn'];
$un = $_POST['loginUn'];
}
}
break;
case "logout":
$_SESSION['login'] = false;
$_SESSION['Username'] = "";
break;
}
}else{
if(isset($_SESSION['login'])){
$login = $_SESSION['login'];
$un = $_SESSION['Username'];
}
}
?>
it seems to work fine, since it works in the page it is used.
I have made some dummy accounts in the database, with these usernames: Admin and User.
Here is the code of the page it went wrong:
PHP:
//THIS IS NOT THE SAME PAGE AS THE PREVIOUS PHP CODE
$login = false; //CHECK IF USER HAS LOGGED IN
$un = "";
if(isset($_SESSION['login'])){
$login = $_SESSION['login']; //IF LOGGED IN SET TO SESSION VALUE
$un = $_SESSION['Username']; //SET $UN TO USERNAME IN SESSION
}
Then I used javascript and php to alert the values which the variables contain:
<script type="text/javascript">
alert("$un = <?php echo $un;?>");
</script>
With the login variable seemed to be no problem, since it had the good value, but the variable $un was wrong. When I wasn't logged in, it had no value, which is correct, but when I was logged in, it contained the value Admin, even when I wasn't logged in with Admin. In the browser options the cookie value seemed correct. I've checked the cookie on every page, and it worked just fine, just not on this page. What am I doing wrong that makes the browser(which is firefox by the way) think that it is always Admin that is logged in?
As mentioned earlier in the comments, there are many security risks in your script.
You should take a look at PHP's sessions to build your login. Using sessions, there will be only one cookie storing an ID and all the data will be stored on your server and can't be modified by the user.
Your problem with 'Admin' staying as cookie value could be a caching problem.
I just found out what I did wrong. A piece of code which I found irrelevant, missed a = so the variable wasn't compared, but set to this wrong value.

Trying to login via php not working scripts

Hi I am trying to get the user signed in via sessions, here is my code it was working before now it isn't i didnt even change the code.
profile.php (to show after logged in)
<?php
ob_start();
session_start();
$userName = $_SESSION['username'];
$userid = $_SESSION['userid'];
if(isset($_GET['session'])) {
$currentSessionID = $_GET['session'];
$currentSessionID = md5(md5(md5($currentSessionID)));
session_id($currentSessionID);
header("Location:profile.php");
return;
}
if(!isset($userName)){
echo "OUT";
return;
}
...
scripts/signin.php
ob_start();
session_start();
include"config.php";
echo "here";
// check for required fields
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['Username']) && isset($_POST['Password'])) {
$user = mysql_real_escape_string($_POST['Username']);
$pass = mysql_real_escape_string($_POST['Password']);
$decrypt = md5(md5(md5($pass)));
$ensure = "select * from userinfo WHERE Username = '$user' and Password='$decrypt' and status='1'";
$result= mysql_query($ensure);
if(mysql_num_rows($result) > 0) {
echo "here2";
$entry = mysql_fetch_array($result) or die(mysql_error());
$_SESSION['username'] = $entry['Username'];
echo $entry['Username'];
$_SESSION['userid'] = $entry['Id'];
$currentSessionID = session_id();
$currentSessionID = md5(md5(md5($currentSessionID)));
header("Location: http://www.myprocity.com/profile.php?session=".$currentSessionID);
echo "here3";
the reason why im passing in the session id is because im trying to only keep sign in and sign up HTTPS while the other pages HTTP so I can show Google ads, does anyone know how to implement this without security issues (perfectly)
it always goes to OUT even when $_SESSION is my username (database is correct)
In profile.php you are checking for the presence of a session ID, and changing the session ID if you find it. You are doing this after you've set up a session with session_start(), but the PHP manual specifically says you must call session_id() before session_start() for this to work.
You're also hashing $_GET['session'] before sending it, and again before using it. The session ID you're trying to use in profile.php won't match the session ID used in signin.php
The result is that $_SESSION does not have the data in it you are expecting.
You need to rationalise your use of session_id(), and ensure the correct value is passed from page to page. All the hashing with md5() is just complicating matters - drop it. Realistically, I don't see why you need anything more than session_start() at the top of each page and let PHP handle the sessions. You may have an argument for doing what you're doing, but your solution simply won't work.

cannot pass session variables

if(isset($_POST["username"])&& isset($_POST["password"])){
include('config.php'); //this one connects to the database
$username = $_POST["username"];
$password = md5($_POST["password"]);
$sql2=mysql_query("SELECT * FROM clinic_staff WHERE username='$username' AND password='$password'");
$count2 = mysql_num_rows($sql2);
if($count2 == 1){
while($row2 = mysql_fetch_array($sql2)){
$id = $row2["staff_ID"];
$position = $row2["position"];
}
$_SESSION["id"] = $id;
$_SESSION["name"] = $username;
$_SESSION["password"] = $password;
$_SESSION["pos"] = $position;
header("location:index.php");
exit();
}
The problem is I can't echo the username in index.php. I don't know if it is passed successfully. in index.php i used echo $_SESSION["name"];
put session_start(); at the beginning of your document with no white space above it.
You need to look at session_start to start a session. Examples are here
I don't see session_start();. You have to call that function at the top of every page you use session variables. (At least I have to do that on my server, somebody said to me you should actually be able to use Session variables without session_start();, but everything that needed a session variable stopped working after I removed the calls to session_start();)

PHP session_start question

So i'm writing a simple login script and I ran into some problems. I was able to create the login.php file that works with this dashboard.php file below. Let me describe the scenario: User come into the main page, which is the login page. Enters username and password. If entered correctly user will see the output "dashboard succesfull". If entered wrongly it will redirect them to loginfailed.php. Problem is that the browser does not remember that the user has already been logged in. If I re-enter this page, it will directly goes to loginfailed.php. So my obivous n00b question here is......is there a way to make the browser remember that the user has already been logged in?
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
$dblink = mysql_connect("localhost", "root", "");
mysql_select_db("user",$dblink);
$sql = "select * from members where username = '$username' and password = '$password'";
$result = mysql_query($sql) or die ( mysql_error() );
$count = 0;
while ($line = mysql_fetch_assoc($result)) {
$count++;
}
if ($count == 1) {
$_SESSION['loggedIn'] = "true";
echo "<a href='dashboard.php'>dashboard succesfull</a>";
} else {
$_SESSION['loggedIn'] = "false";
header("Location: loginfailed.php");
}
?>
Sure. You just need to put, at the top of the page but below session_start(), something like:
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] == 'true') {
# do something. maybe redirect and then exit?
}
Also, I'd suggest using a session name and escaping the username and password before putting them in your SQL.

Categories