登录之间的PHP重定向&其他页面

时间:2013-12-15 20:11:15

标签: php authentication login

我是PHP的新手,我遇到了一些问题,理解我做错了什么。

我的问题是我无法通过登录页面。我尝试访问的每个页面都会重定向到我的登录/主页。

这是我登录页面的代码:

<?php
session_start(); // start up your PHP session!
require_once ('includes/config.inc.php');
$page_title = 'Login'; 
include ('includes/header.html');
?>
</head>  
<body>
<?php
include ('includes/menus.html');
?>
</div>
<br />
<br />
<br /> 
<br />


<div id="main"><div class="inner_copy"></div>
        <div id="right">
        <br></br>
            <h4>Welcome to Sopshin&#39;s Rental Tracker!</h4>
            <p>Sopshin&#39;s Rental Tracker is a Ft. Lauderdale, FL based <b>theatrical lighting and equipment</b> rental and distribution company. We offer a unique interactive rental catalogue that allows the renter to track where our equipment is, and when it will return to the shop. The theatre industry is constantly faced with the challenge of working during non-typical business hours. Now, from the comfort of your computer, and at any time of day, it is possible to see the full list of equipment we have available on the dates of your event. Please take a look around or site, and feel free to contact us if you have any questions. Thank you! </p>
            <h4>Our Promise...</h4>
            <p>Sopshin&#39;s Rental Tracker is proud to offer the best in stage lighting equipment. We rent equipment from many companies including Martin Lighting, High End Systems, Vari*Lite, ETC, Strand and more! </p>
            <p><b>We promise to offer you the best in customer service and lighting equipment at the lowest possible price. Our goal is to make your show or event a success in every way possible!</b></p>
        </div>
        <div id="left">
        <br></br>
            <h3>Registered User Sign In</h3>
            <center>To create an account, please <a href="register.php"> click here. </a></center>

<head>
<center>

  <meta charset="UTF-8">

  <title>Track form progress with <progress> - CodePen</title>


    <link rel="stylesheet" href="Styles/indexlogin.css" media="screen" type="text/css" />


<body>
<?php
                if (!isset($_SESSION['user'])){
                ?>
                <div id="loginajax">
                <form>
                    <div align="center">
                            <input type='text' name='user_name' required='required' value='' class='Text' placeholder='Username' id='user_name' />
                         <input type='password' name='password' required='required' value='' class='password' placeholder='Enter Password' id='password' />
                          <div class="actions" div id="login">
                             <input name="commit" type="button" value="Login" class="login" onClick="loginUser();">
                    </div>
                </form>
                </div>
                <?php
                } else {
                echo '<p class="welcome">Welcome ' . $_SESSION['user_name'] . '</p>';
                echo '<a href="logout.php", class="welcome">Logout<br></br></a>';
                echo '<p class="welcome">Click Here to View Account </p>';
                }
                ?>    
  </div>
  </body>
  </form>
        </br>
 </body>
            <h3>News & Updates</h3>
            <img src="images/S4Mini.jpg" alt="" title="" width="150" height="100" style=" float:left; padding-right: 20px; padding-left:15px;"/>
            <p>Sopshin&#39;s Rental Tracking is proud to announce that the <b>ETC Source 4 Mini</b> is now available for rental! <a href="ETC Source 4 Mini.html">Click here for more information.</a> </p>
</div>
        <?php
        include ('includes/footer.html');
        ?>
    <!-- end #page -->
</body>
</html>

这是我尝试访问的网页的代码:

