Username hidden html + php - php

I have problem with html and php,so I created login page and all functions for login,but I want to put username in header (Like a facebook) and have problem.Username is hidden when I add php code.
Everything work perfect,here is my HTML code.
pocetna.html
<?php
session_start();
?>
<html>
<head>
<title>
weekta RolePlay | Pocetna
</title>
<link rel="stylesheet" href="style/styless.css">
<link href="https://fonts.googleapis.com/css2?family=Jost&display=swap" rel="stylesheet">
</head>
<body>
<header>
<a class="logo" href="/" style="text-decoration: none;color: #1260a8;font-size: 30px;font-family: 'Jost', sans-serif;"><p>weekta</p></a>
<nav>
<ul class="nav__links">
<li>Services</li>
<li>Projects</li>
<li>About</li>
<li><span><?php echo( $_SESSION['korisnickoime'] );?></span></li>
</ul>
</nav>
<a class="cta" href="index.html">Login</a>
<p class="menu cta">Menu</p>
</header>
<div id="mobile__menu" class="overlay">
<a class="close">×</a>
<div class="overlay__content">
Services
Projects
About
</div>
</div>
<script type="text/javascript" src="mobile.js"></script>
</body>
</html>
And here is login_process.php
<?php
$mysql_host="localhost";
$mysql_user="root";
$mysql_password="";
$mysql_db="weekta";
$conn = mysqli_connect($mysql_host,$mysql_user,$mysql_password);
mysqli_select_db($conn, 'weekta');
session_start();
if(isset($_POST['korisnickoime'])){
$username=$_POST['korisnickoime'];
$password=$_POST['sifrajedan'];
$sql="SELECT * FROM loginform where korisnickoime='".$username."'AND sifrajedan='".$password."' limit 1";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result)==1){
header("Location:pocetna.html");
echo " Dobodosao $username";
exit();
}
else{
echo " Pogresna lozinka.";
exit();
}
}
?>
Can someone help me?Thanks.

You are not setting $_SESSION['username'] after your user was found in the db.
Im not a PHP expert, but you need to do something like $_SESSION['username'] = 'xyz' i think. Besides that your select query is vunerable to sql injection.
https://www.php.net/manual/en/security.database.sql-injection.php

