2016-04-16 13 views
1

私がやっているプロジェクトでは、私はまだまだ新しくなっているPHPを使用しています。ユーザーがサインインしたりログインしたりすると、ホームページに移動し、そこで私は$_SESSIONを使用してログインします。$_SESSION['user']は、ユーザー名をセッションストアに格納することによって使用されます。しかし、ホームページからプロフィールページ(名前をクリックして行う)に切り替えると、セッションがないかのように、ログイン画面に戻って効果的にログアウトしますもう私は自分のコードを見て、私は何をやっているのか分からない。誰かが何が間違っているのか、他のページをナビゲートするときにユーザーをログインさせ続ける方法を教えてもらえますか?ここでユーザーは切り替えページをログアウトし続ける

は私signup.phpです:

<?php 
session_start(); 

/** 
* Include ircmaxell's password_compat library. 
*/ 
require 'lib/password.php'; 

/** 
* Include our MySQL connection. 
*/ 
require 'connect.php'; 


//If the POST var "register" exists (our submit button), then we can 
//assume that the user has submitted the registration form. 
if(isset($_POST['signUp'])){ 

    //Retrieve the field values from our registration form. 
    $firstName = !empty($_POST['firstName']) ? trim($_POST['firstName']) : null; 
    $lastName = !empty($_POST['lastName']) ? trim($_POST['lastName']) : null; 
    $userName = !empty($_POST['userName']) ? trim($_POST['userName']) : null; 
    $email = !empty($_POST['email']) ? trim($_POST['email']) : null; 
    $password = !empty($_POST['password']) ? trim($_POST['password']) : null; 

    //TO ADD: Error checking (username characters, password length, etc). 
    //Basically, you will need to add your own error checking BEFORE 
    //the prepared statement is built and executed. 

    //Now, we need to check if the supplied username already exists. 

    //Construct the SQL statement and prepare it. 
    $sql = "SELECT COUNT(Username) AS num FROM users WHERE Username = :username"; 
    $stmt = $pdo->prepare($sql); 

    //Bind the provided username to our prepared statement. 
    $stmt->bindValue(':username', $userName); 

    //Execute. 
    $stmt->execute(); 

    //Fetch the row. 
    $row = $stmt->fetch(PDO::FETCH_ASSOC); 

    //If the provided username already exists - display error. 
    //TO ADD - Your own method of handling this error. For example purposes, 
    //I'm just going to kill the script completely, as error handling is outside 
    //the scope of this tutorial. 
    if($row['num'] > 0){ 
     die('That username is already in use.'); 
    } 

    //Hash the password as we do NOT want to store our passwords in plain text. 
    $hash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 12)); 

    //Prepare our INSERT statement. 
    //Remember: We are inserting a new row into our users table. 
    $sql = "INSERT INTO users (firstName, lastName, Username, email, Password) VALUES (:firstName, :lastName, :username, :email, :password)"; 
    $stmt = $pdo->prepare($sql); 

    //Bind our variables. 
    $stmt->bindValue(':firstName', $firstName); 
    $stmt->bindValue(':lastName', $lastName); 
    $stmt->bindValue(':username', $userName); 
    $stmt->bindValue(':email', $email); 
    $stmt->bindValue(':password', $hash); 

    //Execute the statement and insert the new account. 
    $result = $stmt->execute(); 

    //If the signup process is successful. 
    if($result){ 
     //What you do here is up to you! 
     echo 'You are registered.'; 
     $_SESSION['user'] = $userName; 
//    return $userName; 
//  //die('debug'); 
     header('Location: home.php'); 
    } 

} 

