首页 > 解决方案 > PHP Header() - 白页问题(无错误)

问题描述

我对 PHP 标头有一个令人费解的问题。我之前在一个项目中使用过下面的代码,并将其复制到一个新项目中,我还需要一个管理面板来从数据库中添加、编辑和删除用户。用户看到的我的页面设置为发布给自己,并且我的所有支持功能都包含在一个单独的 php 文件中,并相应地响应。正如我所期望的那样,数据库创建、删除和更新都可以正常工作,但是我的函数在到达 header() 时似乎失败了;我留下的部分代码让用户坐在没有错误的空白页面上,而不是根据需要重新加载页面的功能。我已经在替换 header(); 下面测试了我的删除功能;带有 javascript 代码的代码

echo"<script type=\"text/javascript\"> window.location.rel=\"noopener\" target=\"_blank\" href = 'users.php';</script>";

并且使用上面的代码,页面重新加载并按我的预期运行,但我想找出为什么标头函数无法正常运行,所以我不必依赖 javascript。正如您将看到的,我的 users.php 页面上有许多包含,但这主要用于菜单等,以使更新通用页面项目(例如菜单)更容易进行站点范围的更新。唯一与设置相关的其他文档是我的“config_admauth.php”,它启动我的会话,包含数据库连接并检查用户是否是管理员,因此有权查看管理页面。有趣的是,这里的标题方向工作正常,就好像我没有登录并尝试访问我被重定向到登录页面的页面,正如我所期望的那样。

所有的代码都和我的一样,除了我的 config_admauth.php,我已经对其进行了清理以删除域、用户名等。

任何帮助将非常感激。

艾伦。


[Users.php](用户看到的页面)

<?php require_once($_SERVER['DOCUMENT_ROOT'].'/admin/includes_adm/config_admauth.php') ?> 
<?php include($_SERVER['DOCUMENT_ROOT'].'/admin/includes_adm/admin_functions.php'); ?>
<?php 
error_reporting(E_ALL);
ini_set("display_errors", TRUE);
?>
<?php 
    // Get all admin users from DB
    $admins = getAdminUsers();
    $roles = ['Admin', 'User'];             
?>
<!DOCTYPE HTML>
<!--
    Future Imperfect by HTML5 UP
    html5up.net | @ajlkn
    Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
