How come the user name is not shown? - php

I wrote some simple login script for a school assignment. I need to ask the user to log in redirect them to the main page, and display their username on top of the main page. I've been following the instructions I found online, but the username is not shown in the main page after the user logged in. Can someone take a look at my PHP code and give me some hints on how to resolve this? Thanks!
Here is my main php:
<?php
session_start();
echo "You are logged in as " .$_SESSION['username'];
echo "<p>Click here to logout</p>";
//Turn on error reporting
ini_set('display_errors', 'On');
//Connects to the database
$mysqli = new mysqli("abc", "edf","xyz", "123");
if($mysqli->connect_errno){
echo "Connection error: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Test</title>
<meta charset="UTF-8">
<style type="text/css">
body {font-family:sans-serif;}
h1 {color: #0000FF;text-align: center;}
.fieldset-auto-width {display: inline-block;}
</style>
</head>
<body>
<div id="header" style="background-color:#FFA500;">
<h1>Restaurant Review</h1>
</div>
//DO SOMETHING HERE
<div id="content">
<form method="post" action="addreview.php">
</div>
</form>
</body>
</html>
Here is my login php
<?php
ob_start();
$username = $_POST['username'];
$password = $_POST['password'];
//Turn on error reporting
ini_set('display_errors', 'On');
//Connects to the database
$mysqli = new mysqli("abc", "edf","xyz", "123");
if($mysqli->connect_errno){
echo "Connection error " . $mysqli->connect_errno . " " . $mysqli->connect_error;
}
$username = mysqli_real_escape_string($mysqli, $username);
$query = "SELECT password, salt FROM member WHERE username = '$username';";
$result = mysqli_query($mysqli, $query);
// User not found. So, redirect to login_form again.
if (mysqli_num_rows($result) == 0)
{
header('Location: login.html');
}
$userData = mysqli_fetch_array($result, MYSQL_ASSOC);
$hash = hash('cs494', $userData['salt'] . hash('cs494', $password));
//Incorrect password. Redirect to login form again
if ($hash != $userData['password'])
{
header('Location: login.html');
}else {
//redirect to main page after successful login
session_start();
$_SESSION['username'] = $username;
header('Location: main.php');
}
?>

You are echo-ing outside of the HTML document, and it is probably on the page where you cannot see it. If you click View > Source you might see it printed at the top of the document before the <!DOCTYPE> declaration.
Instead of:
echo "You are logged in as " .$_SESSION['username'];
echo "<p>Click here to logout</p>";
<!DOCTYPE html>
<html>...</html>
You should move the echo inside the document like:
<!DOCTYPE html>
<html>
<head>...</head>
<body>
<?php
echo "You are logged in as " .$_SESSION['username'];
echo "<p>Click here to logout</p>";
?>
...
</body>
</html>

Related

Can't call dynamic page with $_GET

I'm trying to use $_GET to call a dynamic page, but it throws "Error". Do I need to call page 1 from page 2 or why can't they talk to each other?
Thanks in advance for your help, supposingly there's an easy solution.
/Jimmy
This is page 1:
<!DOCTYPE html>
<html>
<head>
<title>Players</title>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
<?php include ("header.php"); ?>
<?php
$servername = "localhost";
$username = "jim";
$password = "pass";
$dbname = "jim";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL search
$sql = "SELECT PlayerID, Person FROM People where PlayerID is not null ORDER BY Person";
$result = $conn->query($sql);
// Condition
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Player</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>"."<a href='spelarfakta.php?=id{$row['PlayerID']}'>{$row['PlayerID']}</a>"."</td>"."<td>".$row["Person"]."</td>";
}
echo "</table>";
} else {
echo "No hits";
}
$conn->close();
?>
</body>
</html>
This is page 2:
<!DOCTYPE html>
<html>
<head>
<title>Player Stats</title>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
<?php include ("header.php");
if (isset($_GET['id'])) {
echo '<p>'. $_GET['id'].'</p>';}
else {echo 'Error';
}
?>
</body>
</html>
Correct solution as a comment:
=id should be id=

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.

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>

Display username once user has logged in