<?php
ob_start();
if (!isset($_SESSION)) {
session_start();
}
require_once ('includes/config.inc.php');
$page_title = 'Account History';
include ('includes/header.html');
?>
</head>
<body>
<?php
include ('includes/menus.html');
?>
<div id="main">
<div id="page">
    <div id="content">
 <?php
    // Check if the employee is login:
    if (isset($_SESSION['user'])) {

        require_once ('mysqli_connect.php'); // Connect to the db and creates      $dbc

        // Query the database:

        // Make the query:
        $id = $_SESSION['user'];
        $q = "SELECT `rental_ID`, `User_ID`, `date_out`, `date_in`, `price`, `venue`, `status` FROM `History` WHERE 1 ";

        $r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
        ?>


<center><IMG src="Images/Account History.png" width=175 height=40></IMG></center>
<h3><center><u>Renter:</u><?php echo $_SESSION['first_name'];?> </center></h3>
<h3><center>ID #:1031</center></h3>
<a href="Login.php"><h3><center><u>Sign Out</u></center></h3></a>
</div>
<div>
<br></br>
<link rel="stylesheet" href="Styles/table.css" type="text/css"/>    
<table class="features-table">
<thead>
    <tr>
<td></td>
<td><u><a href="RentalOrder101.html">Rental Order #101</a></u></td>
<td><u><a href="RentalOrder101.html">Rental Order #331</a></u></td>
<td><u><a href="RentalOrder101.html">Rental Order #432</a></u></td>
<td><u><a href="RentalOrder101.html">Rental Order #598</a></u></td>
    </tr>
</thead>

<tbody>
    <tr>
        <td>Dates</td>
        <td>April 1 - May 31, 2011</td>
        <td>July 1 - July 5, 2012</td>
        <td>August 1 - December 31, 2012</td>
        <td>June 1 - October 31, 2013</td>          
    </tr>
    <tr>
        <td>Venue Location</td>
        <td>Broward PAC</td>
        <td>Miniaci PAC</td>
        <td>Epstein PAC</td>
        <td>Parker Playhouse</td>           
    </tr>
    <tr>
        <td>Price</td>
        <td>$8,751.00</td>
        <td>$3,000.32</td>
        <td>$10,392.39</td>
        <td>$13,339.31</td>
    </tr>
    <tr>
        <td>Paid/Unpaid</td>
<td>Paid</td>
<td>Paid</td>
<td>Paid</td>
<td><b>Unpaid</b></td>
    </tr>
</tbody>
</table>
        <br></br>
        <a href="RentalRequest.html"><center><IMG src="Images/Request Rental.png" width=250 height=40></IMG></center></a>

    <br></br>
                <?php
        mysqli_close($dbc); // Close the database connection.

        // Include the footer and quit the script:
        echo '</div>';
        echo '<div style="clear: both; height: 1px;"></div></div><!-- end #page -->';
        include ('includes/footer.html');
        exit();

        mysqli_close($dbc); // Close the database connection.

    } // End of the main Submit conditional.
    else {
        $url = BASE_URL . 'Login.php'; // Define the URL:
        ob_end_clean(); // Delete the buffer.
        header("Location: $url");
        exit(); // Quit the script.

    }
    ?>


    </div>
<!-- end #page -->
<?php
include ('includes/footer.html');
?>
</body>
</html>

如果重要,我可以注册并成功登录,所以我知道我正在查看我的数据库。我也知道我还没有完全将我的第二段代码转换为php(还有一些静态的部分),但我希望能够在我尝试深入研究之前看到它运行。

提前感谢您的帮助。

编辑 - 我想在下面发布一些代码:

这是我的config.inc.php:

<?php # Script 16.3 - config.inc.php
/* This script:
* - define constants and settings
* - dictates how errors are handled
* - defines useful functions
*/
// Document who created this site, when, why, etc. 
// ********************************** //
// ************ SETTINGS ************ //
// Flag variable for site status:
define('LIVE', FALSE);
// Admin contact address:
define('EMAIL', 'ds155@nova.edu');
// Site URL (base for all redirections):    
define ('BASE_URL', 'http://localhost:8888/sopshin_rental/');
// Location of the MySQL connection script:
define ('MYSQL', '../mysqli_connect.php');
// Adjust the time zone for PHP 5.1 and greater:
date_default_timezone_set ('US/Eastern');
// ************ SETTINGS ************ //
// ********************************** //
// ****************************************** //
// ************ ERROR MANAGEMENT ************ //
// Create the error handler:
function my_error_handler ($e_number, $e_message, $e_file, $e_line, $e_vars) {
// Build the error message.
$message = "<p>An error occurred in script '$e_file' on line $e_line: $e_message\n<br />";  
// Add the date and time:
$message .= "Date/Time: " . date('n-j-Y H:i:s') . "\n<br />";
// Append $e_vars to the $message:
$message .= "<pre>" . print_r ($e_vars, 1) . "</pre>\n</p>";
if (!LIVE) { // Development (print the error).
    echo '<div class="error">' . $message . '</div><br />'; 
} else { // Don't show the error:
    // Send an email to the admin:
    mail(EMAIL, 'Site Error!', $message, 'From: email@example.com');
    // Only print an error message if the error isn't a notice:
    if ($e_number != E_NOTICE) {
        echo '<div class="error">A system error occurred. We apologize for the inconvenience.</div><br />';
    }
} // End of !LIVE IF.
} // End of my_error_handler() definition.
// Use my error handler.
set_error_handler ('my_error_handler');
// ************ ERROR MANAGEMENT ************ //
// ****************************************** //
?>

这是我的header.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

</head>
<body>
<div id="content">
<div id="header">
</div>
        <link href="Styles/styles.css" rel="stylesheet" type="text/css">
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'>    </script>
 <script type="text/javascript">
 function loginUser()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
 {
document.getElementById("loginajax").innerHTML=xmlhttp.responseText;
//window.location='index.php';
}
}
//alert("user "+document.getElementById("user_email").value);
xmlhttp.open("GET","ajaxLogin.php?un=" + document.getElementById("user_name").value +  "&p="  + document.getElementById("password").value ,true);
xmlhttp.send();
}
</script>
<!-- end header.html -->

