What I'm Trying To Do
I'm creating a single-page members' area with a login form.
When logged in, the only thing the user should see (at this stage) is a button to logout.
What's going wrong
Whenever there is a match in the database (e.g. the username is correct, or both username and password are correct) there is a 500 Server Error
.
Refreshing the page, regardless of if the password is a match, the user gets logged in.
When the user clicks the Logout link, there is also a 500 Server Error
.
The Code
<?php
session_start();
if(isset($_GET['logout'])&&$_GET['logout']==='true'){
logout();
header('location: ./');
}
if(isset($_POST['submit'])) {
$email = $_POST['email'];
$password = $_POST['password'];
$hostname = 'REDACTED';
$username = 'REDACTED';
$password = 'REDACTED';
$dbname = 'REDACTED';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
}
catch(PDOException $e){
echo($e->getMessage());
}
$stmt=$dbh->prepare('SELECT `password`, `id` FROM `tap_users` WHERE `email`=?');
$stmt->execute(array($email));
if($stmt->rowCount()==0){
//incorrect username
header('location: ./?error=user');
exit();
}
$userData = $stmt->fetch(PDO::FETCH_ASSOC);
if($password != $userData['password']) {
//incorrect password
header('location: ./?error=pass');
exit();
} else {
validateUser($userData['id']);
header('location: ./');
}
}
?>
<head></head>
<body>
<?php
if(!isLoggedIn()) {
show_login();
exit();
}
?>
<a href="?logout=true">Logout</a>
</body>
</html>
<?php
//Show login form
function show_login(){
echo '<form method="post">
<input type="text" name="email" placeholder="Email Address" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Submit" name="submit" />
</form>
</body>
</html>';
}
//Check if a user is logged in
function isLoggedIn(){
if(isset($_SESSION['valid']) && $_SESSION['valid'])
return true;
return false;
}
//validate the user
function validateUser($userid){
//this is a security measure
session_regenerate_id();
$_SESSION['valid'] = 1;
$_SESSION['userid'] = $userid;
}
//logout the user
function logout(){
//destroy all of the session variables
$_SESSION = array();
session_destroy();
}
?>
what you are doing is if user login is correct then you are redirecting to header('location: ./'); Maybe either you dont have index.php or directory index is off in your apache configuration.
do one thing change it to
header('location:index.php');
it will work.
this is not related to php or mysql, it is server configuration error.