Log in page on index.html - php

I currently have a login system on my index page; which is working fine. However, when a user logs in, it directs them to a completely new page which i don't want. How to I implement the code so that;
A) the user stays on the index page after login
B) A welcome message "Welcome...." displays on the index page.
index.html
<div id="leftmenu_top"></div>
<div id="leftmenu_main">
<div class="login">
<h3>Please login below</h3>
<br/>
<!--Log in form-->
<html>
<form action='login.php' method='POST'>
Username: <input type='text' name='username'><br>
Password: <input type='password' name='password'><br>
<input type='submit' value='Log in'>
</form>
</html>
login.php
<?php
session_start();
$username = strtolower($_POST['username']);
$password = strtolower($_POST['password']);
if ($username&&$password)
{
$connect = mysql_connect("localhost", "root", "") or die("Couldn't connect");
mysql_select_db("a&e") or die("Couldn't find db");
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrows = mysql_num_rows($query);
if ($numrows==!0)
{
//code to login
while ($row = mysql_fetch_assoc($query))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
//check to see if they match
if($username==$dbusername&&$password==$password)
{
echo "Welcome $username";
$_SESSION['username']=$username;
}
else
echo "incorrect password";
}
else
die("That user does not exist");
}
else
die("please provide a username and password");
?>

put
header('Location: index.php');
at the bottom of the login.php
Also, if you add ?success at the end of this link and then call it in your index page it will display the message you want. Change the above code to
header('Location: index.php?status=success');
and then in you index page put this where you want the message to appear
<?php If($_GET['status'] = "success") { ?>
<p>This is a welcome message</p>
<?php } ?>

<?php if(isset($_POST['submit'])){
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$query = "SELECT Username, Password FROM tbluser
WHERE Username = '$username' AND Password = '$password'";
$result = mysql_query($query) or die (mysql_error());
if(mysql_num_rows($result) == 0){
echo ' Password/Username is not found';
}else {
while($row = mysql_fetch_array($result)) {
echo 'You are logged in </br>';
}
}
}

Related

