Login.php
<?php
session_start();
$server = "localhost";
$user = "...";
$pass = "...";
$database = "...";
$verbindung = mysqli_connect($server, $user, $pass, $database)
or die("Verbindung konnte nicht hergestellt werden.");
$Email = $_POST["Email"];
$Passwort = $_POST["Passwort"];
$sql = "SELECT passwort FROM accounts WHERE email = '".$Email."'";
$hashPasswort = mysqli_query($verbindung, $sql);
$VerifyHash = mysqli_fetch_assoc($hashPasswort);
if(password_verify($Passwort, $VerifyHash['passwort']))
{
session_regenerate_id();
$_SESSION['email'] = $Email;
echo "<script type='text/javascript'>
window.location.replace('...');
</script>";
}
else
{
echo '<script type="text/javascript">
window.location.replace("...");
</script>';
}
$return = mysqli_close($verbindung);
if (!$return) {
echo "<p>Die Verbindung mit dem Server konnte nicht geschlossen werden.</p>";
}
?>
Index.php
<?php
session_start();
if (!isset($_SESSION['email'])) {
header('Location: Login.php?login=loginRequired');
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=0.85">
<link rel="icon" type="image/png" href="../Bilder/favicon.ico"/>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Erste-Hilfe Kurs</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel='stylesheet' type='text/css' media='screen' href='../CSS/main.css'>
<link rel='stylesheet' type='text/css' media='screen' href='../CSS/index.css'>
</head>
<body>
<header>
<div class="container">
<img src="../Bilder/Litec.png" alt="Litec" class="logo">
<img src="../Bilder/RotesKreuz2.png" alt="Litec" class="logo">
<nav>
<ul>
<li><b><u>Home</u></b></li>
<li>Über uns</li>
<li>Anmeldung</li>
<li>Impressum</li>
<li>LOGOUT</li>
</ul>
</nav>
</div>
</header>
<label id="email"></label>
<?php echo("{$_SESSION['email']}"."<br />");?>
</body>
</html>
I made a Login script which opens, if the password is correct, the Index.php site. When first opening the Index.php site via the Login script everything works fine and the session is set. But after I refresh the page the sessions gets destroyed and is not set.
So how can I save the session, so it's not getting destroyed by refreshing the browser?
This line in your index.php destroys your session:
<li>LOGOUT</li>
^^^^^^^^^^^^^^^^^
To realize your logout process, you could link to another php file and do your session_destroy(); there - for example.
Related
I'm building a simple login system.
Registration is working with password_default:
So, now the login. This is my login class:
<?php
include("../Controllers/DatabaseController.php");
class LoginModel extends DatabaseController
{
protected $dbconn;
public function __construct()
{
$this->dbconn = DatabaseController::instance();
}
public function Login()
{
$db = $this->dbconn->pdo;
try {
$username = $_POST['username'];
$passwordAttempt = $_POST['user_password'];
//Retrieve the user account information for the given username.
$sql = "SELECT * FROM user WHERE username = :username";
$stmt = $db->prepare($sql);
//Bind value.
$stmt->bindParam(':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!
?>
<script type="text/javascript">
alert("username not found!");
window.location.href = "../Views/login.php";
</script>
<?php
} else {
//User account found. Check to see if the given password matches the
//password hash that we stored in our users table..
$validPassword = password_verify($passwordAttempt, $user['user_password']);
//If $validPassword is TRUE, the login has been successful.
if ($validPassword) {
//Provide the user with a login session.
$_SESSION['id'] = $user['id'];
$_SESSION['logged_in'] = time();
//Redirect to our protected page, which we called home, to see if we are provided a session.php
?>
<script type="text/javascript">
alert("You're logged in!");
window.location.href = "../index.php";
</script>
<?php
header('Location: home.php');
exit;
} else {
//$validPassword was FALSE. Passwords do not match.
?>
<script type="text/javascript">
alert("Password is incorrect!");
window.location.href = "../Views/login.php";
</script>
<?php
}
}
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
}
Now I know, it isn't proper OOP, but I'm learning.
When I press login, passwords do match:
But when redirecting to home.php, it seems the log in didn't provide me with a session_id...
Home.php:
<?php
/**
* Start the session.
*/
session_start();
/**
* Check if the user is logged in.
*/
if(!isset($_SESSION['id']) || !isset($_SESSION['logged_in'])){
//User not logged in. Redirect them back to the login.php page.
?>
<script type="text/javascript">
alert("You're not logged in!" );
</script>
<?php
exit;
}
/**
* Print out something that only logged in users can see.
*/
echo 'Congratulations! You are logged in!';
I hope somebody has a solution, because I don't see one unfortunately.
For completion my partial login.php:
<?php
include "../Models/LoginModel.php";
$login = new LoginModel();
?>
<?php
if (isset($_POST["submit"])) {
$login->Login();
}
?>
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<title>Title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="../style-registration.css">
</head>
<body>
<?php
include 'header.php';
?>
<div class="signup-form">
<form action="" method="post">
And my partial header.php:
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<title>Scores Website</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="../style-index.css">
</head>
<body>
<nav class="navbar navbar-expand-xl bg-light">
Try to end with that kind of structure :
<?php
include "../Models/LoginModel.php";
session_start();
if ($_POST) {
//execute login method
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
//set title, meta, call needed css files
</head>
<body>
//your form etc...
//end with javascript calls
</body>
</html>
In this order everything should works as expected.
So I was able to make a code work where if the user is an Admin in the database, the link 'ADMIN' shows. However, when no one is logged in, it shows that part of the code to determine if the user is admin is undefined index.
How do I make it so that it doesnt show the undefined index when no one is logged in?
<?php
session_start();
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="HandheldFriendly" content="True">
<link rel="stylesheet" type="text/css" media="screen" href="css/masthead.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/styles.css" />
</head>
<body>
<nav>
<div class="brand">
<h1>HOME PAGE</h1></div>
<ul>
<li>BOOKS</li>
<li>STORIES</li>
<li>QUOTES</li>
<li>UPLOAD</li>
<li>REGISTER</li>
<li>CONTACT ME</li>
<?php
$dbserverName = "localhost";
$dbuserName = "root";
$dbpassword = "";
$dbname = "database";
$db = mysqli_connect( $dbserverName , $dbuserName , $dbpassword , $dbname );
$value = $_SESSION['u_id'];
$sql = "SELECT admin, user_id FROM users WHERE username='".$value."'";
$result = mysqli_query($db,$sql);
if ($row = mysqli_fetch_assoc($result)) {
$user_id = $row['user_id'];
$u_admin = $row['admin'];
if ($u_admin === "Y") {
print '<li>admin</li>';
}
}
?>
<?php
if (isset($_SESSION['u_id'])) {
print '<form action = "includes/logout.inc.php" method="POST">
<button type="submit" name="logout">LOGOUT</button>
</form>';
}
else {
print '<form action = "includes/login.inc.php" method="POST">
<button type="submit" name="logout">LOGIN</button>
</form>';
}
?>
</ul>
</nav>
<section class="sec1"></section>
<section class="sec2"></section>
</div>
</ul>
</nav>
</div>
</header>
<main container class="siteContent">
<!-- BEGIN CHANGEABLE CONTENT. -->`enter code here`
I am stuck....I have tried different if statements with a variable equal to true instead...but that doesnt work.
I forgot to add the the error is at when I run the code. It doesnt show when the user is logged in, just when no one is logged in.
$value = $_SESSION['u_id'];
You need to check if array values are set before using them. Something like this
$u_admin = isset($row['admin']) ? $row['admin'] : false
If you are using php 7, you can shorten this with the null coalescing operator
$u_admin = $row['admin'] ?? false
This assigns your variable if it's set, otherwise it assigns it as the second value.
Right now I'm coding this really simple user page but getting one problem that's bugging me and can't find out why it's happening.
When ever I would put <?php HTML will just stop loading from there.
<?php
session_start();
if (!isset($_SESSION["user"])) {
$logged_in = "no";
} else {
$username = $_SESSION["user"];
$logged_in = "yes";
}
include ('global.php');
?>
<head>
<title><?php echo $sitename; ?></title>
<link rel="stylesheet" type="text/css" href="css.css">
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="header">
<div class="header_content">
<div class="middle_logo">
<p><?php echo $sitename; ?></p>
</div>
</div>
</div>
<div class="under_header">
<?php
$id = htmlentites($_GET["id"]);
$get_user_data = mysqli_query ($dconnect, "SELECT * FROM user_data WHERE id='$id'");
if (mysqli_num_rows($get_user_data) < 2) {
header ("Location: index.php");
} else {
while ($row = mysqli_fetch_array($get_user_data)) {
echo $row["username"];
}
}
?>
<h1><?php echo $users_name; ?></h1>
</div>
When I look at the source code it ends at <div class="under_header">
The answer has already been found in the comment :
The line :
$id = htmlentites($_GET["id"]);
Contain an error and should be :
$id = htmlentities($_GET["id"]);
Thanks to #RiggsFolly and #JustOnUnderMillions.
You can now accept an answer and close the question.
I have three pages on my site index (login page) Home (navigation) Project Creation and Management (informational) now after login there is no issues however when I try going from home to Project Creation and Management it seams like I'm instantly getting redirected back to the home page. It does the same thing via url entry or the navigation from the home page. Here's my code:
index
<!DOCTYPE html>
<?php
session_start();
$username = "admin";
$password = "collins1";
if (isset($_GET['logout'])){
session_destroy();
}
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
header("Location: home.php");
}
if (isset($_POST['username']) && isset($_POST['password'])){
if ($_POST['username'] == $username && $_POST['password'] == $password)
{
$_SESSION['loggedin'] = true;
header("Location: home.php");
}
else
{
echo '<font color="#FF0000"><p align="center">Username or Password incorrect please try again</p></font>';
}
}
?>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Login</title>
<link href="../CSS/boilerplate.css" rel="stylesheet" type="text/css">
<link href="../CSS/master.css" rel="stylesheet" type="text/css">
<script src="../JAVASCRIPT/respond.min.js"></script>
</head>
<body link="black">
<div class="gridContainer clearfix">
<div id="borderDiv">
<div id="headerDiv">
<p>Welcome</p>
</div>
<div id="subHeaderDiv">
<p>Please login to continue to the Project Creation and Management System</p>
</div>
<form method="post" action="index.php">
<div id="userNameLoginDiv">
<p>Username:</p>
<input type="text" name="username" size="12">
</div>
<div id="userPasswordLoginDiv">
<p>Password:</p>
<input type="password" name="password" size="12">
</div>
<div id="loginBtnDiv">
<input id="button" type="submit" value="Login">
</div>
</form>
</div>
</div>
</body>
</html>
home
<!DOCTYPE html>
<?php
session_start();
if (isset($_GET['logout'])){
session_destroy();
}
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] == false) {
header("Location: index.php");
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Home</title>
<link href="../CSS/boilerplate.css" rel="stylesheet" type="text/css">
<link href="../CSS/master.css" rel="stylesheet" type="text/css">
<script src="../JAVASCRIPT/respond.min.js"></script>
</head>
<body link="black">
<div class="gridContainer clearfix">
<div id="headerDiv">
<p>Home</p>
</div>
<font color="#000000">Logout</font>
<div id="homeBtn1"> <img src="../button.png" alt="Project Creation and Management">
<div id="homeBtnText1">
<font color="#000000" ><p>Project Creation and Management<p></font>
</div>
</div>
</div>
</body>
</html>
Project Creation and Management
<!DOCTYPE html>
<?php
session_start();
if (isset($_GET['logout'])){
session_destroy();
}
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] == false) {
header("Location: index.php");
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Home</title>
<link href="../CSS/boilerplate.css" rel="stylesheet" type="text/css">
<link href="../CSS/master.css" rel="stylesheet" type="text/css">
<script src="../JAVASCRIPT/respond.min.js"></script>
</head>
<body link="black">
<div class="gridContainer clearfix">
<div id="headerDiv">
<p>Project Creation & Management</p>
</div>
<font color="#000000">Logout</font>
</div>
</body>
</html>
you should edit your code below
<?php
session_start();
$username = "admin";
$password = "collins1";
if (isset($_GET['logout'])){
session_destroy();
}
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
header("Location: home.php");
}
if (isset($_POST['username']) && isset($_POST['password'])){
if ($_POST['username'] == $username && $_POST['password'] == $password)
{
$_SESSION['loggedin'] = true;
header("Location: home.php");
}
else
{
echo '<font color="#FF0000"><p align="center">Username or Password incorrect please try again</p></font>';
}
}
?>
...
Because session_start() have to above every output-string. You printed <!DOCTYPE html> that make session cannot start
The session_start(); must go above all else in all pages. Otherwise, the session variables cannot be created and saved. For that reason, the second if in your Project Creation and Management page will be called. That's the problem!
I am trying to get echo $userRow['student_firstname']; to pass into the html so I can use it as a automatic way to change displaying the users first name & logout with register & login. The first echo $userRow['student_firstname']; does work, however the second does not. The idea would be able to get the second to work, so I can remove the first. If there isn't a session then it displays the login & register.
<?php
session_start();
include_once 'dbconnect_new.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimal-ui">
<link href="favicon.png" type="image/x-icon" rel="shortcut icon">
<link href="assets/css/master.css" rel="stylesheet">
<script src="assets/plugins/jquery/jquery-1.11.3.min.js"></script>
</head>
<?php if(isset($_SESSION['user'])) {
// error_reporting(E_ALL ^ E_DEPRECATED);
$res=mysql_query("SELECT * FROM studentdata WHERE student_id=".$_SESSION['user']);
if ($res === FALSE){
die(mysql_error());
}
while($userRow=mysql_fetch_array($res))
{
echo $userRow['student_firstname'];
}
?>
<li class="dropdown">
<a href="">
<?php echo $userRow['student_firstname'];?><span class="nav-subtitle">Account</span></a</li>
<li>Logout<span class="nav-subtitle">Goodbye</span></li>
<?php } else { ?>
<li>Register<span class="nav-subtitle">for Students</span></li>
<li>Login<span class="nav-subtitle">for Students</span></li>
<?php } ?>
</html>
Check this link out http://php.net/manual/en/function.mysql-fetch-array.php,
Tip: USE mysqli/pdo as mysql is deprecated.
<?php
session_start();
include_once 'dbconnect_new.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimal-ui">
<link href="favicon.png" type="image/x-icon" rel="shortcut icon">
<link href="assets/css/master.css" rel="stylesheet">
<script src="assets/plugins/jquery/jquery-1.11.3.min.js"></script>
</head>
<?php
if (isset($_SESSION['user'])) {
// error_reporting(E_ALL ^ E_DEPRECATED);
$res = mysql_query("SELECT * FROM studentdata WHERE student_id=" . $_SESSION['user']);
if ($res === FALSE) {//IF QUERY RETURNS NULL
die(mysql_error());
} else {
$userRow = mysql_fetch_array($res, MYSQL_ASSOC); //DATA IN ARRAY TYPE
//IF BELOW DOES NOT WORK USE print_r(); to check the structure of array !
?>
<li class="dropdown">
<?php echo $userRow['student_firstname']; //ACCESS DATA THROUGH ITS INDEX ?><span class="nav-subtitle">Account</span>
</li>
<li>
Logout<span class="nav-subtitle">Goodbye</span>
</li>
<?php
}
} else {
?>
<li>Register<span class = "nav-subtitle">for Students</span></li>
<li>Login<span class = "nav-subtitle">for Students</span></li>
<?php } ?>
</html>
I Hope this works !