2016-04-13 5 views
1

Итак, у меня есть сценарий входа и не слишком уверен, почему он не будет работать. В моей таблице User У меня есть эти поля:Страница входа не указана - показывает пустую страницу PHP

Таблица: Пользователь

Field 1) ID 
Field 2) Password (it is stored with crypt) 
Field 3) Status (ranges from 0-2) 

index.php

<?php 
session_start(); 
unset($_SESSION['Status']); 
?> 
<head> 

    <title>Login Form</title> 
    <link rel="stylesheet" type="text/css" href="login.css"> 
    <img src="logo1.jpg" style="float:left; width:490px; height:130px; margin-top: -70px;"> 
    <!--[if lt IE 9]><script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script><![endif]--> 
</head> 
<body> 

<section class="container"> 
    <div class="login"> 
     <h1>Login</h1> 
     <form action="process_login.php" method="POST"/> 
     <div class="help-tip"> 
     <p>Enter the User ID and Password that you were given, in order to login. If you have forgotten your ID or Password, contact Admin</p> 
</div> 
      <p><input type="number"  name="ID" value="" placeholder="ID*"  required autofocus></p> 
     <p><input type="password" name="Password" value="" placeholder="Password*" required></p> 
     <p class="submit"><input type="submit" name="commit" value="Login"></p> 
    </form> 
</div> 

process_login.php

<?php 
session_start(); 
?> 
<?php 
//Connect to host site and databse 
include("functions.php"); 
// Fetching variables 
$id = $_POST['ID']; 
$pw = crypt($_POST['Password']); 

//Find user details from User table using the username entered and comparing the entered password with the one retrieved form the user table 

$UserValidate = mysqli_query ("SELECT * FROM User WHERE ID = '$id'") or die (mysqli_error()); 
$row = mysqli_fetch_array($UserValidate); 
$CorrectId = $row['ID']; 
$CorrectPw = $row['Password']; 
$UserType = $row['Status']; 

//check if ID in database 
if ($id == $CorrectId) { 
//check if password is assigned to that username and is correct 
if ($pw == $CorrectPw) { 
//check if user is standard user 
if ($UserType == 0) { 
    $_SESSION['CadetUser'] = $id; 
header('http://****/calendar.php:'.$url);die(); 
if ($UserType == 1) { 
$_SESSION['StaffUser'] = $id; 
header('http://****/calendar_staff.php:'.$url);die(); 
if ($UserType == 2) { 
$_SESSION['AdminUser'] = $id; 
header('http://****/calendar_admin.php:'.$url);die(); 
} 
} 
else { 
    echo "Either your ID or Password is wrong"; 
    header('http://******/index.php:'.$url);die(); 
} 
} 
} 
} 
?> 

UPDATE Моя проблема заключается в том, что я получаю пустой экран, когда я вхожу в с правильными данными. Он просто останавливается на process_login.php Также я изменил редирект «заголовок ..........», как предложил

+0

Что именно не работает? какие ошибки вы получаете? почему ваш код так сильно отформатирован? –

+0

, пожалуйста, отформатируйте свой код в соответствии с [предлагаемыми стандартами] (http://www.php-fig.org/psr/) – Baruch

+0

Санируйте ввод пользователя! Никогда не используйте данные POST непосредственно в запросах базы данных! – Paul

ответ

0

Это ваш кода - с отступом, как и вошел в вашем посте:

//check if ID in database 
if ($id == $CorrectId) { 
    //check if password is assigned to that username and is correct 
    if ($pw == $CorrectPw) { 
     //check if user is standard user 
     if ($UserType == 0) { 
      $_SESSION['CadetUser'] = $id; 
      header('http://****/calendar.php:'.$url); 
      die(); 
      if ($UserType == 1) { 
       $_SESSION['StaffUser'] = $id; 
       header('http://****/calendar_staff.php:'.$url); 
       die(); 
      // <----- missing a closing brace 
      if ($UserType == 2) { 
       $_SESSION['AdminUser'] = $id; 
       header('http://****/calendar_admin.php:'.$url); 
       die(); 
      } 
     } 
     else { 
      echo "Either your ID or Password is wrong"; // you need to remove this; outputting HTML prior to sending headers will result in a PHP error 
      header('http://******/index.php:'.$url); 
      die(); 
     } 
    } 
} 
} // <----- remove this 

Как вы можете видеть единственное условие, которое стоит шанс: if ($UserType == 0). Не говоря уже о том, что там есть ошибочный }, который может вызвать синтаксическую ошибку.

Вам также не хватает Location в вашем заголовке, например. header('Location: url/goes/here.php');

Я переформатировать код ниже, и фиксированные синтаксические ошибки:

//check if ID in database 
if ($id == $CorrectId && $pw == $CorrectPw) { 
    //check if user is standard user 
    if ($UserType == 0) { 
     $_SESSION['CadetUser'] = $id; 
     header('Location: http://****/calendar.php:'.$url); 
     die(); 
    } 
    elseif ($UserType == 1) { 
     $_SESSION['StaffUser'] = $id; 
     header('Location: http://****/calendar_staff.php:'.$url); 
     die(); 
    } 
    elseif ($UserType == 2) { 
     $_SESSION['AdminUser'] = $id; 
     header('Location: http://****/calendar_admin.php:'.$url); 
     die(); 
    } 
    else { 
     header('Location: http://******/index.php:'.$url); 
     die(); 
    } 
} 

А поскольку if ($id == $CorrectId) и if ($pw == $CorrectPw) необходимые условия, которые должны быть выполнены для того, чтобы продолжить, это имеет смысл только включить их в одном условии .. для удобочитаемости. По возможности избегайте условий гнездования. Делает вещи беспорядочными, и код трудно читать/следовать. Вы можете видеть, что я добавил их в одно условие.

1

Для редиректа можно попробовать

header('location:'.$url);die(); 

Примечание: удалить все эхо или печать до того заголовка и убедитесь, что вы не имеете белые пробелов перед тегами открытия PHP

0

Функция Изменить заголовок

header('http://****/calendar.php:'.$url); 

Для

header('location : http://****/calendar.php:'); 

Добавить местоположение в заголовке, как показано выше

1

Как и в сторону, ваш SQL заявление уязвимо для SQL инъекций, потому что вы положили $ id прямо в утверждение. Было бы гораздо безопаснее использовать параметры и mysqli

Смежные вопросы