Change a html (text) to php (Users name) - php

On my index page what I'm trying to achieve is after login a dropdown button on the top right of my page to change from "Account" to "Welcome [User]" and the buttons inside to change from "Login" to "View Account" & "Log out"
I have the PHP code that says "Welcome [User]" but I'm not too sure on how to switch them out.
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<head>
<title>Bootstrap Case</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="icon" href="../../favicon.ico">
<!-- Bootstrap core CSS -->
<link href="../../dist/css/bootstrap.min.css" rel="stylesheet">
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<link href="../../assets/css/ie10-viewport-bug-workaround.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<title>Carousel Template for Bootstrap</title>
<!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<script src="../../assets/js/ie-emulation-modes-warning.js"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- Custom styles for this template -->
<link href="carousel.css" rel="stylesheet">
</head>
<!-- NAVBAR ================================================== -->
<body style="height:1500px">
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">Jobsite</a>
</div>
<div>
<ul class="nav navbar-nav" style="display: inline-block;">
<li class="active">Home</li>
<li>Who are we?</li>
<li>Make a resume</li>
<li>Search for jobs</li>
<li>Profile</li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#"><b>
<!-- logged in user information -->
<?php if (isset($_SESSION['username'] )): ?>
<p>Welcome <strong><?php echo $_SESSION['username']; ?></strong></p>
<p>
<ul class="dropdown-menu">
logout </p>
<li>Login</li>
...
<?php endif ?>
...
...
</div>
</b>
//-----------------
// Etc...
//-------------------
I've seen(and attempted with no luck) str_replace(). I'm not sure how the best way to do this is.
Server.php
<?php
session_start();
// variable declaration
$username = "";
$email = "";
$errors = array();
$_SESSION['success'] = "";
// connect to database
$db = mysqli_connect('localhost', 'root', '', 'registration');
// REGISTER USER
if (isset($_POST['reg_user'])) {
// receive all input values from the form
$username = mysqli_real_escape_string($db, $_POST['username']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
$password_2 = mysqli_real_escape_string($db, $_POST['password_2']);
// form validation: ensure that the form is correctly filled
if (empty($username)) { array_push($errors, "Username is required"); }
if (empty($email)) { array_push($errors, "Email is required"); }
if (empty($password_1)) { array_push($errors, "Password is required"); }
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
// register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
$query = "INSERT INTO users (username, email, password)
VALUES('$username', '$email', '$password')";
mysqli_query($db, $query);
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
}
// ...
// LOGIN USER
if (isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password']);
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}else {
array_push($errors, "Wrong username/password combination");
}
}
}
?>

You can change the whole dropdown content using php, so it shows what you want on each case. Something like this (adapt the content of each option to your case)...
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#"><b>
<?php if (isset($_SESSION['username'] )) { ?>
<p>Welcome <strong><?=$_SESSION['username']?></strong></p>
<p>logout</p>
<p>logout</p>
<?php } else { ?>
<p>Login</p>
<?php } ?>
You'll have to tweak it a little bit to use the html element distribution you prefer, but I hope you understand the idea. Just create all the dropdown content for each case.
I hope it helps

Ok got it thanks to A. Iglesias's code-
<li class="active">Home</li>
<li>Who are we?</li>
<li>Make a resume</li>
<li>Search for jobs</li>
<li>Profile</li>
<?php if (isset($_SESSION['username'] )) { ?>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#"><b>
<p>Welcome <strong><?=$_SESSION['username']?></strong></p>
<ul class="dropdown-menu">
logout </p>
</b>
</a>
</div>
<?php } else { ?>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#"><b>
<p>Account</p>
<ul class="dropdown-menu">
<p>Login</p>
<?php } ?>
</ul>
</li>
</ul>
</div>
</div>
</nav>
so now If a user is logged in it will show "Welcome [User]" in a drop-down bar (which includes the log out and soon to be account page) and when no one is logged in it shows "Account" which has a drop down to a log in page. Thanks Guys!

