Link to home
Start Free TrialLog in
Avatar of fackz
fackz

asked on

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

SOLUTION
Avatar of ycTIN
ycTIN
Flag of Hong Kong image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of fackz
fackz

ASKER

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

Avatar of fackz

ASKER

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.
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
Avatar of fackz

ASKER

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

Avatar of Vimal DM
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
Hi, ok I see what is happening. Just call session_commit() before you do any kind of redirects. Should solve it I think.
Avatar of fackz

ASKER

fraserc can you write an example with my code?
sorry I'm pretty new with php
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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