Current Logged in user/admin must not delete itself (which's currently logged in)

I have a 'users' table which have two columns/attributes i-e username and password. this table holds admins of the website. now i have created a form that's used to delete one or more admins from the table mentioned above, but if currently logged in user tries to delete itself, it must not happen.
the problem i'm facing is: i have received the username and password of the currently logged in user from the session, but when i enters another admin details, still it gives me the error that currently logged in user is trying to delete itself.
FORM:
<form action="delete_user.php" method="post">
<fieldset><legend style="text-align:center; font-size:18px">Enter Details of the User You want to Delete</legend><br>
<label for="username">Username : </label><input type="text" name="username" placeholder = "Username"><br>
<label for="password">Password :</label><input type="password" name="password" placeholder = "Password"><br>
</fieldset>
<p id="btn">
<input type="submit" value="Delete" name="submit_delete_user" style="font-size:16px"><input type="reset" value="Reset" style="font-size:16px"><br>
<center>
Admin Home<br>
Logout
</center>
</p>
</form>
PHP file/CODE:
<?php session_start();
$server="localhost";
$user="root";
$password="";
$database="camouflage_studio";
$con = mysqli_connect($server,$user,$password,$database);
if (mysqli_connect_errno())
{
echo "Connection Error: " . mysqli_connect_error();
}
//reiving values from form
$username = mysqli_real_escape_string($con,$_POST['username']);
$password = mysqli_real_escape_string($con,$_POST['password']);
if(isset($_POST['submit_delete_user'])){
if(!empty($_POST['username']) && !empty($_POST['password'])){
if($username == $_SESSION['username'] && $password == $_SESSION['password']){
$sql_delete = "DELETE FROM 'users' WHERE username = '$username' AND password = '$password'";
if($result = mysqli_query($con, $sql)){
echo '<script language="javascript" type="text/javascript">
alert("Record Deleted Successfully!");
window.location = "admin.php";
</script>';
}else { echo '<script language="javascript" type="text/javascript">
alert("SQL Error!");
window.location = "delete_user_form.php";
</script>'; }
}else { echo '<script language="javascript" type="text/javascript">
alert("Sorry! You can not delete currently Logged in User");
</script>'; }
}else { echo '<script language="javascript" type="text/javascript">
alert("Please Fill the Form Completly");
window.location = "delete_user_form.php";
</script>'; }
}
?>
LOGIN (from where i'm getting currently logged in user details)
<?php session_start();
error_reporting();
$server="localhost";
$user="root";
$password="";
$database="camouflage_studio";
$con = mysqli_connect($server,$user,$password,$database);
if (mysqli_connect_errno()){
echo "Connection Error: " . mysqli_connect_error();
}
mysqli_select_db($con,"camouflage_studio");
if(isset($_POST['submit_login']))
{
if(!empty($_POST['username']) && !empty($_POST['password']))
{
$get_user_name = mysqli_real_escape_string($con,$_POST['username']);
$get_password = mysqli_real_escape_string($con,$_POST['password']);
$sql = "SELECT * FROM `users` WHERE username='$get_user_name' and password='$get_password'";
if($result = mysqli_query($con, $sql))
{
if(mysqli_num_rows($result) == 1)
{
$_SESSION['username'] = $get_user_name;
$_SESSION['password'] = $get_password;
header('Location:admin.php');
}
else{
header('Location:login_form.html');
}
}
else{
header('Location:login_form.html');
}
}
else {
header('Location:login_form.html');
}
}
?>
I think your if condition is opposite :
Try this :
if($username != $_SESSION['username']){
// delete user
} else {
// can not delete
}

Log in page error

this is my log in page. I can log in when I put the relevant username and password and can't log in if they do not match. but the thing is I still have the privilege of logging in when I do not enter any username, password and click on the log in button.
this is the index page
<html>
<head>
<title>Login</title>
<link rel="stylesheet" type="text/css" href="login.css">
</head>
<body>
<div class="login-page">
<form method="post" class="form" action="login.php">
<input type="text" id="user" name="user" placeholder="username"/>
<input type="password" id="pass" name="pass" placeholder="password"/>
<button type="submit" name="submit" id="btn">login</button>
</form>
</div>
</body>
</html>
this is login.php
<?php
//get values passe from form in login.php file
$username = $_POST['user'];
$password = $_POST['pass'];
//to prevent sql injection
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
//connect to the server and select database
mysql_connect("localhost","root","");
mysql_select_db('laboursalary');
//query the database for user
$result = mysql_query("SELECT * FROM login WHERE username= '$username' and password='$password'")
or die("Failed to query database" .mysql_error());
$row = mysql_fetch_array($result);
if ($row['username']==$username && $row['password']==$password) {
header("Location: ../projectdetails/index.php");
} elseif ($row['username']=="" && $row['password']==""){
echo "Failed to login";
} else {
echo "Failed to login";
}
?>
<?php
if(isset($_POST['submit']))
{
//get values passe from form in login.php file
$username = mysql_real_escape_string($_POST['user']);
$password = mysql_real_escape_string($_POST['pass']);
//connect to the server and select database
mysql_connect("localhost","root","");
mysql_select_db('laboursalary');
//query the database for user
$result = mysql_query("SELECT * FROM login WHERE username= '$username' and password='$password'");
$row = mysql_num_rows($result);
if($row == 1)
{
header("Location: ../projectdetails/index.php");
} else {
echo "Failed to login";
}
}
?>
Which means you are having a row with username and password empty. Delete those rows in the table and update the below code as well.
if ($username != "" && $password !=""){
//query the database for user
$result = mysql_query("SELECT * FROM login WHERE username= '$username' and password='$password'")
or die("Failed to query database" .mysql_error());
$row = mysql_fetch_array($result);
if ($row['username']==$username && $row['password']==$password) {
header("Location: ../projectdetails/index.php");
} else {
echo "Failed to login";
}
} else
echo "Failed to login";
}
Note: Also change your mysql connection to mysqli or PDO. Because it is deprecated in the latest PHP versions.

only last line of if/else statement is working on php

Only the last line of if/else statement is working.
How do i solve this? the result is
Please enter a user name and password
the following is the php code :
<?php
session_start();
$username =#$_POST['username'];
$password =#$_POST['password'];
if ($username&&$password)
{
$connect = mysql_connect("localhost","root","")or die("Couldn't connect to the database!");
mysql_select_db("login") or die("Couldn't find database!");
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrows = mysql_num_rows($query);
if($numrows!==0)
{
while($row = mysql_fetch_assoc($query))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if($username==$dbusername&&$password==$dbpassword)
{
echo "Your are logged in!";
$_SESSION['username']=$username;
}
else
echo "Your password is incorrect!";
}
else
die("That user doesn't exists!");
}
else
die("Please enter a user name and password");
?>
This is what I've got as my HTML form:
<html>
<form action="loginpage.php" method="post">
Username: <input type="text" name"username">
<p>
Password: <input type="password" name"password">
<p>
<input type="submit">
</form>
</html>
<?php
session_start();
$username = #$_POST['username'];
$password = #$_POST['password'];
if (!empty($_POST['submit'])) {
$connect = mysql_connect("localhost", "root", "")or die("Couldn't connect to the database!");
mysql_select_db("login") or die("Couldn't find database!");
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrows = mysql_num_rows($query);
if ($numrows > 0) {
while ($row = mysql_fetch_assoc($query)) {
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if ($username == $dbusername && $password == $dbpassword) {
echo "Your are logged in!";
$_SESSION['username'] = $username;
} else
echo "Your password is incorrect!";
} else
die("That user doesn't exists!");
}
else {
ECHO "Please enter a username and Password";
}
?>
<form method="post">
<input type="text" name="username">
<input type="text" name="password">
<input type="submit" name="submit" value="submit">
</form>
Try this But my suggestion would also be that you take if(!empty($_POST['submit'])) because when the document loads input fields will definitely be empty so it will go to the else part. where you have added the die code...avoid using die code in else use echo prompt there.

Trying to create login page using PHP and SQL

I've been working on a website login, and so far, I have the database and register page set up, but I'm trying to work on a Login page. I've been trying to retrieve data from the Database's Table. I was successfull at doing so on my register page to make sure there aren't multiple usernames of the same name, so I copied some of the code and pasted it onto this page. The problem: it returns blank. Please help... ._.
`
KHS SiteSpace
<div id="header">
<img src="./IMAGES/khslogo2.png" style="margin-left:4;float:left;" width="100" hieght="100">
<b>KHS<span id="name">SiteSpace</span></a>
<!--img src="./IMAGES/Menu.png" style="float:right;margin-right:6;" height="100" width="90"-->
</div>
<div id="content">
<p id="subTitle">Login</p>
<div style="float:left;height:30%;">
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" id="register"><br>
Username:<br>
<input type="text" name="name"><br><br>
Password:<br>
<input type="password" name="pass">
<br><br>
<input type="submit" value="Confirm">
</form>
</div>
<div style="float:right;width:50%;border-style:none none none solid; border-color:222222;border-width:4;height:30%;">
<p style="margin-left:20;font-size:20;">Output:</p>
<p style="margin-left:20;padding-bottom:15;">
<?php
error_reporting(0);
#ini_set('display_errors', 0);
session_start();
$conn = new mysqli("localhost", "shanedrgn", "getting321", "Users");
if (!$conn) {die("Failure to connect");}
$name = trim($_POST['name']);
$pass = trim($_POST['pass']);
if (empty($name) or empty($pass)) {echo "Empty Fields";} else {
$name = trim($_POST['name']);
$pass = trim($_POST['pass']);
echo "Check: The fields arent empty...";#OUTPUT
echo "Testing Variables...";#OUTPUT
//Error Trapping
$sql = "SELECT Username FROM Users where Username = '$name'";
$Data = mysqli_query($conn, $sql);
if($record=mysqli_fetch_array($Data)) {
$nameTrap = $record['Username'];
}
$sql = "SELECT Address FROM Users where Address = '$address'";
$Data = mysqli_query($conn, $sql);
if($record=mysqli_fetch_array($Data)) {
$ipTrap = $record['Address'];
}
if ($nameTrap == $name) {
echo "Check: Username Exists...";
if ($passTrap == $pass) {
echo "Password is correct!";
$_SESSION['User'] = $name;
$sql = "SELECT * FROM Users where Username = '$name'";
$Data = mysqli_query($conn, $sql);
$record=mysqli_fetch_array($Data);
session_start();
$_SESSION['id'] = $record['id'];
echo "<script>alert('You have successfully logged in!')</script>";
sleep(4);
header("Location: ./index.php"); /* Redirect browser */
exit();
} else { echo "Password Invalid";}
} else {echo "That username doesn't exist!";echo $name.";;";echo $nameTrap;}
}
?>
</p></div>
</div>
</body>
</html>`
EDIT: Added missing code
You are doing this:
echo "<script>alert('You have successfully logged in!')</script>";
sleep(4);
header("Location: ./index.php"); /* Redirect browser */
I understand, what you try, but it can't work. You can't set an Header after sending Body-Content - what you do using echo.
You should use JavaScript for your redirect, after the 4 second timeout. Use setTimeout and window.location.

php sessions are not being saved

I apologize for the wall of text but I've been banging my head against the wall around this problem for awhile so I'm gonna try to provide as much information as possible.
I'm not quite sure if the problem I'm getting has to do with user sessions (I'm new to PHP), but that's what it seems to me.
I ask a user to enter his login information (id and password) to enter the system in ask_login.php:
<div class="login_box">
<h1>Login</h1>
<form method="POST" action="login.php">
<p><input type="text" name="username" placeholder="UserID"></p>
<p><input type="password" name="password" placeholder="Password"></p>
<input type="submit" name="submit" value="Login"></p>
</form>
</div>
If the login details (id and password) are found in the database the user gets logged in to his user portal (login.php) where he can check his details, exams dates, etc..
My problem is whenever I login, if I click for example on the details button to check the user details, it redirects me to my ask_login.php page asking for my login details again saying that I didn't enter any ID/Password details.
I've tried removing the code where it checks if the login forms were submitted blank, and it eventually started working and I was able to click the 'Details' button or any other button, without getting redirected to ask_login.php.
But now when I click on the 'Details' button my "Welcome, username" line doesn't show the username, which makes me think that it has something to do with php sessions. Furthermore, any query that I make won't show the result.
Here's my login.php code:
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if($username && $password) {
$conn_error = 'Could not connect.';
$mysql_db = '------';
if(!mysql_connect('localhost', '------', '') || !mysql_select_db($mysql_db)) {
die($conn_error);
}
$query = mysql_query("SELECT * FROM users WHERE id='$username' AND password='$password'");
$numrows = mysql_num_rows($query);
if($numrows!== 0)
{
while($row = mysql_fetch_assoc($query))
{
$dbusername = $row['id'];
$dbpassword = $row['password'];
}
if($username==$dbusername && $password==$dbpassword) {
//echo "You are logged in!";
#$_SESSION['id'] = $username;
}
else {
echo "<script>alert('Username/Password are incorrect');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
die();
//die("Wrong username/password!");
}
}
else {
echo "<script>alert('User doesn't exist.');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
die();
//die("That user doesn't exist!");
}
}
else if(empty($username) || empty($password)) {
echo "<script>alert('You didn't enter an ID/Password');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
die();
//die("Please enter an ID and password!");
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Logged in | FCUL</title>
<link rel="stylesheet" href="css/stylesheet_loggedin.css" type="text/css"/>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<link rel="shortcut icon" href="img/vitor-20130904-favicon.ico"/>
</head>
<body>
<div id="header">
<br/>
<img src="/img/fcul_cent_logo_001.png" width="510" height="70"/>
</div>
<div id="loggedinas">
<br/>
Welcome,
<?php
$result = mysql_query("SELECT nome FROM users WHERE id='$username'");
while($row = mysql_fetch_assoc($result)) {
echo $row["nome"];
}
?>
( <?php echo $username; ?> )
<br/>
<div id="logout">
<font size="2"><u>[Logout]</u></font></a>
</div>
<hr/>
</div>
<?php
//FETCH USER'S BI
if(isset($_POST['username'] )) {
$ID = $_REQUEST['username'];
$query = "SELECT bi FROM users WHERE id='$ID'";
//if query is successful
if($query_run = mysql_query($query)) {
//if it returns 0 rows
if(mysql_num_rows($query_run)==NULL) {
echo "<script>alert('Unexpected Error 004');</script>";
echo "<script language='javascript'>window.location = 'index.php';</script>";
}
while($query_row = mysql_fetch_assoc($query_run)) {
$bi = $query_row['bi'];
//echo $bi;
}
}
}
?>
<br/>
<center>
<div id="buttons">
<form method="POST" action="login.php">
<input type="submit" name="details" value="details">
</form>
<?php
//**print user's BI if he clicks on 'Details' button**
if($_POST['detalhes']){
echo '<div id="content">' . $bi . '</div>';
}
?>
</div>
</center>
</body>
</html>
you cannot access session on first time you insert it in $_SESSION['id'] = $username variable.
you can only access it on the second run of session_start();
try this.
1. make login.php
2. make welcome.php
try to separate the module where login.php will only process for checking
the login process then if this condition success then
<?
if($username==$dbusername && $password==$dbpassword) {
//echo "You are logged in!";
$_SESSION['id'] = $username;
header("location: welcome.php");
}
?>
in welcome.php
<?
session_start();
// this is for the checking if user is loged in
if (!$_SESSION['id']) {
header("location: ask_login.php");
exit;
}
?>
You are not checking if the user is already logged, so, after receiving your post from ask_login.php, when you click anything in your page $username and $userpassword will be null.
Just wrap all your code after session_start with
if($_SESSION['id'] === false)
{
//Your code
$username = $_POST['username'];
$password = $_POST['password'];
if($username &&...
}
wrap your code with this
if ($_SESSION['id']){
//your login checking here
};
e.g
if ($_SESSION['id']){
if($username && $password) {
$conn_error = 'Could not connect.';
$mysql_db = '------';
if(!mysql_connect('localhost', '------', '') || !mysql_select_db($mysql_db)) {
die($conn_error);
}
$query = mysql_query("SELECT * FROM users WHERE id='$username' AND password='$password'");
$numrows = mysql_num_rows($query);
if($numrows!== 0)
{
while($row = mysql_fetch_assoc($query))
{
$dbusername = $row['id'];
$dbpassword = $row['password'];
}
if($username==$dbusername && $password==$dbpassword) {
//echo "You are logged in!";
#$_SESSION['id'] = $username;
}
else {
echo "<script>alert('Username/Password are incorrect');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
die();
//die("Wrong username/password!");
}
}
else {
echo "<script>alert('User doesn't exist.');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
die();
//die("That user doesn't exist!");
}
}
else if(empty($username) || empty($password)) {
echo "<script>alert('You didn't enter an ID/Password');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
die();
//die("Please enter an ID and password!");
}
}
?>

Categories