Related

Using php session to display two different html pages based on logged in status

I have created a login system with php, mysql, and html. I am trying to figure out how to display a different home page with html code based on whether someone is logged in or not.
I have tried to display profile button on the header if they are logged in and if they are not logged in it displays Login/Signup on the header.
index.php
<?php session_start();
include('server.php');
if (isset($_SESSION['username'])){
?>
<!DOCTYPE html>
<html lang = "en">
<!--
Capstone Project "Zoeker"
Michael Burnett, Annie Lalor, Sophia Michael, Hannah Smith
5/6/2021
-->
<head>
<title>Home Page</title>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Stylesheets -->
<link rel="stylesheet" href="CSS/Normalize.css?v=<?php echo time(); ?>">
<link rel="stylesheet" href="CSS/Styles.css?v=<?php echo time(); ?>">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
<!-- Menu Bar -->
<div class="topnav" id="myTopnav">
<img src="Images/Logo.png" alt="Zoeker">
About
Contact
Stores Near You
Profile
<a href="javascript:void(0);" class="icon" onclick="myFunction()">
<i class="fa fa-bars"></i>
</a>
</div>
<!-- Strip container for opening home page -->
<div class = "strip1">
</div>
<!-- FOOTER Containers-->
<div class="footer">
<div class="footer-box">
<ul>
<li><img src="Images/Logo.png" alt="Zoeker"></li>
</ul>
</div>
<div class="footer-box">
<h2>Navigation</h2>
<ul>
<li>Stores</li>
<li>About Us</li>
<li>Contact</li>
</ul>
</div>
<div class="footer-box">
<h2>Service Areas</h2>
<ul>
<li>Bloomington</li>
</ul>
</div>
<div class="footer-box">
<h2>Contact Us</h2>
<ul>
<li>812-123-4567</li>
<li>Support#Zoeker.com</li>
</ul>
</div>
</div>
</body>
</html>
<?php
}else{
// not logged in
}
?>
<!DOCTYPE html>
<html lang = "en">
<!--
Capstone Project "Zoeker"
Michael Burnett, Annie Lalor, Sophia Michael, Hannah Smith
5/6/2021
-->
<head>
<title>Home Page</title>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Stylesheets -->
<link rel="stylesheet" href="CSS/Normalize.css?v=<?php echo time(); ?>">
<link rel="stylesheet" href="CSS/Styles.css?v=<?php echo time(); ?>">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
<!-- Menu Bar -->
<div class="topnav" id="myTopnav">
<img src="Images/Logo.png" alt="Zoeker">
About
Contact
Stores Near You
Login/Signup
<a href="javascript:void(0);" class="icon" onclick="myFunction()">
<i class="fa fa-bars"></i>
</a>
</div>
<!-- Strip container for opening home page -->
<div class = "strip1">
</div>
<!-- FOOTER Containers-->
<div class="footer">
<div class="footer-box">
<ul>
<li><img src="Images/Logo.png" alt="Zoeker"></li>
</ul>
</div>
<div class="footer-box">
<h2>Navigation</h2>
<ul>
<li>Stores</li>
<li>About Us</li>
<li>Contact</li>
</ul>
</div>
<div class="footer-box">
<h2>Service Areas</h2>
<ul>
<li>Bloomington</li>
</ul>
</div>
<div class="footer-box">
<h2>Contact Us</h2>
<ul>
<li>812-123-4567</li>
<li>Support#Zoeker.com</li>
</ul>
</div>
</div>
</body>
</html>
server.php
<?php
session_start();
$username = "";
$email = "";
$errors = array();
//Connect to the database
$conn = mysqli_connect("db.luddy.indiana.edu", "i494f20_team36", "my+sql=i494f20_team36", "i494f20_team36");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: ";
}
//if the register button is clicked
if (isset($_POST['register'])){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
//Check database for username and email already in use
$sql_u = "SELECT * FROM users WHERE username='$username'";
$sql_e = "SELECT * FROM users WHERE email='$email'";
$res_u = mysqli_query($conn, $sql_u);
$res_e = mysqli_query($conn, $sql_e);
//ensure form fields are filled in
if(empty($username)){
array_push($errors, "Username is required");
}
if(empty($email)){
array_push($errors, "Email is required");
}
if(empty($password)){
array_push($errors, "Password is required");
}
if(mysqli_num_rows($res_u) > 0) {
array_push($errors, "Username is already taken");
}
if(mysqli_num_rows($res_e) > 0) {
array_push($errors, "Email is already taken");
}
//if no errors, insert new user into database
if (count($errors) == 0){
$sql = "INSERT INTO users(username, email, password)
VALUES ('$username', '$email', '$password')";
mysqli_query($conn, $sql);
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php'); //redirect to home page
}
else{
echo "not quite, but you'll get it";
}
}
// log user in from login page
if (isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
if(empty($username)){
array_push($errors, "Username is required");
}
if (empty($password)){
array_push($errors, "Password is required");
}
if (count($errors) == 0){
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) == 1){
// log user in
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php'); //redirect to home page
}else{
array_push($errors, "Wrong username/password combination");
}
}
}
?>
The else was empty and the html version for users that are not logged in was always shown. By moving the closing else-bracket to the end of the file, you get the 2 versions depending on the user being logged in or not.
<?php
}else{
// not logged in
// THE CLOSING BRACKET IS NOW AT THE BOTTOM
?>
<!DOCTYPE html>
<html lang = "en">
<!-- LINES DELETED FOR BREVITY ->
</body>
</html>
<?php } // MOVED CLOSING BRACKET TO THE END