-->
<html>
    <!-- Head Section -->
    <?php include 'includes_adm/head_section_adm.php'; ?>
    
    <body class="single is-preload">

        <!-- Wrapper -->
            <div id="wrapper">

                <!-- Header -->
                    <?php include $_SERVER['DOCUMENT_ROOT'].'/includes/header.php'; ?>
                    
                <!-- Menu -->
                    <?php include $_SERVER['DOCUMENT_ROOT'].'/includes/menu.php'; ?>

                <!-- Main -->
                    <div id="main">
                         <!-- Dashboard Menu Content -->
                            <article class="post">
                                <header>
                                    <div class="title">
                                        <h2>User Management</h2>
                                        <p>Add, edit & delete user profiles</p>
                                    </div>
                                </header>                                   
                                <!-- Display notification message -->
                                <?php include($_SERVER['DOCUMENT_ROOT'] . '/includes/messages.php') ?>
                                <?php include($_SERVER['DOCUMENT_ROOT'] .'/includes/errors.php') ?>
                                <!-- Start Content. -->
                                <section style="padding-bottom:1em;">
                                    <h3 class="icon fa-server collapsible">
                                        <span>Add / Edit User</span>
                                    </h3>
                                    
                                    <div id="useradm" class="action content useradm">
                                        <h1 class="page-title">User Admin</h1>
                                            <form method="post" action="<?php echo BASE_URL . 'admin/users.php'; ?>" >
                                            <!-- validation errors for the form -->
                                            <!-- if editing user, the id is required to identify that user -->
                                                                                                <?php if ($isEditingUser === true): ?>
                                                <input type="hidden" name="admin_id" value="<?php echo $admin_id; ?>">
                                                <?php endif ?>
                                                
                                                <input type="text" name="first_name" value="<?php echo $first_name; ?>" placeholder="First Name">
                                                <input type="text" name="last_name" value="<?php echo $last_name; ?>" placeholder="Last Name">
                                                <input type="email" name="email" value="<?php echo $email ?>" placeholder="Email">
                                                <input type="password" name="password" placeholder="Password">
                                                <input type="password" name="passwordConfirmation" placeholder="Password confirmation">
                                                <select name="role">
                                                <option value="" selected disabled>Assign role</option>
                                                <?php foreach ($roles as $key => $role): ?>
                                                <option value="<?php echo $role; ?>"><?php echo $role; ?></option>
                                                <?php endforeach ?>
                                                </select>
                                                <?php 
                                                if(empty($enabled)){echo "<input type=\"hidden\" name=\"enabled\" value=\"1\">";}else{
                                                ?>
                                                <label for="enabled_select">Account Status</label>
                                                <select name="enabled" id="enabled_select">
                                                <?php if($enabled="1"){echo "<option value=\"1\" selected>Enabled</option><option value=\"0\">Disabled</option>";}else{echo "<option value=\"1\">Enabled</option><option value=\"0\" selected>Disabled</option>"; }?>
                                                </select>
                                                <?php }?>
                                                
                                                <br />
                                                <!-- if editing user, display the update button instead of create button -->
                                                <?php if ($isEditingUser === true): ?> 
                                                <button type="submit" class="btn" name="update_admin">UPDATE</button>
                                                <?php else: ?>
                                                <button type="submit" class="btn" name="create_admin">Save User</button>
                                                <?php endif ?>
                                                
                                                </form>
                                        </div>
                                    </section>
                                    <!-- ********************************
                                          * START USER LIST PRESENTATION *
                                          ******************************** -->
                                    <section>
                                        <h3 class="icon solid fa-id-card collapsible">
                                            <span>User List</span>
                                        </h3>
                                        <div id="userlist" class="table-div content">
                                                                                        <!-- Display notification message -->
                                        <?php if (empty($admins)): ?>
                                            <h1>No users in the database.</h1>
                                        <?php else: ?>
                                            <table class="table" style="text-align:center;">
                                            <thead>
                                                <th>Nr</th>
                                                <th>Name</th>
                                                <th>Email</th>
                                                <th>Acc Type</th>
                                                <th>Status</th>
                                                <th colspan="2">Action</th>
                                            </thead>
                                            <tbody>
                                            <?php foreach ($admins as $key => $admin): ?>
                                                <tr style="border-bottom: 1px solid #333;">
                                                <td><?php echo $key + 1; ?></td>
                                                <td><?php echo $admin['first_name']." ".$admin['last_name']; ?></td>
                                                <td><?php echo $admin['email']; ?></td>
                                                <td><?php echo $admin['role']; ?></td>
                                                <td>
                                                <?php 
                                                if($admin['enabled']="1"){echo "Enabled";}
                                                if($admin['enabled']="0"){echo "Disabled";}
                                                ?>
                                                </td>
                                                <td><a class="fa fa-pencil" href="users.php?edit-admin=<?php echo $admin['id'] ?>">ed</a></td>
                                                <td>
                                                <a class="fa fa-trash btn delete" href="users.php?delete-admin=<?php echo $admin['id'] ?>"></a>
                                                </td>
                                                </tr>
                                            <?php endforeach ?>
                                            </tbody>
                                            </table>
                                        <?php endif ?>
                                        </div>
                                    </section>
                                    <!-- ********************
                                          * SHOW MENU FOOTER *
                                          ******************** -->
                                    <?php include 'includes_adm/footer_adm.php'; ?>
                            </article>



                    </div>  
                
                </div>

                <!-- Footer -->
                    <section id="footer">
                        <p class="copyright">&copy; NAME. Design: <a href="http://html5up.net">HTML5 UP</a>.</p>
                    </section>

            </div>

        <!-- Scripts -->
            <?php include $_SERVER['DOCUMENT_ROOT'].'/includes/scripts_default.php'; ?>

    </body>
</html>

[admin_functions.php]

<?php
$admin_id = 0;
$isEditingUser = false;
$first_name = "";
$last_name = "";
$email = "";
$role = "";
$reset_key = "";
$enabled = "";


// general variables
$errors = [];