In your script there is one mistake
$sql="SELECT * FROM loginform where korisnickoime='".$username."'AND sifrajedan='".$password."' limit 1";
in this query near username where korisnickoime='".$username."'AND sifrajedan='".$password."' there is not space between $username and AND.
The end result of this query after appending username and password will be like
SELECT * FROM loginform where korisnickoime='user1'AND sifrajedan='xyz' limit 1";
This Query will break so please add a little space between, replace your Query string with this.
$sql="SELECT * FROM loginform where korisnickoime='".$username."' AND sifrajedan='".$password."' limit 1";
Your PHP script could be like this
index.php
<form method="post" name="login">
<label for="username">Username:</label><br>
<input type="text" name="username"><br>
<label for="password">Password:</label><br>
<input type="password" name="password"><br>
<button type="submit" name="login">Log in</button>
</form>
<?php
session_start();
if(isset($_POST['username']) and isset($_POST['password']))
{
$username = $_POST['username'];
$pass = $_POST['password'];
$query = "SELECT * FROM `person` WHERE name='$username' and pass='$pass'";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);
if ($count == 1){
$_SESSION['username'] = $username;
header('Location: homepage.php');
}
else
{
$msg = "Wrong credentials";
}
}
if(isset($msg) & !empty($msg)){
echo $msg;
}
?>
Then in homepage.php
<nav>
<ul class="nav__links">
<li>Services</li>
<li>Projects</li>
<li>About</li>
<li><a href="#">
<span>
<?php
session_start();
if(!isset($_SESSION['username']))
{
die("You are not logged in!");
}
$username = $_SESSION['username'];
echo "Hai " . $username;
?>
</span></a></li>
</ul>
</nav>
PS: TO make your Query Secure use parameterized query like this
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare(SELECT * FROM loginform where korisnickoime='?' AND sifrajedan='?' limit 1");
$stmt->bind_param("ss", $username, $password);
// set parameters and execute
$username = "John";
$password = "Doe";
$result = $stmt->execute();
?>

Related

How not let user go back to login.php without logging out?

I have a login.php, loginer.php, registration.php, register.php, logout.php, logouter.php, dashboard.php and menu.php file as well. The menu.html is included into my dashboard.php because the menu.html contains the button which I have to click on if I would like log out.
I have the folder of the project of mine in htdocs. Inside the project's folder I have a 'hu' folder because the website is in hungarian language at the moment. Inside this 'hu' folder I have all the mentioned .php files apart from dashboard.php and menu.html because these 2 files are in the 'registered' folder which is also inside the 'hu' folder.
I have a registration-login system. But when I log in I do not need to sign out forward to get to login.php because I just have to click on the "back" button.
Why is it happening?
I have already tried to write "session_destroy();" to almost everywhere. I did not work.
This is how login.php looks like:
<!DOCTYPE html>
<html>
<head>
<title>Bejelentkezés | LASOW Projekt</title>
<link rel="stylesheet" href="css/login.css">
</head>
<body>
<?php
include 'navbar.html';
?>
<div class="main">
<h1>Bejelentkezés</h1>
<form action="loginer.php" method="POST">
<label for="">Email:</label><br>
<input type="text" name="emailaddress"><br>
<label for="Jelszó:">Jelszó:</label><br>
<input type="password" name="password"><br>
<input name="login" type="submit" value="Belépek">
</form>
</div>
</body>
</html>
This is how loginer.php looks like:
<?php
session_start();
include '../connect.php';
$error = ""; //Variable for storing our errors.
if(isset($_POST["login"]))
{
if(empty($_POST["emailaddress"]) || empty($_POST["password"]))
{
$error = "Mindkét mező kitöltése kötelező!";
}else
{
// Define $username and $password
$emailaddress=$_POST['emailaddress'];
$password=$_POST['password'];
// To protect from MySQL injection
$emailaddress = stripslashes($emailaddress);
$password = stripslashes($password);
$emailaddress = mysqli_real_escape_string($conn, $emailaddress);
$password = mysqli_real_escape_string($conn, $password);
$password = md5($password);
//Check username and password from database
$sql="SELECT id,emailaddress,password FROM users WHERE emailaddress='$emailaddress' and password='$password'";
$result=mysqli_query($conn,$sql);
//$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
//email és jelszó létezése esetén folytatódik a folyamat
//Otherwise echo error.
if(mysqli_num_rows($result) == 1)
{
$_SESSION['emailaddress'] = $emailaddress; // Initializing Session
header("location: registered/dashboard.php"); // átirányítás a login.php-re
}else
{
$error = "Helytelen email vagy jelszó";
}
}
}
?>
This is how register.php looks like:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
if(isset($_POST["register"])){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "lasowcompany";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
mysqli_set_charset($conn,"utf8");
//nem $POST hanem $_POST a htmlspecialchars nem enged javasrcipt kódot be írni az adatbázisba
$surname = htmlspecialchars($_POST['surname']);
$firstname = htmlspecialchars($_POST['firstname']);
$emailaddress = htmlspecialchars($_POST['emailaddress']);
$phonenumber = htmlspecialchars($_POST['phonenumber']);
$password = md5($_POST['password']);
$passwordconfirm = md5($_POST['passwordconfirm']);
if(empty($surname))
{
echo "A vezetéknevet meg kell adnod!";
}
elseif(empty($firstname))
{
echo "A keresztnevet meg kell adnod";
}
elseif(empty($emailaddress))
{
echo "Az email címet meg kell adnod";
}
elseif($password != $passwordconfirm)
{
echo "A megadott jelszavak nem egyeznek";
}
elseif(strlen($password) < 6)
{
echo "Minimum 6 karakteres lehet a jelszó";
}
elseif(empty($password))
{
echo "A kívánt jelszót meg kell adnod";
}else{
$sql = "INSERT
INTO
users
(surname,
firstname,
emailaddress,
phonenumber,
password)
VALUES
('".$surname."',
'".$firstname."',
'".$emailaddress."',
'".$phonenumber."',
'".$password."')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
header('Location: dashboard.php');
}
}
/*$sql = "INSERT INTO users (surname, firstname, emailaddress, phonenumber, password, passwordconfirm)
VALUES ('".$_POST["surname"]."','".$_POST["firstname"]."','".$_POST["emailaddress"]."','".$_POST["phonenumber"]."','".$_POST["password"]."','".$_POST["passwordconfirm"]."')";
*/
?>
</body>
</html>
logout.php:
<?php
session_start();
unset($_SESSION['emailaddress']);
header("Location: logouter.php");
?>
dashboard.php:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<style>
h2 { text-align: center; }
</style>
</head>
<body>
<?php
if(isset($_SESSION['emailaddress'])){
include 'menu.html';
}else{
header("Location: ../logout.php");
exit();
}
?>
<h2>Üdv a LASOW rendszerében</h2>
</body>
</html>
menu.html:
<ul>
<li><span style="font-size:30px;cursor:pointer" onclick="openNav()">☰</span></li>
<li><a class="active" href="#home">Főoldal</a></li>
</ul>
<div id="mySidenav" class="sidenav">
×
Főoldal
Tudás
Profil
Kilépés
</div>
<script>
function openNav() {
document.getElementById("mySidenav").style.width = "30%";
}
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
}
</script>
Do not let user to go back to login.php if user did not log out.
you have to use the sessions in every pages that you want to be tracked