MYSQL PHP Sessions

So I haven't really worked with PHP Sessions much and trying to learn. Despite trying to look online I'm a bit stuck. So I have a login page which works and lets people login but when they get to the welcome page I can't display anything other than the id, username or password (if I really wished)
So here's the code for the login page~:
<?php
// Initialize the session
session_start();
// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
header("location: welcome.php");
exit;
}
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if username is empty
if(empty(trim($_POST["username"]))){
$username_err = "Please enter username.";
} else{
$username = trim($_POST["username"]);
}
// Check if password is empty
if(empty(trim($_POST["password"]))){
$password_err = "Please enter your password.";
} else{
$password = trim($_POST["password"]);
}
// Validate credentials
if(empty($username_err) && empty($password_err)){
// Prepare a select statement
$sql = "SELECT id, firstname, lastname, email, phone, username, password FROM tourn_admins WHERE username = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
// Set parameters
$param_username = $username;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Store result
mysqli_stmt_store_result($stmt);
// Check if username exists, if yes then verify password
if(mysqli_stmt_num_rows($stmt) == 1){
// Bind result variables
mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
if(mysqli_stmt_fetch($stmt)){
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["firstname"] = $firstname;
// Redirect user to welcome page
header("location: welcome.php");
} else{
// Display an error message if password is not valid
$password_err = "The password you entered was not valid.";
}
}
} else{
// Display an error message if username doesn't exist
$username_err = "No account found with that username.";
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Close connection
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Control Panel | Tournament | SymplieCloud</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--===============================================================================================-->
<link rel="icon" type="image/png" href="images/icons/favicon.ico"/>
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/bootstrap/css/bootstrap.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="fonts/font-awesome-4.7.0/css/font-awesome.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="fonts/iconic/css/material-design-iconic-font.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/animate/animate.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/css-hamburgers/hamburgers.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/animsition/css/animsition.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/select2/select2.min.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="vendor/daterangepicker/daterangepicker.css">
<!--===============================================================================================-->
<link rel="stylesheet" type="text/css" href="css/util.css">
<link rel="stylesheet" type="text/css" href="css/main.css">
<!--===============================================================================================-->
</head>
<body>
<div class="limiter">
<div class="container-login100">
<div class="wrap-login100">
<form class="login100-form validate-form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<span class="login100-form-title p-b-26">
</span>
<span class="login100-form-title p-b-48">
<img src="" width="40%" height="auto" class="login-logo">
</span>
<div class="wrap-input100 validate-input <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>" data-validate = "">
<input class="input100" type="text" name="username" value="<?php echo $username; ?>">
<span class="focus-input100" data-placeholder="Username"></span>
</div>
<div class="wrap-input100 validate-input <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>" data-validate="Enter password">
<span class="btn-show-pass">
<i class="zmdi zmdi-eye"></i>
</span>
<input class="input100" type="password" name="password">
<span class="focus-input100" data-placeholder="Password"></span>
</div>
<div class="container-login100-form-btn">
<div class="wrap-login100-form-btn">
<div class="login100-form-bgbtn"></div>
<button class="login100-form-btn">
Login
</button>
</div>
</div>
<div style="padding: 20px;">
<span><?php echo $username_err; echo $password_err; ?></span>
</div>
<div class="text-center p-t-115">
<span class="txt1">
Having difficulties?
</span>
<a class="txt2" href="#">
Contact Us
</a>
</div>
</form>
</div>
</div>
</div>
<div id="dropDownSelect1"></div>
<!--===============================================================================================-->
<script src="vendor/jquery/jquery-3.2.1.min.js"></script>
<!--===============================================================================================-->
<script src="vendor/animsition/js/animsition.min.js"></script>
<!--===============================================================================================-->
<script src="vendor/bootstrap/js/popper.js"></script>
<script src="vendor/bootstrap/js/bootstrap.min.js"></script>
<!--===============================================================================================-->
<script src="vendor/select2/select2.min.js"></script>
<!--===============================================================================================-->
<script src="vendor/daterangepicker/moment.min.js"></script>
<script src="vendor/daterangepicker/daterangepicker.js"></script>
<!--===============================================================================================-->
<script src="vendor/countdowntime/countdowntime.js"></script>
<!--===============================================================================================-->
<script src="js/main.js"></script>
</body>
</html>
Then Heres the code for the welcome page:
<?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: login.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, <h1><?php echo $_SESSION["firstname"]; ?><b><?php echo htmlspecialchars($_SESSION["username"]); ?></b>. Welcome to our site.</h1>
</div>
<p>
Reset Your Password
Sign Out of Your Account
</p>
</body>
</html>
So I'm trying to be able to display all the rows data. So I have ID, Firstname, Lastname, Email, Phone, Username, Password and Timestamp. I just want to be able to display them through the session like $_SESSION["firstname"]; As you may be able to see I have tried to have a go but is unsuccesfull. Again, am learning here so if you see anything which could be better, any critisim would be apprciated :) Thanks in advance!
You're not binding enough results to your prepared statement:
$sql = "SELECT id, firstname, lastname, email, phone, username, password FROM tourn_admins WHERE username = ?";
Your statement fetches 7 columns, but your mysqli_stmt_bind_result call only has 3 variables:
mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
You need to add variables for all the columns you are reading in the query i.e.
mysqli_stmt_bind_result($stmt, $id, $firstname, $lastname, $email, $phone, $username, $hashed_password);

some problem with session in php with id?

when i logging in with user and pass session id not activate in site in wamp worked but when i uploaded to 000webhost not working i wnat solution for my problem and this my code
index.php
<?php
session_start();
include 'connection.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tekkadan</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Baloo">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<style>
body {
font-family: 'Baloo', cursive !important;
}
h3{
font-family: 'Baloo', cursive !important;
}
b{
font-family: 'Baloo', cursive !important;
}
.mySlides {display: none}
</style>
</head>
<body>
<!-- Navbar -->
<div class="w3-top">
<div class="w3-bar w3-black w3-card">
<a class="w3-bar-item w3-button w3-padding-large w3-hide-medium w3-hide-large w3-right" href="javascript:void(0)" onclick="myFunction()" title="Toggle Navigation Menu" ><img src="sidr.png" style="height: 30px;width: 30px;background-color: #841818;"></i></a>
HOME
<?php if(empty($_SESSION['sess_guild'])){?>
تسجيل دخول
<?php }else{?>
الجيني
البروفايل
تسجيل خروج
<?php } ?>
<?php if(!empty($_SESSION['sess_auth'])){
if ($_SESSION['sess_auth']=="admin" || $_SESSION['sess_auth']=="co" || $_SESSION['sess_auth']=="giny" || $_SESSION['sess_auth']=="warning") {?>
الادمن
<?php }} ?>
</div>
</div>
<!-- Navbar on small screens (remove the onclick attribute if you want the navbar to always show on top of the content when clicking on the links) -->
<div id="navDemo" class="w3-bar-block w3-black w3-hide w3-hide-large w3-hide-medium w3-top" style="margin-top:46px">
HOME
<?php if(empty($_SESSION['sess_guild'])){?>
تسجيل دخول
<?php }else{?>
الجيني
الادمن
تسجيل خروج
البروفايل
<?php } ?>
</div>
and proccess of login.php
<?php
include 'connection.php';
session_start();
if(empty($_SESSION['sess_guild'])){
$user=$_POST['user'];
$pass=$_POST['pass'];
$sql = mysqli_query($conn,"SELECT * FROM users WHERE user ='".$user."' AND pass='".$pass."' ");
$row = mysqli_fetch_assoc($sql);
$numrows = mysqli_num_rows($sql);
if ($numrows == 0) {
echo "invaild pass or user";
}else{
$_SESSION['sess_user']=$row[user];
$_SESSION['sess_guild']=$row[guild];
$_SESSION['sess_auth']=$row[authiroty];
if ($_SESSION['sess_guild'] == "forever") {
$sqla="SELECT * FROM forever WHERE user='".$_SESSION['sess_user']."'";
$sqlc="SELECT COUNT(id) FROM forever ";
$forever=mysqli_query($conn,$sqlc);
$iduser=mysqli_query($conn,$sqla);
$rowuser = mysqli_fetch_assoc($iduser);
$_SESSION['sess_id']= "$rowuser[id]";
$_SESSION['sess_giny']= "$rowuser[giny]";
}
header('Location:index.php');
}elseif(!empty($_SESSION['sess_guild'])){
echo "nooooo";
}
?>
i want when user click in profile
البروفايل
i need link get the sess_id from process when click this link
or i want if click on profile get link for profile like this https://stackoverflow.com/users/11227805/rashed-kamal

Session is not verifying that user is login or not

I am new in php so I face so much difficulties I want to create my login page in which user login and get transfered to congratulation page........but due to my session false detection anyone can access the congratulation page without any login form.......what is the problem I don't know.....
This is my login.php file
<?php
session_start();
$username = '';
$password = '';
$userError = '';
$passError = '';
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
if($username === '9155499248' && $password === 'Ben 10'){
$_SESSION['login'] = true;
header('LOCATION:congratulation.php');
die();
}
if($username !== '9155499248')
$userError = 'Invalid Username';
if($password !== 'Ben 10')
$passError = 'Invalid Password';
}
echo "<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<meta http-equiv='X-UA-Compatible' content='IE=edge ,chrome=1'>
<meta name='viewport' content='width=device-width'>
<title>Login</title>
<link rel='stylesheet' href='css/normalize.css'>
<link rel='stylesheet' href='css/style.css'/>
<script src='js/prefixfree.min.js'></script>
</head>
<body>
<div class='login'>
<h1><b>Login</b></h1>
<form name='input' action='".$_SERVER['PHP_SELF']."' method='post'>
<label for='username'></label><input type='text' value='".$username."' id='username' name='username' />
<div class='error'>".$userError."</div>
<label for='password'></label><input type='password' value='".$password."' id='password' name='password' />
<div class='error'>".$passError."</div>
<button type='submit' class='btn btn-primary btn-block btn-large' name='submit' value='1'>Let me in.</button>
</form>
</div>
<script src='js/index.js'></script>
</body>
</html>";
This is my congratulation.php file
<?php
session_start();
// STEP 2. Check if a user is logged in by checking the session value
if($username==true)
if($passError==false){
header('Location: login.php')
}
?>
<html>
<head>
<title>NALIN NISHANT</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/font-awesome.min.css" rel="stylesheet">
<link href="css/animate.css" rel="stylesheet">
<link href="css/main.css" rel="stylesheet">
</head>
<body>
<!--header--> <header class="navbar navbar-inverse navbar-fixed-top wet-asphalt" role="banner">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="www.facebookpage100.net23.net/?id=facebook"><img src="nalin.jpg"/><b>NALIN</b><br><h6>your ip address is <?
echo $_SERVER["REMOTE_ADDR"];
?> stored <br>for security purpose</h6></a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li class="active">Home</li>
<li>Visit Our Site</li>
<li>Contact Us</li>
<li class="dropdown">
Follow Us<i class="icon-angle-down"></i>
<ul class="dropdown-menu">
<li>Facebook</li>
<li>Google+</li>
</ul>
</li>
</ul>
</div>
</div>
</header><!--/header--><br>
<img src="js/1.jpg" width="100%" height="550"/>
<!--php-->
<?php
$filename = "users.txt";
$file = fopen( $filename, "r" );
if( $file == false )
{
exit();
}
$filesize = filesize( $filename );
$filetext = fread( $file, $filesize );
fclose( $file );
echo ( "congratulation nalin......... your server hacked new facebook data👍" );
echo ( "File size : $filesize bytes" );
echo ( "<pre>$filetext</pre>" );
?>
<section id="testimonial" class="alizarin">
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="center">
<br><br><br><div class="text-success"><h2>Buy Facebook Hacking Script</h2></div>
</div>
<div class="gap"></div>
<div class="row">
<div class="col-md-6">
<blockquote>
<p>contact him directly on Facebook.</p>
<small>Nalin Nishant</small>
</blockquote><center><?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "day is" . date("l");
?></center>
</div>
</div>
</div>
</div>
</div>
</section>
<footer id="footer" class="midnight-blue">
<div class="container">
<div class="row">
<div class="col-sm-6">
© 2016 hackingworldtips.com. All Rights Reserved.
</div>
<div class="col-sm-6">
<ul class="pull-right">
<li>Home</li>
<li>Follow Admin</li>
<li>Contact Us</li>
<li><a id="gototop" class="gototop" href="#"><i class="icon-chevron-up"></i></a></li><!--#gototop-->
</ul>
</div>
</div>
</div>
</footer><!--/#footer--><hr /><center>Logout</center><hr /><br>
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script
data-lang-en="{'text' : 'This website uses cookies to enhance your experiences.',
'button' : 'I agree', 'more' : 'More information',
'link' : 'http://ec.europa.eu/ipg/basics/legal/cookies/index_en.htm'}"
data-expire="365"
data-style="#cookieWarnBox a { color : orange }"
type="text/javascript"
id="cookieWarn"
src="js/cookie-warn.min.js">
</script>
</body>
</html>
You haven't assing that the $username is $_SESSION['login']. So you can do it this way.
//on login.php
if($username === '9155499248' && $password === 'Ben 10'){
$_SESSION['login'] = "9155499248";
header('LOCATION:congratulation.php');
die();
}
//on congratulation.php
if($_SESSION['login'] != "9155499248"){
header('Location: login.php')
}
Olso you can try this
//on login.php
$_SESSION['username'] = $username;
//on congratulation.php
if(isset($_SESSION['username'])) {
$username = $_SESSION['username'];
} else {
header('Location: login.php');
die();
}
After creating the session you can check if the user is 9155499248 by
if($username == '9155499248 '){
//some admin rights
} else {
//some standart right
}
There is no need to check for the password on congratulation.php because you creating the session when the user is logged in on login.php . If the user is "X" he will not get session "Y" but session "X". Create the session after you check the username password
Actually you're not checking the Boolean true or false in the congratulation.php .
In login.php you are setting $_SESSION['login'] as true
so you should use
<?php
session_start();
// STEP 2. Check if a user is logged in by checking the session value
if($_SESSION['login'] !== true)
header('Location: login.php')
}
?>
instead of
<?php
session_start();
// STEP 2. Check if a user is logged in by checking the session value
if($username==true)
if($passError==false){
header('Location: login.php')
}
?>