?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 
<title>Sign Up</title> 
<!-- Bootstrap core CSS --> 
<link href="css/bootstrap.min.css" rel="stylesheet"> 
<!-- Index Custom CSS --> 
<link href="css/signup.css" rel="stylesheet"> 
<!-- Animate.css --> 
<link href="css/animate.css" rel="stylesheet"> 
<!-- Custom styles for this website --> 
<link href="css/custom.css" rel="stylesheet"> 
<link href='https://fonts.googleapis.com/css?family=Fugaz+One' rel='stylesheet' type='text/css'> 
<link href='https://fonts.googleapis.com/css?family=Fjalla+One' rel='stylesheet' type='text/css'> 
</head> 
<body> 
    <div class="container"> 
     <div class="col-md-8 col-md-offset-2"> 
      <h1 id="loginPrompt">Sign Up</h1> 
     </div> 
    </div> 
    <form class="form-horizontal" role="form" method="post" 
     action="signup.php"> 
     <div class="form-group"> 
      <label for="inputName" class="col-md-2 col-md-offset-2 control-label">First 
       Name</label> 
      <div class="col-md-4"> 
       <input type="text" class="form-control" id="inputName2" 
        name="firstName" placeholder="John"> 
      </div> 
     </div> 
     <div class="form-group"> 
      <label for="inputName2" 
       class="col-md-2 col-md-offset-2 control-label">Last Name</label> 
      <div class="col-md-4"> 
       <input type="text" class="form-control" id="inputName2" 
        name="lastName" placeholder="Doe"> 
      </div> 
     </div> 
     <div class="form-group"> 
      <label for="inputUserName" 
       class="col-md-2 col-md-offset-2 control-label">Username</label> 
      <div class="col-md-4"> 
       <input type="text" class="form-control" id="inputUserName" 
        name="userName" placeholder="JDoe"> 
      </div> 
     </div> 
     <div class="form-group"> 
      <label for="inputEmail3" 
       class="col-md-2 col-md-offset-2 control-label">Email</label> 
      <div class="col-md-4"> 
       <input type="email" class="form-control" id="inputEmail3" 
        name="email" placeholder="Email"> 
      </div> 
     </div> 
     <div class="form-group"> 
      <label for="inputPassword3" 
       class="col-md-2 col-md-offset-2 control-label">Password</label> 
      <div class="col-md-4"> 
       <input type="password" class="form-control" id="inputPassword3" 
        name="password" placeholder="Password"> 
      </div> 
     </div> 
     <div class="form-group"> 
      <div class="col-md-offset-4 col-md-2"> 
       <button type="submit" name="signUp" class="btn btn-default">Sign Up</button> 
      </div> 
     </div> 
    </form> 
    <div class="container"> 
     <div class = "col-md-8 col-md-offset-2"> 
      <h3 id="signUpMessage"></h3> 
     </div> 
    </div> 
</body> 
</html> 

Login.php:

<?php 


// if(isset($_POST['submit'])) 
// { 
// $Username = $_POST['email']; 
// $email= $_POST['email']; 
// $Password = $_POST['password']; 

// if($user->login($Username,$email,$Password)) 
// { 
//  $user->redirect('home.php'); 
// } 
// else 
// { 
//  $error = "Your Credentials Are Incorrect."; 
// } 
// } 

//login.php 

/** 
* Start the session. 
*/ 
session_start(); 

/** 
* Include ircmaxell's password_compat library. 
*/ 
require 'lib/password.php'; 

/** 
* Include our MySQL connection. 
*/ 
require 'connect.php'; 




//If the POST var "login" exists (our submit button), then we can 
//assume that the user has submitted the login form. 
if($_POST){ 

    //Retrieve the field values from our login form. 
    $userName = !empty($_POST['userName']) ? trim($_POST['userName']) : null; 
    $passwordAttempt = !empty($_POST['password']) ? trim($_POST['password']) : null; 

    //Retrieve the user account information for the given username. 
    $sql = "SELECT UserID, Username, Password FROM users WHERE Username = :username"; 
    $stmt = $pdo->prepare($sql); 

    //Bind value. 
    $stmt->bindValue(':username', $userName); 

    //Execute. 
    $stmt->execute(); 

    //Fetch row. 
    $user = $stmt->fetch(PDO::FETCH_ASSOC); 

    //If $row is FALSE. 
    if($user === false){ 
     //Could not find a user with that username! 
     //PS: You might want to handle this error in a more user-friendly manner! 
     echo 'The username does not exist.'; 
    } else{ 
     //User account found. Check to see if the given password matches the 
     //password hash that we stored in our users table. 

     //Compare the passwords. 
     $validPassword = password_verify($passwordAttempt, $user['Password']); 

     //If $validPassword is TRUE, the login has been successful. 
     if($validPassword){ 
      //Provide the user with a login session. 
      $_SESSION['user'] = $userName; 
      //    return $user['Username']; 
      //   return true; 

      //die('debug'); 
      //Redirect to our protected page, which we called home.php 
      header('Location: home.php'); 

     } else{ 
      echo 'The user credentials do not match.'; 
     } 
    } 

} 