Deleting Row from users table PHP MYSQL

I would like to delete a row from my users table when the user clicks a button, the user needs to be logged in do delete their own account.
I have echo'd the $user_id which shows '4', which is the correct id for the logged in user, so user_id = $user_id
This is the page that I have which holds the button which I want to delete the users row in the database
<?php
include_once 'dbconfig.php';
if(!$user->is_loggedin())
{
$user->redirect('index.php');
}
$user_id = $_SESSION['user_session'];
if(isset($_POST['leave'])){
$stmt = $DB_con->prepare("DELETE FROM users WHERE user_id = $user_id ");
$stmt->execute();
}
$stmt = $DB_con->prepare("SELECT * FROM users WHERE user_id=:user_id");
$stmt->execute(array(":user_id"=>$user_id));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="style.css" type="text/css" />
<title>Welcome - <?php print($userRow['user_email']); ?></title>
</head>
<body>
<div class="header">
<div class="right">
<label><i class="glyphicon glyphicon-log-out"></i> logout</label>
</div>
</div>
<div class="content">
Welcome <?php print($userRow['user_name']); ?> <br>
<?php print($userRow['team_name']);?><br>
Rank <?php print($userRow['user_rank']); ?> <br>
Players
Teams
<form action='teams.php' method='post'>
<input type='submit' name='leave' value='Delete Profile'/> </form>
<?php echo $user_id?>
</div>
</body>
</html>
I think your problem is your form action(teams.php) which will receive the post data.Your delete code is on the same file and logically $_POST['leave'] will never be set in this page.
Just try to remove your teams.php in your forms action attribute.
<form action='' method='post'>
<input type='submit' name='leave' value='Delete Profile'/> </form>
or in your teams.php file add your delete code
//Make sure you have started the session before using it
$user_id = $_SESSION['user_session'];
if(isset($_POST['leave'])){
$stmt = $DB_con->prepare("DELETE FROM users WHERE user_id = $user_id ");
$stmt->execute();
}
Another piece of advise is use parameterize query.
Example:
if(isset($_POST['leave'])){
$stmt = $DB_con->prepare("DELETE FROM users WHERE user_id = ? ");
$stmt-> bindParam(1,$user_id);
$stmt->execute();
}
<?php $servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} ?>
Delete
<?php if(isset($_GET['id'])){
$user_id = $_SESSION['user_session'];
$id=$_GET['id'];
if($id==$user_id){
$sql = "DELETE FROM Tablename WHERE id='$id'";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
}
}?>

This webpage has a redirect loop - PHP Login