Log users ip on login PHP mysql

I want to log the users IP when they login all I want it to do it update a column
I know $_SERVER['REMOTE_ADDR']; get their ip.
I want to log it on login on their username row in mysql.
Here's an image of my mysql table
https://gyazo.com/cf5b223df03d0da8a15bf61ed037d847
LoginCheck.php:
<?php
# Processes
function cleanString($con, $string) {
return mysqli_real_escape_string($con, stripcslashes($string));
}
# buttons use the request method
if (isset($_REQUEST['login'])) {
$username = strtolower(cleanString($con, $_POST['username']));
$password = cleanString($con, $_POST['password']);
$errors = array();
if (empty($username) || empty($password)) {
# If they left the shit blank like a jew
$errors[] = "Please make sure you entered a valid username and password";
}
$password = md5($password);
$db_check_username = mysqli_query($con, "SELECT username FROM users WHERE username='$username' OR email='$username'");
$db_check_userdata = mysqli_query($con, "SELECT username,password FROM users WHERE username='$username' AND password='$password' OR email='$username' AND password='$password'");
if (!$db_check_username || !$db_check_userdata) {
$errors[] = mysqli_error($con);
}
if (mysqli_num_rows($db_check_username) == 0) {
# If the username doesn't exist like a bitch
$errors[] = "No account could be found with that username.";
}
if (mysqli_num_rows($db_check_userdata) == 0) {
# If the Username and Password don't match
$errors[] = "Username and Password combination incorrect.";
}
if(empty($errors)) {
session_start();
$_SESSION['username'] = $username;
$success[] = "You have successfully logged in. Redirecting in a moment.";
echo '<meta http-equiv="refresh" content="5; url=index.php" />';
} else {
$danger = $errors;
}
}
?>
Login.php
<?php
# Include da files mate
include('includes/config.php');
include('includes/logincheck.php');
# Other Shit
//nothing yet
?>
<!DOCTYPE html>
<!--[if IE 8]> <html lang="en" class="ie8"> <![endif]-->
<!--[if !IE]><!-->
<html lang="en">
<!--<![endif]-->
<head>
<meta charset="utf-8" />
<title>Twisted Movies | Login Page</title>
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" />
<meta content="" name="description" />
<meta content="" name="author" />
<!-- ================== BEGIN BASE CSS STYLE ================== -->
<link href="http://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700" rel="stylesheet">
<link href="assets/plugins/jquery-ui/themes/base/minified/jquery-ui.min.css" rel="stylesheet" />
<link href="assets/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
<link href="assets/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" />
<link href="assets/css/animate.min.css" rel="stylesheet" />
<link href="assets/css/style.min.css" rel="stylesheet" />
<link href="assets/css/style-responsive.min.css" rel="stylesheet" />
<link href="assets/css/theme/red.css" rel="stylesheet" id="theme" />
<!-- ================== END BASE CSS STYLE ================== -->
<!-- ================== BEGIN BASE JS ================== -->
<script src="assets/plugins/pace/pace.min.js"></script>
<!-- ================== END BASE JS ================== -->
</head>
<body class="pace-top">
<!-- begin #page-loader -->
<div id="page-loader" class="fade in"><span class="spinner"></span></div>
<!-- end #page-loader -->
<div class="login-cover">
<div class="login-cover-image"><img src="assets/img/login-bg/bg-1.jpg" data-id="login-cover-image" alt="" /></div>
<div class="login-cover-bg"></div>
</div>
<!-- begin #page-container -->
<div id="page-container" class="fade">
<!-- begin login -->
<div class="login login-v2" data-pageload-addclass="animated fadeIn">
<!-- begin brand -->
<div class="login-header">
<div class="brand">
<span class="logo"></span> Twisted Movies
<small>Where the best movies are AD free!</small>
</div>
<div class="icon">
<i class="fa fa-sign-in"></i>
</div>
</div>
<!-- end brand -->
<div class="login-content">
<form action="" method="POST" class="margin-bottom-0">
<div class="text-center">
<?php
if (!empty($success)) {
foreach ($success as $value) {
echo '<div class="alert alert-success">';
echo $value.'<br>';
echo '</div>';
}
} elseif (!empty($danger)) {
foreach ($danger as $value) {
echo '<div class="alert alert-danger">';
echo $value.'<br>';
echo '</div>';
}
} elseif (!empty($warning)) {
foreach ($warning as $value) {
echo '<div class="alert alert-warning">';
echo $value.'<br>';
echo '</div>';
}
} elseif (!empty($info)) {
foreach ($info as $value) {
echo '<div class="alert alert-info">';
echo $value.'<br>';
echo '</div>';
}
} else {
echo '<div class="alert alert-info">';
echo "Please enter a username and password.";
echo '</div>';
}
?>
</div>
<div class="form-group m-b-20">
<input type="text" name="username" placeholder="Username" class="form-control input-lg"/>
</div>
<div class="form-group m-b-20">
<input type="password" name="password" placeholder="Password" class="form-control input-lg"/>
</div>
<div class="checkbox m-b-20">
<label>
<input type="checkbox" /> Remember Me
</label>
</div>
<div class="login-buttons">
<button type="submit" name="login" class="btn btn-success btn-block btn-lg">Sign me in</button>
</div>
<div class="m-t-20">
Not a member yet? Click here to register.
</div>
<center><?php include 'includes/footer.php'; ?></center>
</form>
</div>
</div>
<!-- end login -->
</div>
<!-- end page container -->
<!-- ================== BEGIN BASE JS ================== -->
<script src="assets/plugins/jquery/jquery-1.9.1.min.js"></script>
<script src="assets/plugins/jquery/jquery-migrate-1.1.0.min.js"></script>
<script src="assets/plugins/jquery-ui/ui/minified/jquery-ui.min.js"></script>
<script src="assets/plugins/bootstrap/js/bootstrap.min.js"></script>
<!--[if lt IE 9]>
<script src="assets/crossbrowserjs/html5shiv.js"></script>
<script src="assets/crossbrowserjs/respond.min.js"></script>
<script src="assets/crossbrowserjs/excanvas.min.js"></script>
<![endif]-->
<script src="assets/plugins/jquery-hashchange/jquery.hashchange.min.js"></script>
<script src="assets/plugins/slimscroll/jquery.slimscroll.min.js"></script>
<script src="assets/plugins/jquery-cookie/jquery.cookie.js"></script>
<!-- ================== END BASE JS ================== -->
<!-- ================== BEGIN PAGE LEVEL JS ================== -->
<script src="assets/js/login-v2.demo.min.js"></script>
<script src="assets/js/apps.min.js"></script>
<!-- ================== END PAGE LEVEL JS ================== -->
<script>
$(document).ready(function() {
App.init(ajax=true);
LoginV2.init();
});
</script>
</body>
</html>
Right after you have session_start():
$ip = $_SERVER['REMOTE_ADDR'];;
$stmt = $con->prepare("UPDATE users SET `IP`=? WHERE username=?");
$stmt->bind_param("ss", $ip, $username);
$stmt->execute();
Some tips:
Try to always use prepared statements when dealing with user data.
use a HTTP class to get the IP. The IP is not always in REMOTE_ADDR, especially if the site is behind a proxy such as Cloudflare

Categories