/* - - - - - - - - - -
-  Admin users actions
- - - - - - - - - - -*/
// if user clicks the create admin button
if (isset($_POST['create_admin'])) {
    createAdmin($_POST);
}
// if user clicks the Edit admin button
if (isset($_GET['edit-admin'])) {
    $isEditingUser = true;
    $admin_id = $_GET['edit-admin'];
    editAdmin($admin_id);
}
// if user clicks the update admin button
if (isset($_POST['update_admin'])) {
    updateAdmin($_POST);
}
// if user clicks the Delete admin button
if (isset($_GET['delete-admin'])) {
    $admin_id = $_GET['delete-admin'];
    deleteAdmin($admin_id);
}
// if user clicks the Delete admin confirm link
if (isset($_GET['delete-adminconf'])) {
    $admin_id_del = $_GET['delete-adminconf'];
    deleteAdminconf($admin_id_del);
}

/* - - - - - - - - - - - -
-  Admin users functions
- - - - - - - - - - - - -*/
/* * * * * * * * * * * * * * * * * * * * * * *
* - Receives new admin data from form
* - Create new admin user
* - Returns all admin users with their roles
* * * * * * * * * * * * * * * * * * * * * * */
function createAdmin($request_values){
    global $conn, $errors, $role, $email;
    $first_name = esc($request_values['first_name']);
    $last_name = esc($request_values['last_name']);
    $email = esc($request_values['email']);
    $password = esc($request_values['password']);
    $passwordConfirmation = esc($request_values['passwordConfirmation']);
    $enabled = esc($request_values['enabled']);


    if(isset($request_values['role'])){
        $role = esc($request_values['role']);
    }
    // form validation: ensure that the form is correctly filled
    if (empty($first_name)) { array_push($errors, "Uhmm...We gonna need the first name"); }
    if (empty($first_name)) { array_push($errors, "Uhmm...We gonna need the last name"); }
    if (empty($email)) { array_push($errors, "Oops.. Email is missing"); }
    if (empty($role)) { array_push($errors, "Role is required for admin users");}
    if (empty($enabled)) { array_push($errors, "Account status is not set");}
    if (empty($password)) { array_push($errors, "uh-oh you forgot the password"); }
    if ($password != $passwordConfirmation) { array_push($errors, "The two passwords do not match"); }
    // Ensure that no user is registered twice.
    // the email and usernames should be unique
    $user_check_query = "SELECT * FROM users WHERE email='$email' LIMIT 1";
    $result = mysqli_query($conn, $user_check_query);
    $user = mysqli_fetch_assoc($result);
    if ($user) { // if user exists
        if ($user['email'] === $email) {
        array_push($errors, "Email already exists");
        }
    }
    // register user if there are no errors in the form
    if (count($errors) == 0) {
        $password = md5($password);//encrypt the password before saving in the database
        $query = "INSERT INTO users (first_name, last_name, email, role, enabled, password, created_at, updated_at)
                VALUES('$first_name', '$last_name', '$email', '$role', '$enabled', '$password', now(), now())";
        //mysqli_query($conn, $query);
        
        if (mysqli_query($conn, $query)) {
        $_SESSION['message'] = "User created successfully";
        header('location: users.php');
        exit(0);
        }else{
        
        $_SESSION['message'] = "User NOT created " . mysqli_error($conn);
        header('location: users.php');
        exit(0);
        }

    }
}
/* * * * * * * * * * * * * * * * * * * * *
* - Takes admin id as parameter
* - Fetches the admin from database
* - sets admin fields on form for editing
* * * * * * * * * * * * * * * * * * * * * */
function editAdmin($admin_id)
{
    global $conn, $role, $isEditingUser, $admin_id, $email, $first_name, $last_name, $enabled, $role;

    $sql = "SELECT * FROM users WHERE id=$admin_id LIMIT 1";
    $result = mysqli_query($conn, $sql);
    $admin = mysqli_fetch_assoc($result);

    // set form values ($username and $email) on the form to be updated
    $first_name = $admin['first_name'];
    $last_name = $admin['last_name'];
    $email = $admin['email'];
    $role = $admin['role'];
    $enabled = $admin['enabled'];
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* - Receives admin request from form and updates in database
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
function updateAdmin($request_values){
    global $conn, $errors, $role, $isEditingUser, $admin_id, $email, $first_name, $last_name, $role, $enabled;
    // get id of the admin to be updated
    $admin_id = $request_values['admin_id'];
    // set edit state to false
    $isEditingUser = false;


    $first_name = esc($request_values['first_name']);
    $last_name = esc($request_values['last_name']);
    $email = esc($request_values['email']);
    $enabled = esc($request_values['enabled']);
    $password = esc($request_values['password']);
    $passwordConfirmation = esc($request_values['passwordConfirmation']);
    if(isset($request_values['role'])){
        $role = $request_values['role'];
    }
    // register user if there are no errors in the form
    if (count($errors) == 0) {
        //encrypt the password (security purposes)
        $password = md5($password);

        $query = "UPDATE users SET first_name='$first_name', last_name='$last_name', email='$email', role='$role', password='$password', enabled='$enabled' WHERE id=$admin_id";
        if (mysqli_query($conn, $query)) {
                
        $_SESSION['message'] = "User updated successfully";
        header('location: users.php');
        exit(0);
        }else{
        
        $_SESSION['message'] = "User update un-successfull:" . mysqli_error($conn);
        header('location: users.php');
        exit(0);
        }
        //mysqli_query($conn, $query);
        
        //$_SESSION['message'] = "User updated successfully";
        //header('location: users.php');
        //exit(0);
    }
}

// delete admin user 
function deleteAdmin($admin_id) 
{
        $_SESSION['message'] = "Confirm Delete User? <a href=\"users.php?delete-adminconf=" . $admin_id ."\" style=\"color:#e97770;\">Delete Now</a><br /><a href=\"users.php\" style=\"color:#e97770;\">Cancel</a>";
        header("location: users.php");
        exit(0);
}
// delete admin user 
function deleteAdminconf($admin_id_del) {
    global $conn;
    $sql = "DELETE FROM users WHERE id=$admin_id_del";
    if (mysqli_query($conn, $sql)) {
        $_SESSION['message'] = "User successfully deleted";
        header("location: users.php");
        exit(0);
    }
}


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* - Returns all admin users and their corresponding roles
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
function getAdminUsers(){
    global $conn, $roles;
    $sql = "SELECT * FROM users WHERE role IS NOT NULL";
    $result = mysqli_query($conn, $sql);
    $users = mysqli_fetch_all($result, MYSQLI_ASSOC);

    return $users;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* - Escapes form submitted value, hence, preventing SQL injection  *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
function esc(String $value){
    // bring the global db connect object into function
    global $conn;
    // remove empty space sorrounding string
    $val = trim($value);
    $val = mysqli_real_escape_string($conn, $value);
    return $val;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* - Receives a string like 'Some Sample String' and returns 'some-sample-string' *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
function makeSlug(String $string){
    $string = strtolower($string);
    $slug = preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
    return $slug;
}
//echo"<script type=\"text/javascript\"> window.location.rel=\"noopener\" target=\"_blank\" href = 'users.php';</script>";
?>

[config_admauth.php]

<?php
session_start();
if (!$_SESSION['user']['role'] == "Admin") {
$_SESSION['message'] = "You do not hold admin access rights or are not logged in";
header('location:https://domainnamehere.com/login.php');
exit(); // <-- terminates the current script
}
    // connect to database
    $conn = mysqli_connect("domainnamehere.com.mysql", "usr_name", "password", "db_name");

    if (!$conn) {
        die("Error connecting to database: " . mysqli_connect_error());
    }
    // define global constants
    define ('ROOT_PATH_INC', realpath(dirname(__FILE__)));
    define('BASE_URL', 'https://domainnamehere.com/');
?>

标签: phpheader

解决方案


好的,所以通过更多的挖掘发现打开和关闭包含我的会话开始和功能的 php 标签是问题所在。我通过将两个包含文件的内容复制到我的用户页面中发现了这一点,并打开了错误报告并遵循了错误。通过删除我复制的代码块之间的 php 标签解决了这个问题。然后我恢复了包含并从我的页面中删除了代码,错误又回来了。最后我在下面进行了切换,一切正常。

从以下切换:

<?php require_once($_SERVER['DOCUMENT_ROOT'].'/admin/includes_adm/config_admauth.php'); ?> 
<?php include($_SERVER['DOCUMENT_ROOT'].'/admin/includes_adm/admin_functions.php'); ?>

<?php 
require_once($_SERVER['DOCUMENT_ROOT'].'/admin/includes_adm/config_admauth.php'); 
include($_SERVER['DOCUMENT_ROOT'].'/admin/includes_adm/admin_functions.php'); 
?>

推荐阅读