0

hi i want to make a page accessible only to logged-in users. i searched for this but all the results i found wasn't helpful So i need to know where should i add codes . this is my login.php:

    <?php

session_start();
include_once 'dbconnect.php';

if(isset($_SESSION['user'])!="")
{
    header("Location: home.php");
}

if(isset($_POST['btn-login']))
{
    $email = mysql_real_escape_string($_POST['email']);
    $upass = mysql_real_escape_string($_POST['pass']);
    $res=mysql_query("SELECT * FROM users WHERE email='$email'");
    $row=mysql_fetch_array($res);

    if($row['password']==md5($upass))
    {
        $_SESSION['user'] = $row['user_id'];
        header("Location: home.php");
    }
    else
    {
        ?>
        <script>alert('wrong details');</script>
        <?php
    }

}
?>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ورود</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<center>
<div id="login-form">
<form method="post">
<table align="center" width="30%" border="0">
<tr>
<td><input type="text" name="email" placeholder="Your Email" required /></td>
</tr>
<tr>
<td><input type="password" name="pass" placeholder="Your Password" required /></td>
</tr>
<tr>
<td><button type="submit" name="btn-login">ورود</button></td>
</tr>
<tr>
<td><a href="register.php">ثبت نام</a></td>
</tr>
</table>
</form>
</div>
</center>
</body>
</html>

do i need to put session_start(); to every page i have ? if not where should i put it? and where should i put :

session_start();
if(!isset($_SESSION['id'])) {
    header("location: index.php"); 
    die();
}

tanq if i need to add any more detail for you guys plz tell me.

Saman D
  • 17
  • 3
  • 1
    This code is really ugly. Take a look at this guide: http://stackoverflow.com/questions/549/the-definitive-guide-to-form-based-website-authentication – klenium Jul 18 '15 at 20:50

1 Answers1

0

i think you have to make one common header file and put things like session_start(); and ob_flush(); in that file and include it in all pages. so you can access it anywhere and no need to rewrite the code . Rewrite the same code is bad-habit