最后,这是我的ajaxlogin.php:

<?php # Script 16.8 - login.php
// This is the login page for the site.

require_once ('includes/config.inc.php');
require_once ('mysqli_connect.php'); // Connect to the db.

// Validate the username:
if (!empty($_GET['un'])) {
$un = mysqli_real_escape_string ($dbc, $_GET['un']);
 } else {
$un = FALSE;
echo '<p class="error">You forgot to enter your username.';
        echo '<a href="register.php", class="welcome"> Register </a>';
        echo '<a href="forgotPassword.php", class="welcome">Forgot Password</a>';
}

// Validate the password:
if (!empty($_GET['p'])) {
$p = mysqli_real_escape_string ($dbc, $_GET['p']);
} else {
$p = FALSE;
echo '<p class="error">You forgot to enter your password!';
        echo '<a href="register.php", class="welcome"> Register </a>';
        echo '<a href="forgotPassword.php", class="welcome">Forgot   Password</a>';
 }

if ($un && $p) { // If everything's OK.
// Query the database:
$q = "SELECT user_name FROM user
                  WHERE (user_name='$un' AND password=SHA1('$p'))";
                $r = mysqli_query ($dbc, $q) or trigger_error("Query:   $q\n<br />MySQL Error: " . mysqli_error($dbc));
                if (@mysqli_num_rows($r) == 1) { // A match was made.
session_start();

    // Put user in the session and send back a Welcome message
    $_SESSION = mysqli_fetch_array ($r, MYSQLI_ASSOC);
    mysqli_free_result($r);
    echo '<p class="welcome">Welcome ' . $_SESSION['user_name'] . '</p>';
    echo '<a href="logout.php", class="welcome">Logout<br></br></a>';
    echo '<a href="accounthistory.php", class="welcome">View11<br></br></a>';

} else { // No match was made.  Send back error message and login form.
    echo '<p class="error">invalid username and/or password.</p>';
    echo "<form><div align='left'>";
    echo "<input type='text' name='user_name' required='required' value=''   class='Text' placeholder='Username' id='user_name'<br/>";
    echo "<input type='password' name='passwrd' required='required' value=''  class='password' placeholder='Enter Password' id='password'<br/>";
    echo "<input type='button' name='submitted' value='Sign In'  onclick='loginUser();'></div></form>";     
}

} else { // If everything wasn't OK.
    echo "<form><div align='left'>";
    echo "<input type='text' name='user_name' required='required' value=''  class='Text' placeholder='Username' id='user_name'<br/>";
    echo "<input type='password' name='passwrd' required='required' value='' class='password' placeholder='Enter Password' id='password'<br/>";
    echo "<input type='button' name='submitted' value='Sign In'   onclick='loginUser();'></div></form>";        
}

mysqli_close($dbc); 
?>

3 个答案:

答案 0 :(得分:1)

  • 我假设您没有强制重定向到登录页面的.htaccess文件。如果这样做,您可能需要重新配置此文件。

  • 我还想看看config.inc.php和header.html文件中的代码(一些程序员在html文档中包含php代码)。

  • 正如phphelp所述,您的表单中没有action属性,但只要您的登录逻辑包含在登录页面或您包含的其中一个文件中,就不需要此属性。我没有在您的代码中看到此逻辑,但您声明您可以登录并成功注册。这段代码在哪里?

  • 您还需要在用户登录后手动设置$ _SESSION变量。我看到您的代码检查变量,如$ _SESSION ['user'],但我看不到您在哪里设置$ _SESSION ['用户']。这也可能包含在您的登录逻辑中,但同样,我在上面的代码中没有看到这个逻辑。

在您的第二个文件(您尝试访问的页面)中,您可能需要替换:

ob_start();
if (!isset($_SESSION)) {
    session_start();
}

使用:

session_start();
ob_start();

另外请注意,您可能需要查看以下代码:

$url = BASE_URL . 'Login.php'; // Define the URL:
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.

PHP标头重定向应该先发送。我注意到,当数据已经发送给用户时,很多时候重定向仍然有效,但不建议这样做。

正如eddwin所说,您需要在登录页面的顶部添加重定向。只有在检查用户已记录后才能发送标头。应将以下内容添加到登录页面的顶部...

If (login_sucessfully() == true) {
    header("Location: go-to-this-page.html");
    exit; // Needs to be added because the redirect header that is sent, does not stop script execution
}

答案 1 :(得分:0)

要重定向到另一个页面,您需要header()示例。

标题('Location:mypage.php');

并确保在标题放置之前没有打印任何内容。对于session_start();

希望这有帮助。

答案 2 :(得分:0)

您的表单似乎没有任何行动 http://www.w3schools.com/php/php_forms.asp