?> 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta charset="utf-8"> 
    <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> 
    <meta name="description" content="Landing Page"> 
    <meta name="author" content="Jordan C. McRae"> 
    <link rel="icon" href="images/favicon.ico"> 

    <title>Login</title> 

    <!-- Bootstrap core CSS --> 
    <link href="css/bootstrap.min.css" rel="stylesheet"> 
    <!-- Login Custom CSS --> 
    <link href="css/login.css" rel="stylesheet"> 
    <!-- Custom styles for this website --> 
    <link href="css/custom.css" rel="stylesheet"> 
    <link href='https://fonts.googleapis.com/css?family=Fugaz+One' rel='stylesheet' type='text/css'> 
    <link href='https://fonts.googleapis.com/css?family=Fjalla+One' rel='stylesheet' type='text/css'> 
</head> 
<body class="body"> 
    <div class="container"> 
     <div class="col-md-8 col-md-offset-2"> 
      <h1 id="loginPrompt">Log In</h1> 
     </div> 
    </div> 
    <form class="form-horizontal" role="form" method="post" 
     action="login.php"> 
    <div class="form-group"> 
    <label for="inputUserName" class="col-md-2 col-md-offset-2 control-label">Username</label> 
     <div class="col-md-4"> 
      <input type="text" class="form-control" id="inputUserName" name="userName" placeholder="JDoe"> 
     </div> 
    </div> 
    <div class="form-group"> 
    <label for="inputPassword3" class="col-md-2 col-md-offset-2 control-label">Password</label> 
    <div class="col-md-4"> 
     <input type="password" class="form-control" id="inputPassword3" name="password" placeholder="Password"> 
    </div> 
    </div> 
    <div class="form-group"> 
    <div class="col-md-offset-4 col-md-2"> 
     <div class="checkbox"> 
     <label> 
      <input type="checkbox"> Remember me 
     </label> 
     </div> 
    </div> 
    </div> 
    <div class="form-group"> 
    <div class="col-md-offset-4 col-md-2"> 
     <button type="submit" name="login" class="btn btn-default">Log in</button> 
    </div> 
    </div> 
</form> 
</body> 
</html> 

home.php:

<?php 


session_start(); 

require 'connect.php'; 
/** 
* Check if the user is logged in. 
*/ 
// if(!isset($_SESSION['user_id']) || !isset($_SESSION['logged_in'])){ 
// //User not logged in. Redirect them back to the login.php page. 
// header('Location: login.php'); 
// exit; 
// } 

if(!isset($_SESSION['user'])){ 
    header("Location: login.php"); } 

    $sql = "SELECT firstName, lastName FROM users WHERE Username = :username"; 
    $stmt = $pdo->prepare($sql); 

    //Bind value. 
    $stmt->bindValue(':username', $_SESSION['user']); 

    //Execute. 
    $stmt->execute(); 

    //Fetch row. 
    $user = $stmt->fetch(PDO::FETCH_ASSOC); 

/** 
* Print out something that only logged in users can see. 
*/ 

echo 'Congratulations! You are logged in!'; 

