I have the following line in my HTML file for my homepage. How come it won't print out the name of the current user when they log in? I have the line in the body section of the html file. I want to put it on all my pages too but it won't display. The user does exist as it logs in succesfully via my php echo mesage.
This line:
<div id="usernameDiv"><?php echo $_SESSION['username']; ?></div>
Here is the login page:
<?php
function SignIn() {
require_once("constants.php"); //Now constants will be accessible
session_start();
try {
$link = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASSWORD);
$username = $_POST['username']; //no need to esaping as we will use prepared statements
$password = $_POST['password'];
if (!empty($username) && !empty($password)) {
//You need to define a new column named "id" which will be int auto_increment and it will be your primary key
$sql = "SELECT id, username, password FROM users where username = :username AND password = :password";
//Prepare your query
$stmt = $link->prepare($sql);
//Execute your query binding variables values
$stmt->execute(array(':username'=>$username, ':password'=>$password));
//Fetch the row that match the criteria
$row = $stmt->fetch();
if (!empty($row['username']) && !empty($row['password'])) {
$_SESSION['is_logged'] = true; //Now user is considered logged in
$_SESSION['username'] = $row['username'];
$_SESSION['id'] = $row['id'];
//Never store passwords in $_SESSION
echo "Welcome to your User Account for CSIT Conference. Click to go home: ";
echo ' Home Page . ';
echo "Or here to go to your assigned papers: ";
echo ' Assigned Papers . ';
} else {
echo "SORRY... YOU ENTERED WRONG ID AND PASSWORD... PLEASE RETRY...";
}
$link = null;
} else {
echo 'Please enter username and password.';
}
} catch(PDOException $e) {
echo $e->getMessage();
}
}
if (isset($_POST['submit'])) {
SignIn();
}
?>
Here is the home page. Eventually I want it on all the pages.
<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="import" href="navigation.html">
</head>
<body>
<center> <b>World Congress CS-IT Conferences 2016</center>
<div id="horizontalmenu">
<ul>
<li>Home<br/></li>
<ul> <li>General Information <ul>
<li>About</li>
<li> Conference Fee</li>
<li>Hotel</li> </ul>
<li>Keynote Speakers<br/></li>
<li>Call for Papers<br/></li>
<li>Important Dates<br/></li>
<li>Major Areas<br/></li>
<li>Paper Submission<br/></li>
<li>Login<br/></li>
<li>Registration<br/></li>
<li>Conference Program<br/></li>
<li>Guidelines<br/></li>
<li>Comments<br/></li>
</ul>
</nav></b>
<div id="usernameDiv"><?php echo $_SESSION['username']; ?></div>
<br><br>
<div class="zoom pic">
<center> <img src="images/technology.png" alt="portrait"> <center>
</div>
</body>
</html>
You are starting the session inside of your SignIn() function. Remove session_start(), and instead put the following at the top of your file to start your session:
if (!session_id()) #session_start();
You must also include the above line anywhere that you want to use the session data (for example, it should be the first line in your index file.)
* All of this assumes that you either have PHP setup to execute in a .html file, or your file is actually index.php instead of index.html
Related
This question already has answers here:
PHP Session variable not getting set
(9 answers)
Closed 1 year ago.
I've been following Dani Krossings Login System It's a great tutorial and is just what I am looking for, there is just one thing I'm struggling with.
After logging in, the header doesn't refresh. Following login, the header should change to ...Profile Page, Logout. The code I have stays as Sign Up, Login. It is as is the $_SESSION variable has not come through to the header. However, if after login, I select the Sign up or login link, the header changes to what it should be.
Function code
function uidExists($conn, $username) {
$sql = "SELECT * FROM users WHERE usersUid = ? OR usersEmail = ?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("location: ../signup.php?error=stmtfailed");
exit();
}
mysqli_stmt_bind_param($stmt, "ss", $username, $username);
mysqli_stmt_execute($stmt);
// "Get result" returns the results from a prepared statement
$resultData = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($resultData)) {
return $row;
}
else {
$result = false;
return $result;
}
mysqli_stmt_close($stmt);
}
function loginUser($conn, $username, $pwd) {
$uidExists = uidExists($conn, $username);
if ($uidExists === false) {
header("location: ../login.php?error=wronglogin");
exit();
}
$pwdHashed = $uidExists["usersPwd"];
$checkPwd = password_verify($pwd, $pwdHashed);
if ($checkPwd === false) {
header("location: ../login.php?error=wronglogin");
exit();
}
elseif ($checkPwd === true) {
session_start();
$_SESSION["userid"] = $uidExists["usersId"];
$_SESSION["useruid"] = $uidExists["usersUid"];
header("location: ../index.php?error=none");
exit();
}
}
header.php
<?php
session_start();
include_once 'includes/functions.inc.php';
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>PHP Project 01</title>
<!--I won't do more than barebone HTML, since this isn't an HTML tutorial.-->
<link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght#0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<!--A quick navigation-->
<nav>
<div class="wrapper">
<img src="img/logo-white.png" alt="Blogs logo">
<ul>
<li>Home</li>
<li>About Us</li>
<li>Find Blogs</li>
<?php
if (isset($_SESSION["useruid"])) {
echo "<li><a href='profile.php'>Profile Page</a></li>";
echo "<li><a href='logout.php'>Logout</a></li>";
}
else {
echo "<li><a href='signup.php'>Sign up</a></li>";
echo "<li><a href='login.php'>Log in</a></li>";
}
?>
</ul>
</div>
</nav>
<!--A quick wrapper to align the content (ends in footer.php)-->
<div class="wrapper">
Login.php
<?php
include_once 'header.php';
?>
<section class="signup-form">
<h2>Log In</h2>
<div class="signup-form-form">
<form action="includes/login.inc.php" method="post">
<input type="text" name="uid" placeholder="Username/Email...">
<input type="password" name="pwd" placeholder="Password...">
<button type="submit" name="submit">Sign up</button>
</form>
</div>
<?php
// Error messages
if (isset($_GET["error"])) {
if ($_GET["error"] == "emptyinput") {
echo "<p>Fill in all fields!</p>";
}
else if ($_GET["error"] == "wronglogin") {
echo "<p>Wrong login!</p>";
}
}
?>
</section>
<?php
include_once 'footer.php';
?>
login.inc.php
<?php
if (isset($_POST["submit"])) {
// First we get the form data from the URL
$username = $_POST["uid"];
$pwd = $_POST["pwd"];
// Then we run a bunch of error handlers to catch any user mistakes we can (you can add more than I did)
// These functions can be found in functions.inc.php
require_once 'dbh.inc.php';
require_once 'functions.inc.php';
// Left inputs empty
if (emptyInputLogin($username, $pwd) === true) {
header("location: ../login.php?error=emptyinput");
exit();
}
// If we get to here, it means there are no user errors
// Now we insert the user into the database
loginUser($conn, $username, $pwd);
} else {
header("location: ../login.php");
exit();
}
Anyone have any thoughts on how I can get the header to refresh on submission of a successful login form?
Since Sometimes Some Content Is Left On The Page After Reloading The Header, We Need To Use die() after Changing Location From Header.
TBH, Redirecting Using PHP Is Not Recommended, I Suggest You To Redirect The User Using An Inbuilt JavaScript Function, window.location.replace(path)
You Can Call It Inside A PHP Script Using
?>
<script>
window.location.replace(path)
</script>
<?php
Or Simply Just Create Your Own Function:
function redirect($path) {
?>
<script>
window.location.replace('<?php echo $path ?>')
</script>
<?php
}
And Use It: redirect("profile.php")
Always put a session_start() into every page I want to use $_SESSION variables.
Fixed.
Thanks for all your help!
I am trying to delete data from MySQL using PHP
<?php
if (isset($_POST['delete'])) {
$queryDelete = "Delete FROM info WHERE userID={$_POST['delete']}";
if (!($database = mysqli_connect("localhost", "root", ""))) {
die("Could not connect to database. </body></html>");
}
if (!mysqli_select_db($database, "project2")) {
die("Could not open books database. </body></html>");
}
if (!(mysqli_query($database, $queryDelete))) {
echo "<p>Could not execute query!</p>";
die(mysqli_error($database) . "</body></html>");
}
mysqli_close($database);
}
this is my delete.php using it on this page
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="Style.css">
</head>
<header>
<div>
<p id="page">Users List</p>
<img id="title_pic" src="images/title_pic.jpg" alt="#">
</div>
</header>
<body>
<?php include 'bar.php' ?>
<?php include 'delete.php' ?>
<br><br><br><br>
<h1 style="color:yellow;"> List of all Users: </h1>
<br>
<?php
$query = "SELECT userID, fName, email FROM info";
if (!($database = mysqli_connect("localhost", "root", ""))) {
die("Could not connect to database. </body></html>");
}
if (!mysqli_select_db($database, "project2")) {
die("Could not open project database. </body></html>");
}
if (!($result = mysqli_query($database, $query))) {
echo "<p>Could not execute query!</p>";
die(mysqli_error($database) . "</body></html>");
}
mysqli_close($database);
while ($row = mysqli_fetch_row($result)) {
foreach ($row as $value) {
echo "<span style='color:white;'> $value </span>";
}
echo ' <form action = "delete.php" method = "POST">';
echo '<input type="submit" name= "delete" value="delete" class="btn">';
echo '</form>';
echo "<br>";
}
?>
</html>
It's redirecting me to delete.php page but when I go back to the second one (Displayuser.php) all info are there and nothing is deleted
I used the same technique to add info but I am having trouble to delete them from the table.
Here is how your code should look like. First in your form, provide the ID of the user you want to delete. Make sure to enable mysqli error reporting and select the right database when connecting.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$database = mysqli_connect("localhost", "root", "", 'project2');
$database->set_charset('utf8mb4'); // always set the charset
$users = $database->query("SELECT userID, fName, email FROM info");
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="Style.css">
</head>
<body>
<header>
<div>
<p id="page">Users List</p>
<img id="title_pic" src="images/title_pic.jpg" alt="#">
</div>
</header>
<?php include 'bar.php' ?>
<?php include 'delete.php' ?>
<br><br><br><br>
<h1 style="color:yellow;"> List of all Users: </h1>
<br>
<?php
foreach ($users as $user) {
foreach ($user as $value) {
echo "<span style='color:white;'>'.htmlspecialchars($value).'</span>";
}
echo ' <form action = "delete.php" method = "POST">';
echo '<button type="submit" name="delete" value="'.htmlspecialchars($user['userID']).'" class="btn">Delete</button>';
echo '</form>';
echo "<br>";
}
?>
</html>
Then in your delete.php, read the POST value and delete the row with that ID using prepared statement.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$database = mysqli_connect("localhost", "root", "", 'project2');
$database->set_charset('utf8mb4'); // always set the charset
if (isset($_POST['delete'])) {
$stmt = $database->prepare("DELETE FROM info WHERE userID=?");
$stmt->bind_param('s', $_POST['delete']);
$stmt->execute();
}
UPDATED: I have a variable in PHP mailuid that I want to show in my HTML. It displays the error the value of mailuid is undefined on the webpage. How can I show the value of height to html page?
index.php
<?php
require "header.php";
?>
<main>
<link rel="stylesheet" type="text/css" href="styl.css">
<div class="wrapper-main">
<section class="section-default">
<h2><?php echo "$mailuid" ?></h2>
<?php
?>
</section>
</div>
</main>
<?php
require "footer.php";
?>
loginbackend.php
<?php
if(isset($_POST['login-submit'])) {
require 'db.php';
$mailuid = $_POST['mailuid'];
$password = $_POST['pwd'];
if (empty($mailuid) || empty($password)) {
header("Location: ./index.php?error=emptyfields");
exit();
} else {
$sql = "SELECT * FROM users WHERE uidUsers=? OR emailUsers=?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ./index.php?error=sqlerror");
exit();
} else {
mysqli_stmt_bind_param($stmt, "ss", $mailuid, $mailuid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)) {
$pwdCheck = password_verify($password, $row['pwdUsers']);
if($pwdCheck == false) {
header("Location: ./index.php?error=wrongpwd");
exit();
} else if ($pwdCheck == true) {
session_start();
$_SESSION['userId'] = $row['idUsers'];
$_SESSION['userUid'] = $row['uidUsers'];
$username = substr($mailuid, 0, strpos($mailuid, "#"));
header("Location: ./index.php?login=success".$username);
exit();
} else {
header("Location: ./index.php?error=wrongpwd");
exit();
}
} else {
header("Location: ./index.php?error=nouser");
exit();
}
}
}
} else {
header("Location: ./signup.php");
exit();
}
As per your latest comment:
To get the mailuid from the URL (GET parameters) add the following code to your index.php
<?PHP
require "header.php";
$mailuid = !empty($_GET['mailuid']) ? $_GET['mailuid'] : null;
// You can also specify the default value to be used instead of `null` if the `mailuid` is not specified in the URL.
?>
<main>
<link rel="stylesheet" type="text/css" href="styl.css">
<div class="wrapper-main">
<section class="section-default">
<h2><?php echo "$mailuid"?></h2>
</section>
</div>
</main>
<?php
require "footer.php";
?>
From PHP7 you can use
$mailuid = $_GET['mailuid'] ?? null;
instead of
$mailuid = !empty($_GET['mailuid']) ? $_GET['mailuid'] : null;
The mistake you've made:
I think you're confusing forms and file including with how post works.
Let me explain:
A form sends data to the server, which is then pushed into the $_POST global variable. You can read this data and use this data easily by echoing or dumping it.
This is what you should do:
In this case, your data value will be empty as you're not passing anything to it.
You can solve this by creating a form and passing it to your PHP file.
You can also just require your php script.
Normally you would put data.php in your action, but since you wish to use the variable before you entered the form, you have to include it first.
index.html
<?php require 'data.php'; ?>
<form method="POST" action="">
<h1>Height: <?=$height?></h1>
<input type="text" placeholder="Enter the height..." name="height">
<input type="submit" name="submit" value="Submit">
</form>
data.php
<?php
if (!empty($_POST)) {
$height = $_POST['height'];
} else {
$height = 0; //Default height
}
My apologies if i didn't get your question properly.
===========================================
Option B, if this is what you mean, is just doing this:
index.html
<body>
<div class="container">
<?php
require 'data.php'; //Get the data.php file so we can use the contents
?>
<h1><?php echo $height; ?></h1>
</div>
</body>
data.php
<?php
$height = 100; //Height variable
I have an backend website setup that displays all the users on my site in an organised table, I should be able to edit and delete the users from the php page. However I cannot get the delete function to work, here is the code.
Data_Display.php
<?php
include('session.php');
?>
<?php include ("db.php"); ?>
<?php
$sql = "SELECT * FROM username ORDER BY UserNameID DESC";
$query = mysql_query($sql) or die(mysql_error());
if (isset($_GET['UserNameID'])) {
$id = mysql_real_escape_string($_GET['UserNameID']);
$sql_delete = "DELETE FROM users WHERE id = '{$UserNameID}'";
mysql_query($sql_delete) or die(mysql_error());
header("location: data_display.php");
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="icon" type="image/ico" href="favicon.ico">
<title>Network TV - All Records</title>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body >
<div class="container">
<div class="content">
<h1>Network TV Users and User control panel</h1>
<br>
<div class="toolbar">
Add New Person
Home
</div>
<br>
</div>
</div>
<div class="container">
<div class="content">
<?php if (mysql_num_rows($query)) { ?>
<?php while ($rows = mysql_fetch_assoc($query)) { ?>
<div class="separator"></div>
<h2><b>User reference:</b> <?php echo $rows['UserNameID']; ?></h2>
<h2><b>Name:</b><?php echo $rows['name']; ?></h2>
<h2><b>Email address:</b> <?php echo $rows['email']; ?></h2>
<h2><b>Gender:</b> <?php echo $rows['sex']; ?></h2>
<h2><b>Profile Picture:</b> <?php echo $rows['imagelink']; ?></h2>
<div class="toolbar">
Edit
Delete
</div>
<?php } /* End Loop */ ?>
<div class="separator"></div>
<?php } else { ?>
<div class="separator"></div>
<h2>There are no records to display</h2>
<div class="separator"></div>
<?php } /* End Rows Checking */?>
</div>
</div>
<div class="container">
<br>
<br>
<br>
<br>
<br>
</div>
<script>
function confirmDelete ( message, url )
{
var confirmation = confirm ( message );
if ( confirmation == true ) {
window.location = url;
} else {
return false;
}
}
</script>
</body>
</html>
Session.php
<?php
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "root", "Oliver");
// Selecting Database
$db = mysql_select_db("users", $connection);
if(!isset($_SESSION)){session_start();}
// Storing Session
$user_check=$_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$ses_sql=mysql_query("select username from username where username='$user_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
$login_session =$row['username'];
if(!isset($login_session)){
mysql_close($connection); // Closing Connection
header('Location: home.php'); // Redirecting To Home Page
}
?>
db.php
<?php
$connection = mysql_connect('localhost', 'root', 'Oliver');
mysql_select_db('users', $connection) or die(mysql_error());
?>
Information
When I click the delete button in data_display.php, I do receive the javascript alert to confirm that I do want to delete the user from the database, but nothing actually happens.
if (isset($_GET['recordId'])) {
$id = mysql_real_escape_string($_GET['recordId']);
$sql_delete = "DELETE FROM users WHERE id = '{$id}'";
mysql_query($sql_delete) or die(mysql_error());
header("location: data_display.php");
exit();
}
You are sending recordId as parameter.
I am new to php. Here is a code to check if the user is logged in using session and then allowing the user.
VALIDATION
<?php
session_start();
$uname = $_POST['uname'];
$pass = $_POST['pass'];
if($uname == "admin" && $pass == "admin")
{
$_SESSION['uname'] = $uname;
$_SESSION['auth'] = 1;
echo "Welcome Mr ".$uname.". You are now logged in ";
echo "<br>";
echo "<a href='TakeMeHome.html'>Click here to access the application </a>";
}
else
{
echo "Invalid username or password";
}
?>
Page
<?php
session_start();
if($_SESSION['auth'] != 1)
{
echo "You are not logged in! ";
echo "<a href = \"TakeMeHome.html\">";
echo "Access Application";
echo "</a>";
exit();
}
?>
<html>
You are now logged in
</html>
But the link tag is displaying
"; echo "Access Application"; echo ""; exit(); } ?>
along with the html data. No verification is done. I know there are many better ways to validate user is logged in or not. But i am learning sessions and hence i am using sessions.
Can you please tell me where i am going wrong?
regards.
use single quote in your echo codes like this:
<html>
<head>
</head>
<body>
<?php
echo "<a href='pageToGoTo.html' title='Page to go to' class='whatEver'>Anchor text</a>";
?>
</body>
</html>
What is told already, html should be put in the body...
I have no idea why #Andy has suggested you put your PHP in your head tags - it isn't javascript. You have 2 ways you can format your PHP and HTML, the first is to put all your PHP above your opening html tag, like so
<?php
session_start();
if($_SESSION['auth'] != 1) {
$message = 'You are not logged in! Access Application';
} else {
$message = 'You are logged in!';
}
?>
<html>
<head>
</head>
<body>
<?php echo $message; ?>
</body>
</html>
Or, place it in the body of your page, like so:
<?php
session_start();
?>
<html>
<head>
</head>
<body>
<?php
if($_SESSION['auth'] != 1) {
echo 'You are not logged in! Access Application';
} else {
echo 'You are logged in!';
}
?>
</body>
</html>
If you are still not getting the desired results then use var_dump($_SESSION); to print out your session array and make sure it holds the correct information.