Web location read from mysql database by sessionID - php

this is my problem. each user should have specific "dashboard" and they should be blocked if user is not logged in. So user1 ==> login==> go to dasboard 1 etc. Dashboard locations are saved in mysql database in specific field. I am using login/sigup form in php and this works. when user is logged comes to welcome page.I want add iframe/content from link in db to be visible for that session user.
I tried loading session element, and displaying it but it dont works and I dont get any errors.
if($stmt->execute()){
// Check if username exists, if yes then verify password
if($stmt->rowCount() == 1){
if($row = $stmt->fetch()){
$id = $row["id"];
$page = $row["location"];
$username = $row["username"];
$hashed_password = $row["password"];
if(password_verify($password, $hashed_password)){
// Password is correct, so start a new session
session_start();
// Store data in session variables
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
$_SESSION["location"] = $page;
// Redirect user to welcome page
header("location: welcome.php");
and this is welcome.php
<?php
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: log.php");
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
body{ font: 14px sans-serif; text-align: center; }
</style>
</head>
<body>
<div class="page-header">
<h1>Hi, <b><?php echo htmlspecialchars($_SESSION["username"]); ?> </b>. Welcome to our site.</h1>
</div>
<?php echo $_SESSION ["location"]; ?>
<p>
Reset Your Password
Sign Out of Your Account
</p>

Related

Missing responsiveness for button

I'm new to php and backend, I tried making a login and I wanted to buttons to change the background colour. Instead of using javascript, I use php to program it, to create sessions.
Below is the code. The buttons work in the url bar, but nothing is happening.
What am I missing or overseeing?
<?php
// Initialize the session
session_start();
require_once "config.php";
session_start();
require_once "config.php";
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
$sql = "SELECT background FROM users ORDER BY id DESC";
$backgroundColour = [];
$colour = [];
$result = $link->query($sql);
$data = [];
while ($row = $result -> fetch_object()) {
$data[] = $row;
}
$backgroundColour['backgroundColour'] = $data;
$_SESSION['colour'] = $colour;
if(isset($_GET['colour'])){
$colour = $_GET['colour'];
$_SESSION['colour'] = $colour;
}
$colour_session = $_SESSION['colour'];
$sql = "INSERT INTO users (background) VALUES ('$colour_session')";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<h1>Choose background color</h1>
Hvid
Sort
</div>
<title>Welcome</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
body{ font: 14px sans-serif; text-align: center; }
</style>
</head>
<body>
<h1 class="my-5">Hi, <b><?php echo htmlspecialchars($_SESSION["username"]); ?></b>. Welcome to our site.</h1>
<p>
Reset Your Password
Sign Out of Your Account
</p>
</body>
</html>
At least you need to tell the client side (the browser) that the background color is set as $_SESSION["color"] (e.g. black)
So, one of the ways is to add the following line to the end of your script (your script already has <body></body>) :
<?php
echo '<script>document.body.style.backgroundColor = "'. $_SESSION['colour'] . '";</script>';
?>
So, omitting the db part, the code (tested, fully working) will be
<?php
session_start();
if(isset($_GET['colour'])){
$colour = $_GET['colour'];
$_SESSION['colour'] = $colour;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<h1>Choose background color</h1>
Hvid
Sort
</div>
</body>
<?php
echo '<script>document.body.style.backgroundColor = "'. $_SESSION['colour'] . '";</script>';
?>
For the db part:
You may need to re-write the part on the db queries. For example, apart from the need to use parameterized prepared statement in your query (to avoid SQL injection attacks). Consider using "update user set background=? where id=?" instead of an insert query, For a multi-user system, it will be something like:
$sql = "UPDATE users SET background=? WHERE id=?";
$stmt= $link->prepare($sql);
$stmt->bind_param("si", $_SESSION['colour'], $_SESSION["id"]);
$stmt->execute();
It is because each user should have only a single record in the db table (so logically it is an update instead of an insert).

Why doesn't login provide me a session_id()?

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.

Sessions In PHP not working

okay so I am getting users to sign in and then "if successful" I redirect them to index.php where I would like to display some info from the database.
my users are validated and I can log in but I think I having issues with the Session.
The user name session does not display any info when I call it on the index.php page.
I am new to php and learning as I go. I have spent the last two days browsing this site for answers to my issue, but can't find anything that really works.
Here is the code
checklogin.php
<?php
session_start();
ob_start();
include_once 'config.php';
// Connect to server and select databse.
try
{
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$db = new PDO('mysql:host='.$host.';dbname='.$db_name.';charset=utf8', $username, $password);
}
catch(Exception $e)
{
die('Error : ' . $e->getMessage());
}
// Define $myusername and $mypassword
$myusername = $_POST['myusername'];
$mypassword = $_POST['mypassword'];
// To protect MySQL injection
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$stmt = $db->query("SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'");
// rowCount() is counting table row
$count = $stmt->rowCount();
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1){
// Register $myusername, $mypassword and print "true"
echo "true";
$_SESSION['username'] = 'myusername';
$_SESSION['password'] = 'mypassword';
}
else {
//return the error message
echo "<div class=\"alert alert-danger alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>Wrong Username or Password</div>";
}
ob_end_flush();
?>
index.php
<?php
session_start();
if(!isset($_SESSION['username'])){
header("location:main_login.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="css/bootstrap.css" rel="stylesheet" media="screen">
<link href="css/main.css" rel="stylesheet" media="screen">
</head>
<body>
<div class="container">
<div class="form-signin">
<div class="alert alert-success">You have been <strong>successfully</strong> logged in <?php echo $_SESSION['username']; ?>.</div>
Logout </div>
</div>
<!-- /container -->
</body>
</html>
I would really appreciate any help or links to articles that can help.
Thanks
Sean
Just change $_SESSION['username'] = 'myusername'; to $_SESSION['username'] = $myusername;

Fetch row and display using sessions

been working on this project where I want people to login and when successful see info that we get from the database. I am not sure how to get the user email and other data stored to session
My problem is that I am struggling to store the data in sessions. I can sign in and echo the username that I created a session for, but the other data is not working.
I have gone through stacks of stuff on here, but obviously I am a little lost.
Here is the code for my checklogin.php
<?php
session_start();
ob_start();
include_once 'config.php';
// Connect to server and select databse.
try
{
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$db = new PDO('mysql:host='.$host.';dbname='.$db_name.';charset=utf8', $username, $password);
}
catch(Exception $e)
{
die('Error : ' . $e->getMessage());
}
// Define $myusername and $mypassword
$myusername = $_POST['myusername'];
$mypassword = $_POST['mypassword'];
$myemail =
// To protect MySQL injection
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$stmt = $db->query("SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'");
// rowCount() is counting table row
$count = $stmt->rowCount();
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1){
// Register $myusername, $mypassword and print "true"
echo "true";
$_SESSION['username'] = $myusername;
$_SESSION['email'] = $myemail;
}
else {
//return the error message
echo "<div class=\"alert alert-danger alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>Wrong Username or Password</div>";
}
ob_end_flush();
?>
and then my index.php looks like this
<?php
session_start();
if(!isset($_SESSION['username'])){
header("location:main_login.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="css/bootstrap.css" rel="stylesheet" media="screen">
<link href="css/main.css" rel="stylesheet" media="screen">
</head>
<body>
<div class="container">
<div class="form-signin">
<div class="alert alert-success">You have been <strong>successfully</strong> logged in as <?php echo $_SESSION['username']; ?>. Your email is <?php echo $row['email']; ?></div>
Logout </div>
</div>
<!-- /container -->
</body>
</html>
Note that on index.php the username works fine when I echo it, but not the email.
Any help would be appreciated
This is supposed to be a comment, but i have a low reputation here.
First of all, please consider binding your values. PDO luckily has that functionality.Also as an observation, stripslashes does not totally prevent SQL injection.
From what i see, your email address is not saved in any session variable. This should fix,
$myemail = $_SESSION['name_of_email_from_database'];
Also do not forget, to access your session variables, include session_start() on every page that needs it. To prevent PHP's warning message of too many session starts, add the following code:
<?php
if(!isset($_SESSION)){
session_start();
}
?>
You can use query here to get all data for the session user, by select query.
$q= "select * from user where username = '$yoursessionusername'"
By this query you will get all details for the loggedin user.
Can create one session.php with below code:
session_start();
$username=$_SESSION['username'];
$email=$_SESSION['email'];
and can use those variables to your page.

php redirect when wrong password

is this right the code will redirect a person to the login page when they try to access it using without going into the login page
<?php
$pass = 'password';
?>
<html>
<head>
<title></title>
</head>
<body>
<?php
if ( $_POST["pass"] == $pass){
?>
Congrats you have log in!
<?php
}else{
header("Location: http://signin.com/");
}
?>
</body>
</html>
i ended up having a "Server error
The website encountered an error while retrieving http://www.test.com It may be down for maintenance or configured incorrectly."
You can't call header after you've already outputted some HTML. Do your password checks & redirect. above the HTML
Eg:
<?php
$pass = 'password';
if ( $_POST["pass"] != $pass){
header("Location: http://signin.com/");
exit;
}
?>
<html>
<head>
<title></title>
</head>
....
So the HTML will only show if they're successful.
You can't send a header() after any output to the user:
<?php
$pass = 'password';
if ( $_POST["pass"] == $pass)
{
?>
<html>
<head>
<title></title>
</head>
<body>
Congrats you have log in!
</body>
</html>
<?php
}
else
{
header("Location: http://signin.com/");
}
?>
Something like this would work better:
<?php
$pass = 'password';
if ($_POST["pass"] != $pass){
header("Location: http://signin.com/");
exit;
}
?>
<html>
<head>
<title></title>
</head>
<body>
Congrats you have log in!
</body>
</html>
You need to check if the user is logged in. If not, redirect and exit. If so, display the message.
Put ob_start(); at the top and ob_end_flush(); and that might fix it.
You can't output html before make a redirect with header. Code all logic before:
<?php
$pass = 'password';
if ($_POST["pass"] == $pass)
{
$message = "Congrats you have log in!";
}
else
{
header("Location: http://signin.com/");
}
?>
<html>
<head>
<title></title>
</head>
<body>
<?php echo $message; ?>
</body>

Categories