Session not working

Guys, I'm using the following code to update some fields in my database.

Everything is working fine, except for the session at the top. Every time that I hit "Save changes" the system seems to be loosing the session because it keeps redirecting me to the index.php and asking for my login info again.

When I log again, The info was changed in the DB, but I would like to stay logged, instead of needing to log every time that I change something. It's important to check the session because this code are in a control panel area of my client website.
<?php
session_start();
if ( $_SESSION['status'] != 'ok' )
{
   header("location:index.php");
   exit();
}
 
require_once("../inc/config.php");
$id = $_GET['id'];
$sql = "SELECT * FROM login WHERE id='$id'";
$resultado = mysql_query($sql);
$coluna = mysql_fetch_array($resultado);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Painel de Controle</title>
<link href="css/estilo.css" rel="stylesheet" type="text/css">
</head>
 
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td><?php include('header.php'); ?></td>
  </tr>
  <tr>
    <td><div class="divalinha">Voc&ecirc; est&aacute; em: <span class="rosa">Editar Conta</span><br>
      <br>
      <?php
	  //altera os dados
	  if(@$_GET['acao']=="editar"){
	  	$quem = $_POST['quem'];
		$usuario = $_POST['usuario'];
		$email = $_POST['email'];
		$senha = $_POST['senha'];
		$status = $_POST['status'];
		$cadastrada = $_POST['cadastrada'];
		
		$mudala = "UPDATE login SET usuario='$usuario', email='$email', senha='$senha', status='$status', cadastrada='$cadastrada' WHERE id='$quem'";
		mysql_query($mudala);
			if(mysql_affected_rows() > 0 ){
				echo "<b>Registro Alterado!</b><br><br>";
				
			}else{
				echo "Erro. Tente Novamente!";
				exit;
			}
	  
	  }
	  
	  ?>
      <form name="edita" method="post" action="editatd.php?acao=editar">
      <table width="570" border="0" cellspacing="2" cellpadding="2">
        <tr>
          <td width="109" valign="middle"><div align="right">Usu&aacute;rio:</div></td>
          <td width="198" valign="middle"><input name="usuario" type="text" class="inputgd" id="usuario" value="<?php echo $coluna['usuario']; ?>"></td>
          <td width="88" valign="middle"><div align="right">Status:</div></td>
          <td width="149" valign="middle"><input name="status" type="text" class="inputgd" id="status" value="<?php echo $coluna['status']; ?>"></td>
          </tr>
        <tr>
          <td valign="middle"><div align="right">Email:</div></td>
          <td valign="middle"><input name="email" type="text" class="inputgd" id="email" value="<?php echo $coluna['email']; ?>"></td>
          <td valign="middle"><div align="right">Cadastrada:</div></td>
          <td valign="middle"><select name="cadastrada" id="cadastrada">
            <option value="sim">sim</option>
            <option value="nao">nao</option>
          </select>          </td>
          </tr>
        <tr>
          <td valign="middle"><div align="right">Senha:</div></td>
          <td valign="middle"><input name="senha" type="text" class="inputgd" id="senha" value="<?php echo $coluna['senha']; ?>"></td>
          <td valign="middle"><div align="right"></div></td>
          <td valign="middle">&nbsp;</td>
          </tr>
        <tr>
          <td>&nbsp;</td>
          <td><input name="quem" type="hidden" id="id" value="<?php echo $coluna['id']; ?>"></td>
          <td>&nbsp;</td>
          <td>&nbsp;</td>
          </tr>
        <tr>
          <td>&nbsp;</td>
          <td><label>
            <input name="button" type="submit" class="submito" id="button" value="Save Changes">
          </label></td>
          <td>&nbsp;</td>
          <td>&nbsp;</td>
          </tr>
      </table>
      </form>
      </div></td>
  </tr>
</table>
</body>
</html>

Open in new window

fackzAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ycTINCommented:
I assume the status in session is mean login status. and you should has some configure about session(e.g. seesion_name('???')) in config.php

require_once("../inc/config.php");
session_start();
if ( $_SESSION['status'] != 'ok' )
{
   header("location:index.php");
   exit();
} 

Open in new window

0
fackzAuthor Commented:
On config.php I just have my database connection code.
this is what I have on my checklogin.php code:
<?php
require_once("../inc/config.php");
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword']; 
// To protect MySQL injection 
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
 
$sql="SELECT * FROM adms WHERE usuario='$myusername' and senha='$mypassword'";
$result=mysql_query($sql);
 
//verifica quantos encontrou
$count=mysql_num_rows($result);
 
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_start();
$_SESSION['status']='ok';
header("location:home.php");
}
else {
echo "invalid password!";
exit;
}
 
?>

Open in new window

0
fackzAuthor Commented:
One thing that I've notice and I forgot to mention. When I click on save changes...I got my success message, but when I click in some link at the menu, I get logged out.

But, If I don't click on "Save Changes" button, I can normally navigate into any menu link without getting logged out.

So, The problem is happening with the POST form...when I use the form, no matter which link I click, I will get logged out.
0
Become a Certified Penetration Testing Engineer

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