?> 
<html lang="en"> 
    <head> 
    <meta charset="utf-8"> 
    <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> 
    <meta name="description" content=""> 
    <meta name="author" content=""> 
    <link rel="icon" href="../../favicon.ico"> 

    <title>My Closet</title> 

    <!-- Bootstrap core CSS --> 
    <link href="css/bootstrap.min.css" rel="stylesheet"> 
    <!-- Login Custom CSS --> 
    <link href="css/home.css" rel="stylesheet"> 
    <!-- Custom styles for this website --> 
    <link href="css/custom.css" rel="stylesheet"> 
    <link href="css/animate.css" rel="stylesheet"> 
    <link href='https://fonts.googleapis.com/css?family=Fugaz+One' rel='stylesheet' type='text/css'> 
    <link href='https://fonts.googleapis.com/css?family=Fjalla+One' rel='stylesheet' type='text/css'> 
    </head> 

    <body> 

    <nav class="navbar navbar-inverse navbar-fixed-top"> 
     <div class="container-fluid"> 
     <div class="navbar-header"> 
      <a href="profile.php" class="navbar-brand animated fadeInLeft"><?php echo $user['firstName'], " ", $user['lastName'];?></a> 
     </div> 
     <div id="navbar" class="navbar-collapse collapse"> 
      <ul class="nav navbar-nav navbar-right animated fadeInRight"> 
      <li><a href="home.php">My Closet</a></li> 
      <li><a href="shoe.php">Post Shoes</a></li> 
      <li><a href="#">Settings</a></li> 
      <li><a href="#">Help</a></li> 
      <li><a class="logout" href="index.html">Logout</a><?php session_destroy();?></li> 
      </ul> 
      <form class="navbar-form navbar-right"> 
      <input type="text" class="form-control" placeholder="Find Shoes"> 
      </form> 
     </div> 
     </div> 
    </nav> 

     <div class="col-md-10 col-md-offset-1 home"> 
      <h1 class="home-header">My Closet</h1> 
     <?php 

     ?> 
      <div class="row placeholders"> 
      <div class="col-xs-6 col-sm-3 placeholder"> 
       <img src="data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" width="200" height="200" class="img-responsive" alt="Generic placeholder thumbnail"> 
       <h4>Shoe</h4> 
       <span class="text-muted">Size</span> 
      </div> 
      <div class="col-xs-6 col-sm-3 placeholder"> 
       <img src="data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" width="200" height="200" class="img-responsive" alt="Generic placeholder thumbnail"> 
       <h4>Shoe</h4> 
       <span class="text-muted">Size</span> 
      </div> 
      <div class="col-xs-6 col-sm-3 placeholder"> 
       <img src="data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" width="200" height="200" class="img-responsive" alt="Generic placeholder thumbnail"> 
       <h4>Shoe</h4> 
       <span class="text-muted">Size</span> 
      </div> 
      <div class="col-xs-6 col-sm-3 placeholder"> 
       <img src="data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" width="200" height="200" class="img-responsive" alt="Generic placeholder thumbnail"> 
       <h4>Shoe</h4> 
       <span class="text-muted">Size</span> 
      </div> 
      <div class="col-xs-6 col-sm-3 placeholder"> 
       <img src="data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" width="200" height="200" class="img-responsive" alt="Generic placeholder thumbnail"> 
       <h4>Shoe</h4> 
       <span class="text-muted">Size</span> 
      </div> 
      </div> 

      </div> 
     </div> 
     </div> 
    </div> 

    <!-- Bootstrap core JavaScript 
    ================================================== --> 
    <!-- Placed at the end of the document so the pages load faster --> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
    </body> 
</html> 

そしてprofile.php:

<?php 


session_start(); 

require 'connect.php'; 
/** 
* Check if the user is logged in. 
*/ 
// if(!isset($_SESSION['user_id']) || !isset($_SESSION['logged_in'])){ 
// //User not logged in. Redirect them back to the login.php page. 
// header('Location: login.php'); 
// exit; 
// } 

if (! isset ($_SESSION ['user'])) { 
    header ("Location: login.php"); 
} 

$sql = "SELECT firstName, lastName FROM users WHERE Username = :username"; 
$stmt = $pdo->prepare ($sql); 

// Bind value. 
$stmt->bindValue (':username', $_SESSION ['user']); 

// Execute. 
$stmt->execute(); 

// Fetch row. 
$user = $stmt->fetch (PDO::FETCH_ASSOC); 

/** 
* Print out something that only logged in users can see. 
*/ 

?> 
<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="utf-8"> 
<meta http-equiv="X-UA-Compatible" content="IE=edge"> 
<meta name="viewport" content="width=device-width, initial-scale=1"> 
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> 
<meta name="description" content=""> 
<meta name="author" content=""> 
<link rel="icon" href="../../favicon.ico"> 

