duanmi1900 2017-02-03 11:09
浏览 40
已采纳

要求用户登录某些页面

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>
";
// 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>
";
}
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>
  • 写回答

1条回答 默认 最新

  • doqpm82240 2017-02-03 11:18
    关注

    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
    
    }
    
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图