frasercCommented:
Hi,

If you want to use sessions you have to use session_start() on every page that uses them.

Make sure the line:

if(session_id() == "") { session_start(); }

Appears at the top of "checklogin.php", "editatd.php" as well as any other files you use.

The best way to do this would be to put it as the first line in "config.php"

F
0
fackzAuthor Commented:
I've checked all my files and I have the following code at the top of every page
<?php
session_start();
if ( $_SESSION['status'] != 'ok' )
{
   header("location:index.php");
   exit();
}
?>

Open in new window

0
Vimal DMSenior Software EngineerCommented:
Find out first the session values are stored or not and then

print all the session values

see the session is available off "status"

try using this method and tell me ur code,works or not working
0
frasercCommented:
Hi, ok I see what is happening. Just call session_commit() before you do any kind of redirects. Should solve it I think.
0
fackzAuthor Commented:
fraserc can you write an example with my code?
sorry I'm pretty new with php
0
frasercCommented:
Here you go, try this....
<?php
require_once("../inc/config.php"); // needs to be here to be inside the session...
session_start();
if ( $_SESSION['status'] != 'ok' )
{
   header("location:index.php");
   exit();
}
$id = $_GET['id'];
$sql = "SELECT * FROM login WHERE id='$id'";
$resultado = mysql_query($sql);
$coluna = mysql_fetch_array($resultado);
session_commit();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Painel de Controle</title>
<link href="css/estilo.css" rel="stylesheet" type="text/css">
</head>
 
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td><?php include('header.php'); ?></td>
  </tr>
  <tr>
    <td><div class="divalinha">Voc&ecirc; est&aacute; em: <span class="rosa">Editar Conta</span><br>
      <br>
      <?php
	  //altera os dados
	  if(@$_GET['acao']=="editar"){
	  	$quem = $_POST['quem'];
		$usuario = $_POST['usuario'];
		$email = $_POST['email'];
		$senha = $_POST['senha'];
		$status = $_POST['status'];
		$cadastrada = $_POST['cadastrada'];
		
		$mudala = "UPDATE login SET usuario='$usuario', email='$email', senha='$senha', status='$status', cadastrada='$cadastrada' WHERE id='$quem'";
		mysql_query($mudala);
			if(mysql_affected_rows() > 0 ){
				echo "<b>Registro Alterado!</b><br><br>";
				
			}else{
				echo "Erro. Tente Novamente!";
				exit;
			}
	  
	  }
	  
	  ?>
      <form name="edita" method="post" action="editatd.php?acao=editar">
      <table width="570" border="0" cellspacing="2" cellpadding="2">
        <tr>
          <td width="109" valign="middle"><div align="right">Usu&aacute;rio:</div></td>
          <td width="198" valign="middle"><input name="usuario" type="text" class="inputgd" id="usuario" value="<?php echo $coluna['usuario']; ?>"></td>
          <td width="88" valign="middle"><div align="right">Status:</div></td>
          <td width="149" valign="middle"><input name="status" type="text" class="inputgd" id="status" value="<?php echo $coluna['status']; ?>"></td>
          </tr>
        <tr>
          <td valign="middle"><div align="right">Email:</div></td>
          <td valign="middle"><input name="email" type="text" class="inputgd" id="email" value="<?php echo $coluna['email']; ?>"></td>
          <td valign="middle"><div align="right">Cadastrada:</div></td>
          <td valign="middle"><select name="cadastrada" id="cadastrada">
            <option value="sim">sim</option>
            <option value="nao">nao</option>
          </select>          </td>
          </tr>
        <tr>
          <td valign="middle"><div align="right">Senha:</div></td>
          <td valign="middle"><input name="senha" type="text" class="inputgd" id="senha" value="<?php echo $coluna['senha']; ?>"></td>
          <td valign="middle"><div align="right"></div></td>
          <td valign="middle">&nbsp;</td>
          </tr>
        <tr>
          <td>&nbsp;</td>
          <td><input name="quem" type="hidden" id="id" value="<?php echo $coluna['id']; ?>"></td>
          <td>&nbsp;</td>
          <td>&nbsp;</td>
          </tr>
        <tr>
          <td>&nbsp;</td>
          <td><label>
            <input name="button" type="submit" class="submito" id="button" value="Save Changes">
          </label></td>
          <td>&nbsp;</td>
          <td>&nbsp;</td>
          </tr>
      </table>
      </form>
      </div></td>
  </tr>
</table>
</body>
</html>

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
frasercCommented:
I just reread this....


$id = $_GET['id'];
$sql = "SELECT * FROM login WHERE id='$id'";
$resultado = mysql_query($sql);

is very dangerous as you are welcoming sql injection attacks!
Always, mistrust user input and sanitise it according to purpose.


$id = $_GET['id'];
if(!ctype_digit($id)) { $id=0; }  
$sql = "SELECT * FROM login WHERE id='$id'";
$resultado = mysql_query($sql);

At the very least would be a very good idea.
Better yet look at methods to clean all get and post data to your system.

Just google term like

 php clean user input post get mysql
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.