<title>Profile</title> 

<!-- Bootstrap core CSS --> 
<link href="css/bootstrap.min.css" rel="stylesheet"> 
<!-- Login Custom CSS --> 
<link href="css/home.css" rel="stylesheet"> 
<!-- Custom styles for this website --> 
<link href="css/custom.css" rel="stylesheet"> 
<link href="css/animate.css" rel="stylesheet"> 
<link href='https://fonts.googleapis.com/css?family=Fugaz+One' 
    rel='stylesheet' type='text/css'> 
<link href='https://fonts.googleapis.com/css?family=Fjalla+One' 
    rel='stylesheet' type='text/css'> 

</head> 

<body> 
    <nav class="navbar navbar-inverse navbar-fixed-top"> 
     <div class="container-fluid"> 
      <div class="navbar-header"> 
       <a href="profile.php" class="navbar-brand animated fadeInLeft"> 
        <?php echo $user['firstName'], " ", $user['lastName'];?> 
       </a> 
      </div> 
      <div id="navbar" class="navbar-collapse collapse"> 
       <ul class="nav navbar-nav navbar-right animated fadeInRight"> 
        <li><a href="home.php">My Closet</a></li> 
        <li><a href="shoe.php">Post Shoes</a></li> 
        <li><a href="#">Settings</a></li> 
        <li><a href="#">Help</a></li> 
        <li><a class="logout" href="index.html">Logout</a> <?php session_destroy();?></li> 
       </ul> 
       <form class="navbar-form navbar-right"> 
        <input type="text" class="form-control" placeholder="Find Shoes"> 
       </form> 
      </div> 
     </div> 
    </nav> 

    <div class="col-md-10 col-md-offset-1 profile"> 
     <h1 class="profile-header"><?php echo $user['firstName'], " ", $user['lastName'];?></h1> 
     <div class="col-md-8 col-md-offset-2"> 
      <h3><?php echo $user['address']?></h3> 
      <h3><?php echo $user['city'], ", ", $user['state'], "", $user['zip']?></h3> 
     </div> 
    </div> 





    <!-- Bootstrap core JavaScript 
    ================================================== --> 
    <!-- Placed at the end of the document so the pages load faster --> 
    <script 
     src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
    <script> 
     window.jQuery 
       || document 
         .write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>') 
    </script> 
    <script src="../../dist/js/bootstrap.min.js"></script> 
    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug --> 
    <script src="../../assets/js/ie10-viewport-bug-workaround.js"></script> 
</body> 
</html> 

私が言ったように、私はPHPにはまだまだ慣れていません。私は投稿する前に同様の質問を見ましたが、まだ固執して混乱しています。何かとすべてが役に立ちます。親切にありがとう。

UPDATE:私は誰かがユーザーのための12時間のセッションを持っているかについてのスタックオーバーフローのここに別のポストを見て、私は自分のコードに似た何かを実装しようとしましたが、PHPはセッションだった私に言い続け

私はまだ他のページを試してみたので私はまだログアウトしていたので、まだそれを理解しようとしていますが、まだ成功していません。

+0

まず、エラーをチェックし、 'var_dump()'を少し実行します。また、各ヘッダの後に 'exit;'を追加する必要があります。それ以外の場合は、コードを実行し続けることができます。 –

+0

だから、私は 'var_dump($ _ SESSION ['user'])'をしたいでしょうか? –

+0

Home.phpを開いてブラウザのF5キーを押すとどうなりますか? – NineBerry

答えて

1

問題はここにあなたのhome.phpprofile.phpである:

<li><a class="logout" href="index.html">Logout</a><?php session_destroy();?></li> 

ページは、そうするたびにレンダリングされている間、あなたが期待するように、ユーザーがリンクをクリックしたときにsession_destroy()への呼び出しは、いない実行されます。あなたはsession_destroy()へのコールを削除する必要があります。代わりに、ログアウトのために別の特定のページにリンクしてください。

+0

それは問題でした!すべてのあなたの助けをありがとう、@NineBerry! –

関連する問題