how to get username and display when is logged in - php

in this i wannna get the username who is logged in and display it in the home page when the username is correct and registered in database .should i use session and where to use it.how it is been done
<?php
error_log("chk.php executing");
// Get values from form
include 'config.php';
foreach ($_POST as $key => $value) {
error_log($key);
}
//error_log($_POST['username']);
$username=$_POST['username'];
$password=$_POST['password'];
// Insert data into mysql
$qry = mysql_query("SELECT * FROM useraccount WHERE username='$username'");
if(!$qry) {
die("Query Failed: ". mysql_error());
} else {
$row=mysql_fetch_array($qry);
if ($username==$row['username']) {
if($username=='' || $password=='') {
error_log("some fields are empty");
//header("Location:login.php?id=Some fields are empty");
// header("Content-Type: text/html");
// {echo "<b>Some fields are empty</b>";}
} else if($username==$row['username'] && $password==$row['password']) {
error_log("logged in");
header('Location: home.html');
// header("Content-Type: text/html");
// {echo "<b>User name password verified</b>";}
//header("Location: home.html?id=$username");
} else {
error_log("password is incorrect");
// header("Content-Type: text/html");
// {echo "<b>username already taken or your password is incorrect. Please try again</b>";}
//header("Location:.php?id=username already taken or your password is incorrect. Please try again");
}}
else
error_log("username incorrect");
}
mysql_close();
?>
html,body
{
margin:0px;
height:100%;
}
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
width: 60%;
margin: auto;
}
.content
{
width:100%;
height:400px;
}
.signup
{
height:500px;
}
.footer
{
position:relative;
background-color:black;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>ASK</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="boot.css">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="jumbotron">
<div class="container">
<div class="row">
<div class="col-md-6">
<h1>school name</h1>
</div>
<div class="col-md-6">
<img src="../project/photo/l.png" height="150px"/>
</div>
</div>
</div>
</div>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#mynavbar">schoolName</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li><a href="about.html" target=_self>About Us</a></li>
<li><a href="infra.html" target=_self>Infrastructure</a></li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="">Administration<span class="caret"></span></a>
<ul class="dropdown-menu">
<li>staff login</li>
<li>staff details</li>
<li>class handling</li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><span class="glyphicon glyphicon-user"></span> Sign Up</li>
<li><span class="glyphicon glyphicon-log-in"></span> Login</li>
</ul>
</div>
</div>
</nav>
<div class="container">
<form class="form-horizontal" action="chk.php" method="POST">
<div class="form-group">
<div class="col-xs-3">
<label for="username">Username:</label>
<input name="username" type="username" class="form-control" id="username" placeholder="Enter username">
</div></div>
<div class="form-group">
<div class="col-xs-3">
<label for="pwd">Password:</label>
<input name="password" type="password" class="form-control" id="password" placeholder="Enter password">
</div></div>
<!-- <div class="checkbox">
<label><input type="checkbox"> Remember me</label><br>
</div> -->
<button type="submit" class="btn btn-default">Submit</button><br>
</form>
</div>
<div class="footer navbar-fixed-bottom">
<p> Copyrights# ©WWW.schools.com</p>
</div>
</body>
</html>

first of all when username store in session on login time
<?php
session_start();
- List item
error_log("chk.php executing"); // Get values from form include 'config.php';
foreach ($_POST as $key => $value) { error_log($key); } //error_log($_POST['username']); $username=$_POST['username']; $password=$_POST['password']; // Insert data into mysql $qry = mysql_query("SELECT * FROM useraccount WHERE username='$username'"); if(!$qry) { die("Query Failed: ". mysql_error()); } else {
$row=mysql_fetch_array($qry);
if ($username==$row['username']) {
if($username=='' || $password=='') {
error_log("some fields are empty");
//header("Location:login.php?id=Some fields are empty");
// header("Content-Type: text/html"); // {echo "<b>Some fields are empty</b>";}
} else if($username==$row['username'] && $password==$row['password']) {
error_log("logged in");
$_SESSION['username']=$row['username'];
header('Location: home.html');
// header("Content-Type: text/html"); // {echo "<b>User name password verified</b>";}
//header("Location: home.html?id=$username");
} else {
error_log("password is incorrect");
// header("Content-Type: text/html"); // {echo "<b>username already taken or your password is incorrect. Please try again</b>";}
//header("Location:.php?id=username already taken or your password is incorrect. Please try again");
}}
else
error_log("username incorrect"); } mysql_close(); ?>
Another page we get this username and we change file name home.html to home.php
home.php
echo $_SESSION['username'];
?>
output username print this page

