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.
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 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
At that time I need two view pages in one page. So that in the session i do something like this:
<?php
session_start();
if(isset($_SESSION['login_id']) && !empty($_SESSION['login_id'])){
?>
///My HTML CODE///
<?
}
else {
?>
//Diffetent View HeRe//
<?
}
require_once('../libraries/config/configPDO.php');
?>
But now I just need to make it become one page and redirect it if they not logged in.
<?php
session_start();
if(isset($_SESSION['login_id']) && !empty($_SESSION['login_id'])){
?>
///My HTML CODE///
<?
}
else {header("Location: login.php");
?>
<?
}
require_once('../libraries/config/configPDO.php');
?>
But as you see, I put the header redirect at the bottom of the page.
How to make it simple, so that I set header location in the top of the page.
Try with -
session_start();
if(empty($_SESSION['login_id'])){
header("Location: login.php");
exit;
} else {
//HTML
}
try this,
<?php
ob_start();
session_start();
if(isset($_SESSION['login_id']) && !empty($_SESSION['login_id'])){
?>
///My HTML CODE///
<?
require_once('../libraries/config/configPDO.php');
}
else {
header("Location: login.php");
}
?>
reverse the if to
if(!isset($_SESSION['login_id']) || empty($_SESSION['login_id'])){
and swap the cases
None of the other methods work so could you please help? Here is my code:
<?php
include("db.php");
If(isset($_SESSION['name']))
{
$main = "<h2>hey</h2>";
}
else
{
$main = "<h2>welcome</h2>"
}
?>
<html>
<body>
<?php echo $main;?>
</body>
</html>
//db.php consists of
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("notes");
echo mysql_error();
session_start();
?>
Whenever I run the code it always shows: welcome. No matter if I'm logged in or logged out of my website.
Your html is looks good but
It seems that you did not set session_start() at the top of your php file or you did not set session variable.
try like this:
<?php
session_start();
if(isset($_SESSION['name']))
{
$main = "<h2>hey</h2>";
}
else
{
$main = "<h2>welcome</h2>"
}
?>
<html>
<body>
<?php echo $main;?>
</body>
</html>
I am not very good at php but I want to detect if a user is in the home of the website such as;
<?php
if (current path = http://website.com/ || website.com)
{?>
<div>We are in home</div>
<?php } else { ?>
<div>do something</div>
<?php } ?>
Someone help me please thanks
$pageName = $_SERVER['PHP_SELF'];
if($pageName == 'http://website.com'){
echo '<div>We are in home</div>';
} else { do something };