I'm trying out a login page example in php. I get the error: This webpage has a redirect loop
Details say: Error code: ERR_TOO_MANY_REDIRECTS
Here's my code:
index.php
<?php
include('login.php'); // Includes Login Script
if(isset($_SESSION['login_user'])){
header("location: profile.php");
}
?>
<form action="" method="post">
<label>UserName :</label>
<input id="name" name="username" placeholder="username" type="text">
<label>Password :</label>
<input id="password" name="password" placeholder="**********" type="password">
<input name="submit" type="submit" value=" Login ">
<span><?php echo $error; ?></span>
</form>
login.php
<?php
session_start();
$error='';
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
$username=$_POST['username'];
$password=$_POST['password'];
$connection = mysql_connect("localhost", "root", "");
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$db = mysql_select_db("rjtest", $connection);
$query = mysql_query("select * from login where myPassword='$password' AND myUserName='$username'", $connection);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$username;
header("location: profile.php");
} else {
$error = "Username or Password is invalid";
}
}
}
?>
profile.php
<?php
include('session.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Your Home Page</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="profile">
<b id="welcome">Welcome : <i><?php echo $login_session; ?></i></b>
<b id="logout">Log Out</b>
</div>
</body>
</html>
session.php
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("rjtest", $connection);
session_start();
$user_check=$_SESSION['login_user'];
$ses_sql=mysql_query("select myUsername from login where myUsername='$user_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
$login_session =$row['username'];
if(!isset($login_session)){
header('Location: index.php');
}
?>
And logout.php
<?php
session_start();
if(session_destroy())
{
header("Location: index.php");
}
?>
I can't seem figure out why. The site where I got this code is now inactive, so that's why Im asking this here. Hope you guys could help me out. Sorry for the long post though.
Comment to answer:
What I think is going on is that your code is erroring out and you're not seeing it, causing it to fight against what it should be showing you as an error.
You have $login_session =$row['username']; using the "username" as the row, but you're not selecting it in your query select myUsername from login where myUsername.
So, I'm thinking that if that row doesn't in fact exist, you'd need to do
$login_session =$row['myUsername'];

login page, circular redirection+including a header

I have a problem with circular redirection on the page. I don't know how I can escape it. I have a header page with all the db connectivity and the session check for all the other pages. I need to include it into login page but I don't want the menu to be displayed on it, I only need the header for the db connectivity.
But I cannot do it because since I have session check, I keep on getting the browser message 'circular redirection'.
Is there any way to fix it and still have the header on the login page?
my code:
admin_header
<?php
session_start();
define('ADMIN',$_SESSION['username']);
if(!$_SESSION['username'])
{
header("location:admin_login.php");
}
?>
<html>
<head>
<title>Project</title>
<link type="text/css" rel="stylesheet" href="styles.css"/>
</head>
<body id="home">
<div class="top" id="header">
<ul>
<li><a class="menu" href="index.php">Home</a></li>
<li><a class="menu" href="search.php">Add an Artist</a></li>
<li><a class="menu" href="contact.php">List the Artists</a></li>
<li><a class="menu" href="contact.php">Add a movie</a></li>
<li><a class="menu" href="contact.php">List the movies</a></li>
<li><a class="menu" href="contact.php">Add an admin</a></li>
<
</ul>
</div>
<?php
$server = 'localhost';
$user = 'root';
$pass = 'blablabla';
$mydb = 'projectdb';
$movies = 'movies';
$artists='artists';
$roll='roll';
$users='Users';
$connect = mysqli_connect($server, $user, $pass);
mysqli_select_db($connect,$mydb)or die("cannot select DB");
session_start();
define('ADMIN',$_SESSION['username']);
if(!$_SESSION['username'])
{
header("location:admin_login.php");
}
?>
</body></html>
admin_login
<?php
include ('admin_header.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<?php
$login_form = <<<EOD
<form name="login" id="login" method="POST" action="">
<p><label for="username">Please Enter Username: </label><input type="text" size="40" name="username" id="username" value="" /></p>
<p><label for="password">Please Enter Password: </label><input type="password" size="40" name="password" id="password" value="" /></p>
<p><input type="submit" name="submit" id="submit" value="Submit"/> <input type="reset" name="reset" id="reset" value="reset"/></p>
</form>
EOD;
if (isset($_GET['msg']))
{
$msg=$_GET['msg'];
if($msg!='')
{
echo '<p>'.$msg.'</p>';
}
}
echo "<h1>Please enter your Login Information</h1>";
echo $login_form;
ob_start();
$server = 'localhost';
$pass = 'blablabla';
$mydb = 'projectdb';
$users='Users';
$connect = mysqli_connect($server, $user, $pass);
mysqli_select_db($connect,$mydb)or die("cannot select DB");
if (!isset($_POST['username'])||!isset($_POST['password']))
{
echo "Please, enter your login information";
}
else
{
$username = $_POST['username'];
$password = $_POST['password'];
if (!$connect)
{
echo ("Cannot connect to $server using $user");
}
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($connect,$username);
$password = mysqli_real_escape_string($connect,$password);
$sql="SELECT * FROM $users WHERE username='".$username."' and password='".$password."'";
$result=mysqli_query($connect,$sql);
$count=mysqli_num_rows($result);
if($count==1)
{
session_start();
header("location:admin_index.php");
$_SESSION["username"]=$username;
$_SESSION["password"]=$username;
}
else
{
$msg = "Wrong Username or Password. Please retry";
echo $msg;
}
}
ob_end_flush();
?>
</body>
</html>
Thank you so much in advance for your help!
You have this twice in the code, once on top and once at the bottom. I would recommend putting it at the top of the script, and do the define after you have checked the session. Also, I added an extra check:
session_start();
if(!$_SESSION['username'] && $page <> 'logon')
{
header("location:admin_login.php");
}
define('ADMIN',$_SESSION['username']);
Then. In your admin logon:
<?php
$page = logon;
include ('admin_header.php');
?>
In admin_header change this code:
define('ADMIN',$_SESSION['username']);
if(!$_SESSION['username'])
{
header("location:admin_login.php");
}
with this:
if(!$_SESSION['username'] && $page != 'login')
{
header("location:admin_login.php");
} elseif(isset($_SESSION['username'])) {
define('ADMIN',$_SESSION['username']);
}
and in admin_login add this line:
$page = 'login';
before you include the header.
EDIT
Try it with the elseif-condition to remove the undefined error

Validation Causing Inconsistencies

I am trying to code a simple validation exercise for a username, password combination that will validate input and point out to users where their errors are and I am getting a strange outcome that i cannot fathom out why.
If a user has a password called Password then the code validates, however if they have a password as Password1 then I get the response that the username and password combination is incorrect even though I have changed it in the database.
Would anyone have come across this issue before and how could I go about fixing it?
<html>
<head>
<title>Login</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<h1>Log In</h1>
<form action="login.php" method="post">
<ul id="login">
<li> Username: <br />
<input type ="text" name="username"/>
</li>
<li>
Password: <br/>
<input type="password" name="password"/>
</li>
<li>
<input type="submit" value="Log In"/>
</li>
<li>
Register
</li>
</ul>
<?php
$username = $_POST['username'];
$password = $_POST['password'];
function user_exists($username){
$server = 'localhost';
$user='root';
$password='';
$db = 'finance_checker';
$mysqli = mysqli_connect($server, $user, $password, $db);
if(mysqli_connect_errno($mysqli)){
echo "Failed to connect to MySQL".mysqli_connect_error();
}
$res = $mysqli->query("SELECT * FROM `users` WHERE `UserName` = '$username'");
return ($res->num_rows>0);
$res->close();
}
function userLogin ($username, $password){
$server = 'localhost';
$user='root';
$pass='';
$db = 'finance_checker';
$mysqli = mysqli_connect($server, $user, $pass, $db);
$res = $mysqli->query("SELECT * FROM `users` WHERE `UserName`='$username' AND `Password` = $password");
if($res&&$res->num_rows>0){
return true;;
}else{
return false;
}
}
if(empty($_POST)==false){
if(empty($username)==true ||empty($password)==true){
echo "Please complete both sections of the form!<br />";
} else if(empty($username)==true){
echo "You must enter a username!<br />";
} else if(empty ($password)==true){
echo "You must enter a password!<br />";
} else if (user_exists($username)==false){
echo "Username cannot be found. Click on the register link to create a new account.";
} else{
$login = userLogin($username, $password);
if($login == false){
echo 'Username and Password combination is not compatible!';
} else{
header("Location:home.php ");
}
}
}
?>
</body>
</html>
You're missing quotes:
...`='$username' AND `Password` = $password"
^-- ^--
Without them, you're inserting a bare word into the query, which MySQL will treat as a field name. Given taht 'password` works, remember that
Password = password
would be valid sql, "where this field is equal to itself".
You want:
... AND `Password` = '$password`
note the quotes.
You are are also WIDE open for SQL injection attacks, so stop working on this code until you've learned about the problem and how to avoid it. Your actual problem stems from this injection vulnerability.

Categories