You can use SESSION . You have to use session_start() in every files that you want to display the username
else if($username==$row['username'] && $password==$row['password']) {
$_SESSION['username'] = $username; // store username name in session
error_log("logged in");
header('Location: home.html');
// header("Content-Type: text/html");
// {echo "<b>User name password verified</b>";}
header("Location: home.php?id=$username"); // redirect to home.php page
You can simply display the username by echo $_SESSION['username']; Don't forget to add session_start(); in your home.php. For more info please refer to this link http://php.net/manual/en/function.session-start.php

You should use session_start();
After successfully login,you can post username or email like this-
<?php
include_once'dbconnect.php';
$res=mysql_query("SELECT * FROM users WHERE user_id=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);
//print logged in user's email as saved in database
echo $userRow['email'];
////print logged in user's username as saved in database
echo $userRow['username'];
?>
This is as per my database where-
'dbconnect.php'is connection file.
'users' is tablename.

You can use session_start(); and store the username into it.
//Initialize the session:
session_start();
<!doctype html>
<head>
.
.
.
</head>
<body>
.
.
<?php
$q = "SELECT * FROM useraccount WHERE username='$username'";
$r = $mysqli->query($q);
if ($r->num_rows == 1) {
$_SESSION = $r-> fetch_array(MYSQLI_ASSOC);
}
?>
.
</body>
</html>
You can take a look at my site for that same query at hiteachers.com

Related

Form fails to proceed on submit

I have a login form(index.php) which allows students to access their portal, the students' registration number and password is then checked if inserted(login.php) and proceeds to a class(StudentLogin.php) which will then allow the students access their portal if at all the credentials match with the ones in the database. On entering the correct credentials, the process doesn't proceed to the stud_page.php.....I would appreciate any help on this cause i don't understand what is happening.
Below is the index.php:
<?php
//Start session
if(!isset($_SESSION)) { session_start(); }
unset($_SESSION['ID']);
unset($_SESSION['REG_NUM']);
?>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Portal System</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="static/css/bootstrap.min.css">
<link rel="stylesheet" href="static/css/style.css">
<!-- <link rel="stylesheet" href="static/css/style.css"/> -->
</head>
<body>
<!-- Header -->
<nav class="navbar navbar-fixed-top" style="background-color: green;" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<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="index.php">portal</a>
</div>
</div><!-- /.container-fluid -->
</nav>
<!-- End Header -->
<div class="background">
<div class="container">
<div class="jumbotron bg-success text-warning">
<h1 class="text-center">portal</h1>
<h3 class="text-center"> Welcome to The Portal.</h3>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-4 col-sm-offset-4">
<div class="login-con">
<h3>Student Log-in</h3><hr>
<?php
if(isset($_SESSION['ERROR_MSG_ARRAY']) && is_array($_SESSION['ERROR_MSG_ARRAY']) && COUNT($_SESSION['ERROR_MSG_ARRAY']) > 0) {
foreach($_SESSION['ERROR_MSG_ARRAY'] as $msg) {
echo "<div class='alert alert-danger'>";
echo $msg;
echo "</div>";
}
unset($_SESSION['ERROR_MSG_ARRAY']);
}
?>
<form action="process/login.php" method="POST" role="form">
<div class="form-group has-warning has-feedback">
<label for="reg_num">Registration Number</label>
<input type="text" name="reg_num" id="reg_num" class="form-control" autocomplete="off" placeholder="Registration Number">
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
<div class="form-group has-warning has-feedback">
<label>Password</label>
<input id="password" type="password" autocomplete="off" class="form-control" placeholder="Password" name="password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<button type="submit" onclick="showSomeMessage()" name="submit" class="btn btn-info">Submit</button>
</form>
</div>
</div>
</div>
</div>
</div>
login.php below:
<?php
require("../admin/database.php");
require("../class/StudentLogin.php");
if(isset($_POST['submit'])){
$regnum = trim($_POST['regnumber']);
$password = trim($_POST['password']);
$loginStud = new StudentLogin($reg_num, $password);
$rtnlogin = $loginStud->Studlogin();
}
$conn->close();
?>
Then the StudentLogin class is:
<?php
class StudentLogin
{
private $_regnumber;
private $_password;
public function __construct($c_reg_num, $c_password){
$this->_regnumber = $c_reg_num;
$this->_password = $c_password;
}
public function StudLogin(){
global $conn;
// starting session
session_start();
// valiidate errors
$error_msg_array = array();
// error msg
$error_msg = FALSE;
if($this->_reg_num == ""){
$error_msg_array[] = "Please input your Registration Number";
$error_msg = TRUE;
}
if($this->_password == ""){
$error_msg_array[] = "Please input your password";
$error_msg = TRUE;
}
if($error_msg){
$_SESSION['ERROR_MSG_ARR'] = $error_msg_array;
header("location: http://localhost/project/index.php");
exit();
}
$sql = "SELECT * FROM students WHERE regnumber ='$reg_num' AND password ='$password' LIMIT 1";
if(!$stmt = $conn->prepare($sql)){
echo $stmt->error;
} else {
$stmt->bind_param("ss", $this->_reg_num, $this->_password);
$stmt->execute();
$result = $stmt->get_result();
}
if($result->num_rows > 0) {
// login successful
$row = $result->fetch_assoc();
// session creation
session_regenerate_id();
$_SESSION['reg_num'] = $row["regnunmber"];
$_SESSION['name'] = $row["name"];
session_write_close();
header("location: http://localhost/project/stud_page.php");
} else {
// Login failed
$error_msg_array[] = "The Registration Number and Password you entered is incorrect.";
$error_msg = TRUE;
if($error_msg) {
$_SESSION['ERROR_MSG_ARR'] = $error_msg_array;
header("location: http://localhost/project/index.php");
exit();
}
$stmt->free_result();
}
$result->free();
return $result;
}
}
?>
MySQL database, table students contains the following columns:
$sql="INSERT INTO `students`(`name`, `education`, `regnumber`, `nationality`, `gender`, `phone`, `photo`, `branch`,`password`)
VALUES ('$name','$education','$reg_num','$nationality','$gender','$phone','$target_file','$branch','$ency_pass')";
You have validation on login.php, which is not loaded before form is send.
And if you can i would recommend you using dibi, because this work with database is not properly right and can cause some problems if u are going to use that in production
https://dibiphp.com/en/

php login script works only when password is true. "else" doesn't works

Why, if I enter a valid username and password, does it work, but when I enter a fake password it doesn't work? Below is my script.
Sign-In.html:
<!DOCTYPE html>
<html lang="">
<head>
<title>LOG-IN</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link href="../layout/styles/layout.css" rel="stylesheet" type="text/css" media="all">
</head>
<body id="top">
<div class="wrapper row1">
<header id="header" class="hoc clear">
<h1>Melis & Morganti</h1>
<p>Hardware Information</p>
</header>
</div>
<div class="wrapper row4">
<nav id="mainav" class="hoc clear">
<ul class="clear">
<li class="active">Home</li>
<li><a class="drop" href="#">ACCOUNT</a>
<ul>
<li>LOG-IN</li>
<li>REGISTER</li>
</ul>
</ul>
</nav>
</div>
<div class="wrapper bgded overlay" style="background-image:url('../images/demo/backgrounds/login.jpg');">
<section id="breadcrumb" class="hoc clear">
<ul>
<li>Home</li>
<li>LOG-IN</li>
</ul>
<h6 class="heading">LOG-IN</h6>
</section>
</div>
<div class="wrapper row3">
<main class="hoc container clear">
<div class="content">
<div id="gallery">
<figure>
<body id="body-color">
<div id="Sign-In">
<fieldset style="width:30%"><legend>Inserisci i tuoi dati</legend>
<form method="POST" action="connectivity.php">
Utente <br><input type="text" name="user" size="40"><br>
Password <br><input type="password" name="pass" size="40"><br>
<input id="button" type="submit" name="submit" value="Log-In">
</form>
</fieldset>
</div>
</body>
</figure>
</div>
</div>
<div class="clear"></div>
</main>
</div>
<div class="wrapper row4">
<footer id="footer" class="hoc clear">
<div class="one_third first">
<h6 class="heading">Sede Legale</h6>
<ul class="nospace btmspace-30 linklist contact">
<li><i class="fa fa-map-marker"></i>
<address>
Via Teano
</address>
</li>
<li><i class="fa fa-phone"></i> +00 0612345678</li>
<li><i class="fa fa-envelope-o"></i> infohardware#MelisMorganti.com</li>
</ul>
</div>
<div class="one_third">
<h6 class="heading"> </h6>
<ul class="nospace linklist">
</ul>
</div>
<div class="one_third">
<h6 class="heading">Newsgroup</h6>
<p class="nospace btmspace-30">Ricevi aggiornamenti</p>
<form method="post" action="#">
<fieldset>
<legend>Newsletter:</legend>
<input class="btmspace-15" type="text" value="" placeholder="Name">
<input class="btmspace-15" type="text" value="" placeholder="Email">
<button type="submit" value="submit">INVIO</button>
</fieldset>
</form>
</div>
</footer>
</div>
<div class="wrapper row5">
<div id="copyright" class="hoc clear">
<p class="fl_left">Copyright © 2017 - All Rights Reserved - Melis - Morganti: Hardware Information</p>
</div>
</div>
<a id="backtotop" href="#top"><i class="fa fa-chevron-up"></i></a>
<!-- JAVASCRIPTS -->
<script src="layout/scripts/jquery.min.js"></script>
<script src="layout/scripts/jquery.backtotop.js"></script>
<script src="layout/scripts/jquery.mobilemenu.js"></script>
</body>
</html>
And this is the connectivity.php:
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
define('DB_HOST', 'localhost');
define('DB_NAME', 'login');
define('DB_USER','root');
define('DB_PASSWORD','');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Impossibile connettersi: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Impossibile connettersi: " . mysql_error());
/*
$ID = $_POST['user'];
$Password = $_POST['pass'];
*/
function SignIn() {
session_start();
//starting the session for user profile page
if(!empty($_POST['user']))
{
$query = mysql_query("SELECT * FROM UserName where userName = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
if(!empty($row['userName']) AND !empty($row['pass']))
{
$_SESSION['userName'] = $row['pass'];
echo "Sei loggato con successo";
echo "<script> window.location.assign('index_success.html'); </script>";
}
else
{
echo "ID o password sbagliata";
}
}
}
if(isset($_POST['submit']))
{
SignIn();
}
?>
Why doesn't it work? I tried to use header(), but it doesn't work.
When I use a real username and password, it works: it shows "Sei loggato con successo" for 0.1 milliseconds and it redirects me to "index_success.html". But when I use a fake username or fake password, it sends me to "connectivity.php" without a message or error. It is blank!
WARNING: Little Bobby says your script is at risk for SQL Injection Attacks.. Even escaping the string is not safe!
DANGER: Please stop using mysql_* functions. These extensions have been removed in PHP 7. Learn about prepared statements for PDO and MySQLi and consider using PDO, it's really pretty easy.
Here is how to fix your problem using the mysql_* API with proper hashing of the password:
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
define('DB_HOST', 'localhost');
define('DB_NAME', 'login');
define('DB_USER','root');
define('DB_PASSWORD','');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Impossibile connettersi: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Impossibile connettersi: " . mysql_error());
session_start();
function SignIn($user, $pw) {
$user = mysql_real_escape_string($user);
$query = mysql_query("SELECT * FROM UserName where userName = '{$user}'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
if(!empty($row))
{
if(password_verify($pw, $row['pass']))
{
$_SESSION['userName'] = $row['user'];
echo "Sei loggato con successo";
echo "<script> window.location.assign('index_success.html'); </script>";
}
else
{
echo "ID o password sbagliata";
}
}
else
{
echo "There is a problem";
}
}
if(isset($_POST['submit']))
{
SignIn($_POST['user'], $_POST['pass']);
}
?>
In this code I have used PHP's built-in functions to handle password security. If you're using a PHP version less than 5.5 you can use the password_hash() compatibility pack. It is not necessary to escape passwords or use any other cleansing mechanism on them before hashing. Doing so changes the password and causes unnecessary additional coding.

Login authentication not working for my site

The codes for site is given below. Login cannot be authenticated with what I've done. Firstly, it will redirect to the login page as expected if not logged in. Then, after I clearly give the login details correctly, it won't redirect me to the site I want. Instead, it will remain on login page. Please help me...
<!--This is the page that I want to redirect after successful login-->
<?php
session_start();
if($_SESSION['loggedIn'])
{
header('Location: restaurant.php');
}
else
{
header('Location: login.php');
}
?>
<html lang="en">
<head>
<title>Welcome to Foodline</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="stylesheet" href="bootstrap/dist/css/bootstrap.min.css">
<link href="css/simple-sidebar.css" rel="stylesheet">
<script src="bootstrap/js/jquery.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="js.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<style>
/* Remove the jumbotron's default bottom margin */
.jumbotron {
margin-bottom: 0;
}
/* Add a gray background color and some padding to the footer */
footer {
background-color: #f2f2f2;
padding: 25px;
}
</style>
</head>
<body>
<div class="jumbotron">
<div class="container text-center">
<h1><font face="Analecta">FOODLINE</font></h1>
<p>We provide the best service for our costumers</p>
</div>
</div>
<nav class="navbar navbar-inverse" data-spy="affix" data-offset-top="197">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand"><font face="Analecta" color="white">>Restaurants<</font></a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li>
Hamro Didi (HD)
</li>
<li>
HK
</li>
<li>
Junu Hotel
</li>
<li>
Junction Cafe
</li>
<li>
Laxmi Hotel
</li>
</ul>
</div>
</div>
</nav>
<footer class="container-fluid text-center">
<p>Foodline Official Website &copy</p>
<p align="center">Logged in as: <div id="username" align="center"> <span class="glyphicon glyphicon-log-in"></span><?php
if(isset($_GET['id'])){
echo ' '.$_GET['id'];
}
else {
echo '(write) a 404 page';
}
?>
</div>
</p>
</footer>
</div>
<!--This is login.php-->
<?php
//session_start();
include("connection.php");
$msg='';
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// username and password sent from form
$username = $_POST['username'];
$password = $_POST['password'];
// To protect MySQL injection
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
//Input Validations
if($username == '') {
$_SESSION["login_user"] = $username; $msg = "Username missing";
header("location: login.php?msg=$msg");
}
if($password == '') {
$msg = "Password missing";
header("location: login.php?msg=$msg");
}
//Create query
$qry="SELECT * FROM user WHERE user_name='$username' AND user_password='$password'";
$result =mysql_query($qry)or die(mysql_error());
$output=mysql_fetch_assoc($result);
//Check whether the query was successful or not
if(!empty($output)) {
//Login Successful
$_SESSION['name']= $username;
$_SESSION['loggedIn'] = true;
header("location:restaurant.php?id=$username");
}
else {
//Login failed
$msg= "user name and password not found";
header("location:login.php?msg=$msg");
}
}
?>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="bootstrap/dist/css/bootstrap.min.css">
<script src="bootstrap/js/jquery.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<style>
.jumbotron {
margin-bottom: 0;
}
</style>
</head>
<body>
<div class="jumbotron">
<div class="container text-center">
<h1><font face="Analecta">FOODLINE</font></h1>
<p>We provide the best service for our costumers</p>
</div>
</div>
<nav class="navbar navbar-inverse" data-spy="affix" data-offset-top="197">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="index.php">Logo</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li>Restaurants</li>
<li>Contact</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><span class="glyphicon glyphicon-user"></span> Sign Up</li>
<li><span class="glyphicon glyphicon-log-in"></span> Login</li>
</ul>
</div>
</div>
</nav>
<div class="container">
<h2><font face="Analecta">>Login from here<</font></h2>
<form role="form" name="login" action="login.php" method="post" accept-charset="utf-8">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" name="username" placeholder="Enter username" required>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" name="password" placeholder="Enter password" required>
</div>
<div class="checkbox">
<label><input type="checkbox"> Remember me</label>
</div>
<button type="submit" class="btn btn-default" value="login">Submit</button>
<br>
<br>
<?php
$msg = (isset($_GET['msg']) ? $_GET['msg'] : null); //GET the message
if($msg!='') echo '<p>'.$msg.'</p>'; //If message is set echo it
?>
</form>
<p>Not a user yet? Sign up here</p>
</div>
<footer class="container-fluid text-center">
<p>Foodline Official Website &copy</p>
<p>Get deals:
<span class="glyphicon glyphicon-menu-right"></span>SignUp
</p>
</footer>
</body>
</html>
Uncomment:
//session_start();
From line 5 in login.php and change to this:
if(! $_SESSION['loggedIn']) {
header('Location: login.php');
}
in restaurant.php.

Have Existing Login/User system, want to know how to create a folder when user signs up

I have an existing login/register system that I would like to make so you that when you sign up it automatically creates a directory with your username, I have put my original register script below. I have included the entire register file code so you will have to excuse the mess
<?php include "../assets/database/160216.php"; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/>
<title>Connect With Me</title>
<!-- CSS -->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="../../assets/css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/>
<link href="../../assets/css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>
</head>
<body>
<!-- Scripts-->
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="../../assets/js/materialize.js"></script>
<script src="../../assets/js/init.js"></script>
<header>
<!--Navigation Menu-->
<div class="navbar-fixed">
<nav class="white" role="navigation">
<div class="nav-wrapper container">
<a id="logo-container" href="../../index.html" class="brand-logo">Connect With Me</a>
<ul class="right hide-on-med-and-down">
<li>About</li>
<li>Contact</li>
<li>Login</li>
</ul>
<ul id="nav-mobile" class="side-nav">
<li>About</li>
<li>Contact</li>
<li>Login</li>
</ul>
<i class="material-icons">menu</i>
</div>
</nav>
</div>
<!--Image Header With Text-->
<div id="index-banner" class="parallax-container">
<div class="section no-pad-bot">
<div class="container">
<br><br>
<br> <h1 class="header center teal-text text-lighten-2"><br>Register</h1>
<div class="row center">
<h5 class="header col s12 light">Register And Start Using Immediately.</h5>
</div>
<br><br>
</div>
</div>
<div class="parallax"><img src="../../assets/images/bg.jpg" alt="Unsplashed background img 1"></div>
</div>
</header>
<div id="main" class="center">
<?php
if(!empty($_POST['username']) && !empty($_POST['password']))
{
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
$email = mysql_real_escape_string($_POST['email']);
$checkusername = mysql_query("SELECT * FROM users WHERE Username = '".$username."'");
if(mysql_num_rows($checkusername) == 1)
{
echo "<h1>Error</h1>";
echo "<p>Sorry, that username is taken. Please go back and try again.</p>";
}
else
{
$registerquery = mysql_query("INSERT INTO users (Username, Password, EmailAddress) VALUES('".$username."', '".$password."', '".$email."')");
if($registerquery)
{
echo "<h1>Success</h1>";
echo "<p>Your account was successfully created. Please click here to login.</p>";
}
else
{
echo "<h1>Error</h1>";
echo "<p>Sorry, your registration failed. Please go back and try again.</p>";
}
}
}
else
{
?>
<main>
<br>
<div class="container">
<div class="section">
<form method="post" action="index.php" name="registerform" id="registerform" class="col s12">
<div class="row">
<div class="input-field col s12">
<input type="text" name="username" id="username">
<label for="username">Username</label>
</div>
<div class="input-field col s12">
<input id="password" type="password" name="password" class="validate">
<label for="password">Password</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="email" type="text" name="email" id="email" class="validate">
<label for="email">Email</label>
</div>
</div>
<button class="btn waves-effect waves-light center" type="submit" name="register" id="register">Register</button>
</form>
</div>
<?php
}
?>
</div>
</body>
</html>
Many Thanks I hope one of you has a suggestion/ idea.
Update- Thanks For The Comments, These Have Been Very Helpful.
You can try something like this:
mkdir($_SERVER["DOCUMENT_ROOT"] . $destinationPath . $userName ,0777,true);
Is what I use to create thumbnails folders.
For further information check the official PHP mkdir manual.
You should be able to create dir with your username using mkdir defined function in PHP:
<?php
mkdir("/path/to/my/dir", 0700);
?>
Here is the manual for mkdir().
You can insert your code after this snippet of yours:
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
$email = mysql_real_escape_string($_POST['email']);
$checkusername = mysql_query("SELECT * FROM users WHERE Username = '".$username."'");
if(mysql_num_rows($checkusername) == 1)
{
$folderPath = "/path/to/your/dir".$username;
if (!is_dir($folderPath)) {
//--. CODE TO CREATE FOLDER HERE
mkdir($folderPath, 0700);
}
But you should not be using mysql. Its deprecated in latest version of php. You should use mysqli.
The mkdir() function creates a directory.
This function returns TRUE on success, or FALSE on failure.
And by this moment you can first check whether your registration has been successful and then you can run your mkdir() function
if($registerquery)
{
mkdir('/test1/'.$username, 0777, true);
echo "<h1>Success</h1>";
echo "<p>Your account was successfully created. Please click here to login.</p>";
}

Unable to return to 'User Profile' page after login

I have login.php page for the user to login their credentials. After the user logs in that is when the doLogin.php page will be displayed. In other words their user profile will be displayed. On the User Profile element, there is an edit button which leads them to editProfile.php page to edit their personal info. However when I clicked the back arrow on my tab to go to the User profile page back an error "Confirm Form Resubmission" was displayed. How do I counter this such that when the user wished to go back to the User Profile page, their details will be displayed?
This is my doLogin.php
session_start();
$msg = "";
//check whether session variable 'user_id' is set
//in other words, check whether the user is already logged in
if (isset($_SESSION['user_id'])) {
$msg = "You are already logged in.<br/><a href='index.php'>Home</a>";
$msg = "<a href ='logout.php'>logout</a>";
} else { //user is not logged in
//check whether form input 'username' contains value
if (isset($_POST['username'])) {
//retrieve form data
$entered_username = $_POST['username'];
$entered_password = $_POST['password'];
//connect to database
include ("dbfunctions.php");
//match the username and password entered with database record
$query = "SELECT *from role,user
WHERE user_name='$entered_username' AND
PASSWORD = SHA1('$entered_password') AND user.role_id = role.role_id";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
$query2 = "SELECT * FROM user,country where user.country_id=country.country_id ORDER BY `user`.`id` ASC ";
$result2 = mysqli_query($link, $query2) or die(mysqli_error($link));
$query3 = "SELECT * FROM book";
$result3 = mysqli_query($link, $query3) or die(mysqli_error($link));
if (mysqli_num_rows($result) == 1) {
$update = "UPDATE `user` SET last_login = NOW() WHERE user_name='$entered_username' ";
$resultupdate = mysqli_query($link, $update);
$row = mysqli_fetch_array($result);
$_SESSION['user_id'] = $row['id'];
$_SESSION['username'] = $row['user_name'];
$_SESSION['email'] = $row['email_address'];
$_SESSION['gender'] = $row['gender_id'];
$_SESSION['role_id'] = $row['role_type'];
$_SESSION['lastlog'] = $row['last_login'];
$msg1 = $_SESSION['username'];
$msg2 = "<b>Gender: </b> " . $_SESSION['gender'] . "<br/>";
$msg3 = "<b>Email: </b>" . $_SESSION['email'] . "<br/>";
$msg4 = "<b>Your last visit on this site: </b>" . $_SESSION['lastlog'];
$msg .= "You are logged in as " . $_SESSION['role_id'] . "<br/>";
$rowz = mysqli_fetch_array($result3);
} else { //record not found
$msg = "<p>Sorry, you must enter a valid username and password to log in.<a href='login.php'>Back</a></p>";
}
}
and this is my editProfile.php
// include a php file that contains the common database connection codes
include ("dbfunctions.php");
session_start();
$userID = $_POST['userID'];
$queryedit = "SELECT * FROM user WHERE id=$userID";
// execute the query
$resultedit = mysqli_query($link, $queryedit) or die(mysqli_error($link));
// fetch the execution result to an array
$rowedit = mysqli_fetch_array($resultedit);
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="style.css" rel="stylesheet" type="text/css"/>
<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="font-awesome/css/font-awesome.min.css" />
<script src="script.js"></script>
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="styles.css">
<title>Edit Profile & Settings</title>
</head>
<body>
<div class="container">
Sign Out
<div class="page-header">
<h1>OBC <small>onlinebookclub</small></h1>
<div class="row">
<div class="col-lg-6">
<form method="post" action="doSearch.php">
<div class="input-group">
<span class="input-group-btn">
<button class="btn btn-default" type="submit">Go!</button>
</span>
<input type="text" class="form-control" placeholder="Title/Author/YearOfPublish">
</form>
</div><!-- /input-group -->
</div><!-- /.col-lg-6 -->
</div><!-- /.row -->
</div>
</div>
<!-- Registration Form - START -->
<div class="container" id="container1">
<div id='cssmenu'>
<ul>
<li class='active'><a href='#'>Profile</a></li>
<li><a href='addbook.php'>Add/Edit Books</a></li>
<li><a href='#'>Add/Edit Authors</a></li>
<li><a href='editProfile.php'>Edit Profile & Settings</a></li>
</ul>
</div>
<h2>Edit Profile</h2>
<hr>
<div class="row">
<!-- left column -->
<div class="col-md-3">
<div class="text-center">
<img src="//placehold.it/100" class="avatar img-circle" alt="avatar">
<h6>Upload a different photo...</h6>
<input type="file" class="form-control">
</div>
</div>
<!-- edit form column -->
<div class="col-md-9 personal-info">
<h3>Personal info</h3>
<form class="form-horizontal" role="form">
<div class="form-group">
<label class="col-lg-3 control-label">Username:</label>
<div class="col-lg-8">
<input class="form-control" type="text" value="<?php echo $rowedit['user_name'] ?>">
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Email:</label>
<div class="col-lg-8">
<input class="form-control" type="text" value="<?php echo $rowedit['email_address'] ?>">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label"></label>
<div class="col-md-8">
<input type="hidden" name="id" value="<?php echo $rowedit['id'] ?>" />
<input type="submit" class="btn btn-primary" value="Save Changes">
<span></span>
<input type="reset" class="btn btn-default" value="Cancel">
</div>
</div>
</form>
</div>
</div>
</div>
<style>
#container1 {
background-color: #e2dada;
opacity: 0.9;
border-radius: 2em;
}
.centered-form {
margin-top: -185px;
margin-bottom: 120px;
}
.centered-form .panel {
background: rgba(255, 255, 255, 0.8);
box-shadow: rgba(0, 0, 0, 0.3) 20px 20px 20px;
}
h2{
color: orange;
}
</style>
</body>
First Way
One way of handling such errors is to redirect the page to itself.
i.e when the user logs in and when you show the doLogin page, i.e the user profile page, ry to use the header() function
header('Location:doLogin.php');
Second Way
You can make an AJAX redirect using jQuery or something

Categories