Hello i am try to display the username after they log in.
here is my code
This is the page i would like to show it.
index.php
<?php
require_once 'classes/Membership.php';
$membership = New Membership();
$membership->confirm_Member();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Home Page</title>
<link href="css/me.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top">
</div>
<div id="top-register">
<?
$_SESSION['username']
?>
<a href="login.php?status=loggedout">
Log Out </a>
</div>
<div id="top-login">
</div>
<div id="line">
<div id="banner-text">
Testing
</div>
<div id="banner">
</div>
</div>
<center>
<div id="plan">
<div id="plan-innder">
<img src="images/plan/starter.png" alt="Starter" width="250" height="300" />
<img src="images/plan/regular.png" alt="Regular" width="250" height="300" />
<img src="images/plan/advanced.png" alt="Advanced" width="250" height="300" />
</div>
</div>
enter code here
</center>
</body>
</html>
The workings
membership.php
<?php
require 'Mysql.php';
class Membership {
function validate_user($un, $pwd) {
$mysql = New Mysql();
$ensure_credentials = $mysql->verify_Username_and_Pass($un, md5($pwd));
if($ensure_credentials) {
$_SESSION['status'] = 'authorized';
header("location: index.php");
} else return "Please enter a correct username and password";
}
function log_User_Out() {
if(isset($_SESSION['status'])) {
unset($_SESSION['status']);
if(isset($_COOKIE[session_name()]))
setcookie(session_name(), '', time() - 1000);
session_destroy();
}
}
function confirm_Member() {
session_start();
if($_SESSION['status'] !='authorized') header("location: login.php");
}
}
Mysql.php
This is what is connecting to the data base.
require_once 'includes/constants.php';
class Mysql {
private $conn;
function __construct() {
$this->conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or
die('There was a problem connecting to the database.');
}
function verify_Username_and_Pass($un, $pwd) {
$query = "SELECT *
FROM users
WHERE username = ? AND password = ?
LIMIT 1";
if($stmt = $this->conn->prepare($query)) {
$stmt->bind_param('ss', $un, $pwd);
$stmt->execute();
if($stmt->fetch()) {
$stmt->close();
return true;
}
}
}
}
In your index.php write the following code:
<div id="top-register">
<?
echo "Hello" .$_SESSION['username'];
?>
Create a session variable which will save the username you got from the query then echo that session variable in your page.
I think, you missed the echo before. Change
<?
$_SESSION['username']
?>
to
<?
echo $_SESSION['username']
?>
In class Membership change this...
if($ensure_credentials) {
$_SESSION['status'] = 'authorized';
header("location: index.php");
} else return "Please enter a correct username and password";
To this...
if($ensure_credentials) {
$_SESSION['status'] = 'authorized';
$_SESSION['username'] = $un;
header("location: index.php");
} else return "Please enter a correct username and password";
I used the same nettuts tutorial for my user login page. This is what works for me to show logged in user on index.php page.
INSERT IN BODY OF INDEX.PHP PAGE:
<?php
echo "Welcome ", $_SESSION['username'];
?>
i think you missed to start session on your index.php page
so enter this line at the starting of your page
session_start();

PHP - loading static class sends headers

I have a simple page in HTML/CSS/PHP that connects to MySQL DB.
"index.php" is loaded and "mainPage::showSectionLogin($_SESSION['login'])" shows logging form
<?php session_start(); ?>
<?php require_once 'clMainPage.php'; ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<HTML>
<HEAD>
<?php mainPage::setSectionHEAD() ?>
<LINK rel="stylesheet" type="text/css" href="style.css">
</HEAD>
<BODY>
<DIV id="sidebar">
<?php mainPage::showSectionLogin($_SESSION['login']) ?>
<?php mainPage::showSidebarMenu($_SESSION['login']) ?>
</DIV>
<DIV id="main">
<?php mainPage::showActualNews(5) ?>
</DIV>
</BODY>
</HTML>
"login.php" is executed after the logging form was filled
<?php session_start(); ?>
<?php require_once 'clMainPage.php'; ?>
<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
$dblink = mainPage::openDBconn();
$result = mainPage::checkIfUserCanLogIn($dblink, $_POST['inpLogin'], $_POST['inpPassw']);
if (mysql_num_rows($result) == 1) {
$row = mysql_fetch_array($result);
mainPage::logUserIn($row['login'], $row['passw']);
}
else
{
die("error checking user: there is no such user in a database");
}
mainPage::closeDBconn($dblink);
header("refresh:1;url=index.php");
} ?>
I don't inderstand why, during logging in, "header("refresh:1;url=index.php");" (line:18) says that "require_once 'clMainPage.php';" in file "login.php" (line:2) sends headers. How is it possible that "require_once 'clMainPage.php';", that is a class declaratin containing only static functions, actually sends headers?
There is white space after your closing php tag on line 1, that's what sends the headers
<?php
session_start();
require_once 'clMainPage.php';
if($_SERVER["REQUEST_METHOD"] == "POST") {
Do you have any whitespace / output before / after your < ?php. This is often the cause.
What does 'clMainPage.php' contain?

Categories