2016-04-16 10 views
1

Für ein Projekt, das ich mache, verwende ich PHP, zu dem ich noch sehr neu bin. Wenn sich ein Benutzer anmeldet oder anmeldet, wird er auf die Homepage geleitet, wo ich ihn mit $_SESSION anmelde. $_SESSION['user'] wird verwendet, wenn die Sitzung ihren Benutzernamen speichert. Aber wenn ich versuche, von der Startseite auf die Profilseite zu wechseln (zu der sie durch Klicken auf ihren Namen klicken), schickt sie mich zurück zum Anmeldebildschirm und protokolliert sie effektiv, als ob sie keine Sitzung hätten nicht mehr. Ich schaute auf meinen Code und ich weiß nicht, was ich falsch mache oder nicht mache. Kann mir jemand sagen, was falsch ist und wie ich meine Benutzer beim Navigieren auf anderen Seiten anmelden kann?Benutzer wird abgemeldet, Seiten zu wechseln

Hier ist meine 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> 

Und 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> 

Wie ich schon sagte, bin ich noch neu in PHP, und ich habe mir ähnliche Fragen angesehen, bevor ich meins gepostet habe, aber ich bin immer noch fest und verwirrt. Alles und jedes wird helfen. Dankesehr.

UPDATE:

ich in einem anderen Beitrag hier auf Stack-Überlauf sah, wie jemand eine 12-Stunden-Sitzung für Benutzer hat, und ich versuchte, etwas Ähnliches zu meinen Code zu implementieren, aber PHP mir immer wieder gesagt eine Sitzung war hat bereits begonnen, und es hat mich immer noch ausgeloggt, als ich andere Seiten ausprobierte, also versuche ich immer noch, es herauszufinden, aber ich mache immer noch keinen Erfolg.

+0

starten durch Überprüfung auf Fehler und ein wenig von 'var_dump()' 'ing. Sie sollten nach jedem Header auch 'exit;' hinzufügen. Andernfalls möchte Ihr Code möglicherweise weiterhin ausgeführt werden. –

+0

Also, würde ich 'var_dump ($ _ SESSION ['user'])' 'dann tun? –

+0

Was passiert, wenn Sie in der Home.php sind und F5 im Browser drücken? – NineBerry

Antwort

1

Das Problem ist in Ihrem home.php und profile.php hier:

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

Der Aufruf von session_destroy() ausgeführt wird, während die Seite gerendert wird, so dass jedes Mal, nicht, wenn der Benutzer klickt auf den Link, wie Sie es erwarten. Sie müssen den Anruf zu session_destroy() dort entfernen. Klicken Sie stattdessen auf eine andere bestimmte Seite zum Abmelden.

+0

Das war das Problem! Danke für deine Hilfe, @NineBerry! –

Verwandte Themen