2016-06-29 5 views
0

現在、私は非常に単純なログインページを作成しようとしています。直接URLへの書き込みのリダイレクトと要求

ローカルで作業しています。 index.phpとlogin.phpページがあるとします。 URLバーにlocalhost:8080/index.phpを書くと、このページを見ることができます。しかし、index.phpページにリダイレクトするにはログインが必要です。ここで

は、私は、URLが入力されたとき、私はそれをリダイレクトすることが出来るのですか見当がつかない、login.phpのコードである

<html> 
<head></head> 
<body> 
<form method="post" name="login" action=""> 
<table align=center> 
    <tr> 
     <td><input type="text" name="username" placeholder="Username"></td> 
    </tr> 
    <tr> 
     <td><input type="text" name="password" placeholder="Password"></td> 
    </tr> 
    <tr> 
     <td><input type="submit" name="submit" value="Login"></td> 
    </tr> 
</table> 
</form> 

<?php 



    if (isset($_POST['submit'])) 
    { 
     $username="admin"; 
     $password="admin"; 
     $uUsername=$_POST['username']; // the username which User will enter 
     $uPassword = $_POST['password'];// the password which User will enter 

     if ($username != $uUsername || $password != $uPassword) 
     { 
      echo 'Incorrect username or password.Please try again'; 
     } 

     else 
     { 
      header("refresh:0; url=deneme.php"); 
     } 
    } 
?> 

+0

大域的な '$ _SESSION'を使用してください。あなたの保護されたページで、あなたは 'if(!isset($ _ SESSION ['login'])){/ *何か* /} else {/ *ページの内容を表示する/}} - http: //www.w3schools.com/php/php_sessions.asp – Qirel

+0

私はセッションについて知っています。しかし、私はこれを行うことができる別の方法を探しています。なぜ私はそれを簡単に保っていたと言いますか?簡単に、別の方法を探してください。 –

+0

セッションはこの目的のために広く使用されており、使用するのが非常に簡単です。私は興味があります、なぜあなたは別の方法を使いたいのですか?代わりにクッキーを使用することですが、基本的にセッションを使用するのと同じです。ログイン後にユーザーを認識できるものが必要なので、オプションが絞り込まれます。 – Qirel

答えて

0

まず第一に、ブラウザには何も出力する前に出力前にheader()を呼び出す必要があるため、ユーザーが認証されているかどうかを確認する必要があります。私はこれにセッションを使用します。

認証されたユーザ(ログインページを除く)が必要とするすべてのファイルの先頭には、私はこれを追加するには:セッション場合

<?php 
session_start(); 
if (!isset($_SESSION['authenticated'])) { 
    // The user isn't authenticated, let's redirect the user to the login page 
    header('location: login.php'); // Change 'login.php' to the correct page/url to the login page. 
    exit; // Important to stop the script-execution after a header location. 
} 

これは、ログインページにユーザーをリダイレクトしますが設定されていません(ユーザーは認証されていません)。

ログインページ

、私は(<html>前)ファイルの先頭に認証スクリプトを移動し、このようにそれを変更しますさらにダウン形式で

<?php 
$errorMessage = null; 

if (isset($_POST['submit'])) { 
    $username = "admin"; 
    $password = "admin"; 
    $uUsername = $_POST['username']; 
    $uPassword = $_POST['password']; 

    if ($username != $uUsername || $password != $uPassword) { 
     $errorMessage = 'Incorrect username or password. Please try again'; 
    } else { 
     // Start the session and set authenticated as true. 
     session_start(); 
     $_SESSION['authenticated'] = true; 
     header('location: index.php'); // Again, change 'index.php' to the correct file/url 
     exit; 
    } 
} 
?> 
<html> 
....// the rest of the login form 

を、あなたは$errorMessageかどうかを確認することができますnullではなく、エラーメッセージを表示する場所です。

認証チェックのコードは、すべてのファイルにハードコードするのではなく、すべてのファイルに含める別のファイルに移動する必要があります。

関連する問題