简体   繁体   中英

Require user to login for certain pages

I have a mysql table that gets data inserted and deleted using the forms on my php pages. That all works. Now I want the users to be able to view index.php (homepage which displays the table and all its data) but if they click delete or add it must ask them to login before the add.php or delete.php pages are shown to them. I have written a login.php script below but am unsure how to force the page to check it before letting them through. Also if the user does login, will it take him to the page he clicked on or just back to index.php

EDIT Updated the Code As requested

login.php

<?php

if (isset($_SESSION['SESS_MEMBER_ID']) && !empty($_SESSION['SESS_MEMBER_ID'])) {


header("location:add.php"); // if user is logged in don't show the form take them were they need to be
} else {
?>


<?php
    //Start session
    session_start();        
    //Unset the variables stored in session
    unset($_SESSION['SESS_MEMBER_ID']);
    unset($_SESSION['SESS_FIRST_NAME']);
    unset($_SESSION['SESS_LAST_NAME']);
?>


<form name="loginform" action="login_exec.php" method="post">
<table width="309" border="0" align="center" cellpadding="2" cellspacing="5">
<tr>
<td colspan="2">
    <!--the code bellow is used to display the message of the input validation-->
     <?php
        if( isset($_SESSION['ERRMSG_ARR']) && is_array($_SESSION['ERRMSG_ARR']) && count($_SESSION['ERRMSG_ARR']) >0 ) {
        echo '<ul class="err">';
        foreach($_SESSION['ERRMSG_ARR'] as $msg) {
            echo '<li>',$msg,'</li>'; 
            }
        echo '</ul>';
        unset($_SESSION['ERRMSG_ARR']);
        }
    ?>
</td>
</tr>
<tr>
<td width="116"><div align="right">Username</div></td>
<td width="177"><input name="username" type="text" /></td>
</tr>
<tr>
<td><div align="right">Password</div></td>
<td><input name="password" type="text" /></td>
</tr>
<tr>
<td><div align="right"></div></td>
<td><input name="" type="submit" value="login" /></td>
</tr>
</table>
</form>


<?php

}


?>

Login_exec.php

<?php
//Start session
session_start();

//Include database connection details
require_once('connection.php');

//Array to store validation errors
$errmsg_arr = array();

//Validation error flag
$errflag = false;

//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
    $str = @trim($str);
    if(get_magic_quotes_gpc()) {
        $str = stripslashes($str);
    }
    return mysql_real_escape_string($str);
}

//Sanitize the POST values
$username = clean($_POST['username']);
$password = clean($_POST['password']);

//Input Validations
if($username == '') {
    $errmsg_arr[] = 'Username missing';
    $errflag = true;
}
if($password == '') {
    $errmsg_arr[] = 'Password missing';
    $errflag = true;
}

//If there are input validations, redirect back to the login form
if($errflag) {
    $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
    session_write_close();
    header("location: login.php");
    exit();
}

//Create query
$qry="SELECT * FROM member WHERE username='$username' AND password='$password'";
$result=mysql_query($qry);

//Check whether the query was successful or not
if($result) {
    if(mysql_num_rows($result) > 0) {
        //Login Successful
        session_regenerate_id();
        $member = mysql_fetch_assoc($result);
        $_SESSION['SESS_MEMBER_ID'] = $member['mem_id'];
        $_SESSION['SESS_FIRST_NAME'] = $member['username'];
        $_SESSION['SESS_LAST_NAME'] = $member['password'];
        session_write_close();
        header("location: index.php");
        exit();
    }else {
        //Login failed
        $errmsg_arr[] = 'user name and password not found';
        $errflag = true;
        if($errflag) {
            $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
            session_write_close();
            header("location: login.php");
            exit();
        }
    }
}else {
    die("Query failed");
}
?>

index.php

<center>
<html>
<head>
<title>Extension List</title></head><body>
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = '****';

$database = 'list';
$table = 'users';

if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");

if (!mysql_select_db($database))
die("Can't select database");

// sending query
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) {
die("Query to show fields from table failed");
}

$fields_num = mysql_num_fields($result);

echo "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";

// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
    echo "<td>$cell</td>";

echo "</tr>\n";
}
mysql_free_result($result);
?>
<br>
<h1> Alpine Motors Extension List</h1>
<h2><a href="add.php">Add Extension</a>
<br>
<br>
<a href="delete.php"> Delete Extension</a></h2> 
<br> <br>
</h3>
</body>
</html>
</center>
<?php

}


?>

delete.php

<?php

require ("database.php");
?>

<?php


$this_Stud_ID =$_REQUEST['id'];

// sending query
mysql_query("DELETE FROM users WHERE id = '$this_Stud_ID'")
or die(mysql_error());      


if($_POST['action'])

header("Location: index.php");
?>
<center><form action="<?php echo $_SERVER['php_self'] ?>" method="post">
Enter ID Number :<br><input type="text" name="id"><br />
<br><input type="submit" name="action" value="Delete!">
<br> <br>
<h3>
<a href="index.php"> Main Menu </a> 
</h3>
</form>
</center>

on everypage that you need the user to login to access it you need to check if any of the sessions u set on login page are set and not empty

in this case I will use the member id session

passwordProtectedPage.php

<?php


if(isset( $_SESSION['SESS_MEMBER_ID']) && !empty($_SESSION['SESS_MEMBER_ID'])):?>

    Do your html and other code

<?php

    else:

        header("location:page.php"); // take them to page

     //or echo "You not allowed to view this page <a href=\"login.php\">Please login</a>";

    endif;
    ?> 

By the way you don't need to store error messages on session var, you could just do everything in one page if errors exists just print them back.

Also it does not matter if its a local test page you need to do things the correct way, so that you can be a better programmer one day, so hash those passwords and read more about prepared statements.

Edit :

On the login page also first you need to check if the user is not logged in already. if they are loggedin take them to where they need to be else show the form and proccess.

<?php

if (isset($_SESSION['SESS_MEMBER_ID']) && !empty($_SESSION['SESS_MEMBER_ID'])) {


    header("location:page.php"); // if user is logged in don't show the form take them were they need to be
} else {
?>


    show the form content and do proccessing


<?php

}


?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM