2014-11-20 9 views
0

Я пытаюсь создать страницу входа, где пользователь вводит пароль, и если он соответствует «секретному» слову, пользователь может изучить 3 варианта. Я попытался с session_start() и включил «аутентификацию», чтобы иметь возможность просматривать 3 варианта, но каждый раз, когда я нажимаю на них, они возвращают меня на главную страницу. Что я делаю не так? P.S Я хочу, чтобы иметь возможность скрывать форму входа после успешной проверки подлинности. Любая помощь очень ценится.

<?php session_start(); ?> 
<!DOCTYPE html> 
<head> 
    <title> 
    </title> 
</head> 

<body> 

<?php 
$entries = array(
    array(
     'stage' => 'Stage One', 
     'plan' => 'To begin your plan, you must first Blackmail a Town Mascot. This will cause the world to sit up and take notice, stunned by your arrival. Who is this Ripe Bastard? Where did they come from? And why do they look so good as a Dark Gunslinger?', 
    ), 
    array(
     'stage' => 'Stage Two', 
     'plan' => 'Next, you will Desecrate the Internet. This will cause countless hordes of Computer Programmers to flock to you, begging to do your every bidding. Your name will become synonymous with Dear God No, as lesser men whisper your name in terror.', 
    ), 
    array(
     'stage' => 'Stage Three', 
     'plan' => 'Finally, you will Reveal to the World your Needlessly Big Weather Machine, bringing about an End to Sanity. This will all be done from a Fake Mountain, an excellent choice if we might say. These three deeds will herald the end, and the citizens of this planet will have no choice but to elect you their new god.', 
    ), 
); 
?> 

<?php if ( isset($_POST["password"])==FALSE) : ?> 

    <form action="wd.php" method="POST"> 
     <div>Please login</div> 
     Password:<br> 
     <input type="text" name="password"/> 
     <br> 
     <input type="submit" value="Submit"/> 

    </form> 

<?php else: ?> 
<?php endif; ?> 

<?php if (isset($_POST["password"])): ?> 




    <?php if ($_POST["password"] == "secret"): 
     ?> 
     <?php $_SESSION["authenticate"] = 1; ?> 
    <?php else: ?> 

     <?php $_SESSION["authenticate"] = 0; ?> 
     <a href="wd.php"></a> 
    <?php endif; ?> 


    <?php if ($_SESSION["authenticate"] == 1): ?> 
     <?php foreach ($entries as $k => $v): ?> 
      <a href="<?php echo $_SERVER['PHP_SELF'] . "?stage_id={$k}" ?>"><?php echo $entries[$k]['stage'] ?></a> 

     <?php endforeach ?> 
     <form method="POST"> 
      <button name ="stop"> Stop </button> 

     </form> 
     <?php if (isset($_GET["stage_id"])): ?> 

      <p><?php echo $entries[$_GET["stage_id"]]['stage']; ?></p> 
      <p><?php echo $entries[$_GET["stage_id"]]['plan']; ?></p> 




     <?php endif; ?> 
     <?php 
     if (isset($_POST["stop"])): 
      session_destroy(); 
      ?> 
     <?php endif; ?> 
<?php else: ?> 

     <form action="wd.php" method="POST"> 
      <div>Please login</div> 
      Password:<br> 
      <input type="text" name="password"/> 
      <br> 
      <input type="submit" value="Submit"/> 

     </form> 
     <?php echo "invalid password"; ?> 

<?php endif; ?> 

+2

Это не имеет ничего общего с исходным вопросом, но вы действительно не должны открывать и закрывать те '' теги в каждой новой строке, которую вы пишете, так как это замедлит выполнение. Если вы снова откроете его сразу, просто не закрывайте его! –

+0

«Обратно на главную страницу» вы имеете в виду форму для входа? –

+0

Вам нужно проверить переменную сеанса в начале. Если они уже прошли проверку подлинности, вам не нужно проверять пароль или отображать форму входа в систему. – Barmar

ответ

0
<?php 
session_start(); //start the session 

function loginForm($url) //gets back the login form 
{ 
    $res = '<form action="'.$url.'" method="POST"> 
     <div>Please login</div> 
     Password:<br> 
     <input type="text" name="password"/> 
     <br> 
     <input type="submit" value="Submit"/> 

    </form>'; 

    return $res; 
} 

function showError($message) 
{ 
    echo "<p class='error'>".$message."</p>"; 
} 

function login($password) //handles the login 
{ 
    $_SESSION['authenticate'] = ($password == 'secret'); 
} 

function logout() //handles the logout 
{ 
    unset($_SESSION['authenticate']); 
} 

function isAuthenticated() //returns if someone is authenticated 
{ 
    return isset($_SESSION['authenticate']) && $_SESSION['authenticate']; 
} 

if(isset($_POST['password']) //if there is a new password, you can try to login 
    $error = login($_POST['password']); 

if(!isAuthenticated()) //if someone isn't authenticated you can show the login form, else show the rest 
{ 
    echo loginForm("wd.php"); 
    if($error) showError("Wrong password!"); 
} 
else{ 
    echo "logged in"; 
} 

взглянуть на это, его хорошую привычку использовать функции или даже пойти на ООП. ваш код станет более многоразовым и т. д.

0

Во-первых, реорганизуйте свой код. Вам нужно много PHP и HTML, чтобы сохранить хорошую читаемость. Во-первых, все процедуры PHP. Затем отобразите HTML с минимальным PHP внутри него.

Для ошибки поймите, что каждый раз, когда страница загружается, вы будете тестировать $ _POST ["password"] == "secret" и поэтому переписывать $ _SESSION ["authenticate"] каждый раз.