Loggin page doesnt work - php

I am making a lo-gin page, where you should use a user_name and a password in order to lo-gin. before logging in, you need to register an account with your name.
This is my code for logging in to the page:
<?php
// if already logged in
if(isset($_SESSION['username']) && isset($_SESSION['password'])) {
if(isset($_POST['logout'])) {
session_destroy();
echo 'Logged Out!';
showloginform();
}
else {
print("<p>Dear $_SESSION[username]</p>");
print "<p>only a logged in user can see this</p>";
}
}
//not logged in:
else {
//have login request:
if(isset($_POST['username']) && isset($_POST['password'])) {
include 'opendb.php';
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT Name, password FROM Restaurant_table WHERE Name = '$username' AND password = '$password'";
$result = mysql_query($sql) or die('Query failed. ' . mysql_error());
//found username/password combination:
if (mysql_num_rows($result) == 1) {
$_SESSION['logged'] = true;
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
echo 'logged in';
//exit;
}
else {
echo 'Sorry, wrong user_id or password.';
}
}
//have no login request:
else {
showloginform();
}
}
function showloginform() {
echo "\r\n please enter your login information to proceed with our site <br/><br/>";
echo '<form action="start.html" method="post">';
echo '<div class="input-group">';
echo '<input type="text" placeholder="User ID" name="username" class="input-transparent" id="email" />';
echo '<input type="password" placeholder="password" name="password" class="input-transparent"/>';
echo '</div>';
echo '<button id="login-submit" type="submit" class="login-button">Manager Login</button>';
echo '</form>';
}
function checkpass() {
include 'opendb';
$sql = "select * from Restaurant_table where Name='$_POST[username]' and password='$_POST[password]'";
$result = mysql_query($sql,$conn) or die(mysql_error());
return mysql_num_rows($result);
}
?>
but it seems like it doesnt work, First of all it doesnt give me any error when i log-in with use wrong info it just moves to the next page. It is suppose to give me an error or omething, I am not sure what is going wrong.

You are using action as start.html page for your <form>. Because of that it is redirecting to start.html rather than start.php. Change this
echo '<form action="start.html" method="post">';
to
echo '<form action="start.php" method="post">';
OR quote by Prisoner
echo '<form action="" method="post">';

Yes first you have to post the values in a php page not html page.
echo '<form action="<?php echo $_SERVER[\'PHP_SELF\']?>" method="post">';
Second mistake is
if (mysql_num_rows($result) == 1) {
instead of this it should be.
if (mysql_num_rows($result)> 0) {

Related

Login form using PHP not verifying password_verify successfully, even though values are correct

Thanks in advance for any advice on this one. I'm a bit of a newbie and am having some problems with a login form using password_verify. My code is as follows -
<?php
error_reporting(E_ALL); ini_set('display_errors', true);
require_once('includes/config.inc.php');
$page_title = 'Login';
include('includes/header.php');
if(isset($_POST['submitted'])){
require_once(MYSQL);
if(!empty($_POST['email'])) {
$e = mysqli_real_escape_string($dbc,$_POST['email']);
} else {
$e = FALSE;
echo '<p class="error">You forgot to enter your email address</p>';
}
//Validate the password
if(!empty($_POST['pass'])) {
$p = $_POST['pass'];
} else {
echo '<p class="error">You forgot to enter your password</p>';
}
if ($e && $p) { // If everything is OK
//Query the DB to get hash for confirmation purposes
$hashquery = mysqli_query($dbc,"SELECT password from users WHERE email = '$e'");
while ($row = $hashquery->fetch_assoc()) {
$hash = $row['password'];
}
//Echo details for verification purposes
echo "The email address you entered was: " .$e."<br />"; //to verify
echo "The password you entered was: " . $p."<br />"; //to verify
echo "The password has from the db is" .$hash."<br />"; //to verify
$verify = password_verify($p,$hash);
if ($verify) {
echo "successful"; } else { echo "Unsuccessful";
}
//End verification
//run the login query
$q = "SELECT user_id, user_level, password from users WHERE email = '$e' AND active is NULL";
$r = mysqli_query($dbc,$q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
if ($r) { //A match was made
//register the values and redirect
$row = mysqli_fetch_row($r);
$user_id = $row[0];
$user_level = $row[1];
$password = $row[2];
}
$verify = password_verify($p, $password);
if ($verify) {
$_SESSION['user_id'] = $user_id;
$_SESSION['user_level'] = $user_level;
$url = BASE_URL . 'index.php'; //Define the url
ob_end_clean(); //Delete the buffer
header("Location: $url");
} else {
echo '<p class="error">We could not verify the details you entered.</p>';
}
} else { //If everything wasn't OK
echo '<p class="error">Please try again.</p>';
}
mysqli_close($dbc);
}
?>
<h1>Login</h1>
<p>Your browser must allow cookies in order to log in</p>
<form action="login.php" method="post">
<fieldset>
<p><b>Email Address</b><input type="email" size="20" maxlength="80" name="email"/></p>
<p><b>Password</b><input type="password" size="20" maxlength="80" name="pass"/></p>
<div align="center"><input type="submit" value="Login" name="submit" /></div>
<input type="hidden" name="submitted" value="TRUE" />
</fieldset>
</form>
<?php
include('includes/footer.php');
?>
The site is at http://scottsathome.com/database/login.php
When I enter the username 'justin#scottsathome.com' and the password 'password', as you'll see at the top of the page, the verify_password query returns sucessful.
However in the below query, where I actually want to log in, I constantly get the "We are unable to verify your details" message and not logged in.
Could someone please explain a possible solution to this problem?
Many Thanks,
Justin.

Why wont my login.php redirect me?

I have a login, register page. The register page is working fine, but I have a problem with my login page. When I log in succesfully it is supposed to redirect me to a page called member.php but instead just stays on the same page and goes no where. Here is my code for the login.php page where I think the problem may be occuring:
<?php
if(isset($_POST["submit"])){
if(!empty($_POST['user']) && !empty($_POST['pass'])) {
$user=$_POST['user'];
$pass=$_POST['pass'];
$con=mysql_connect('127.0.0.1:8889','root','root') or die(mysql_error());
mysql_select_db('user_registration') or die("cannot select DB");
$query=mysql_query("SELECT * FROM login WHERE username='".$user."' AND password='".$pass."'");
$numrows=mysql_num_rows($query);
if($numrows!=0)
{
while($row=mysql_fetch_assoc($query))
{
$dbusername=$row['username'];
$dbpassword=$row['password'];
}
if($user == $dbusername && $pass == $dbpassword)
{
session_start();
$_SESSION['sess_user']=$user;
header("Location: member.php");
}
} else {
echo "Invalid username or password!";
}
} else {
echo "All fields are required!";
}
}
?>
<form action="" method="POST">
Username: <input type="text" name="user"><br />
Password: <input type="password" name="pass"><br />
<input type="submit" value="Login" name="submit" />
</form>
I refractored your code a bit. You do some checking that you don't have to. First you fetch MySQL-results based on login-info and then you compare it again. You don't need to do that.
This code should work. If it does not, I am pretty sure you are logging in with wrong creditials or there is something wrong with your database structure.
<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['user']) && !empty($_POST['pass'])) {
$con = mysql_connect('127.0.0.1:8889','root','root') or die(mysql_error());
mysql_select_db('user_registration') or die('Could not select database');
$login = 'SELECT * FROM login WHERE username = \'' . $user . '\' AND password = \'' . $pass . '\' LIMIT 1';
$loginq = mysql_fetch_assoc(mysql_query($login));
if (isset($loginq['username'])) {
session_start();
$_SESSION['sess_user'] = $loginq['username'];
header('Location: member.php');
}
else {
echo 'Invalid username or password!';
}
}
else {
echo 'All fields are required!';
}
}
?>
Try adding the page you are POSTing to in the HTML form, like so:
<form action="login.php" method="post">
Also, look into PDO as this is vulnerable to SQL Injection.

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!");
}
}
?>

staying in same page after submiting form button

I'm trying to stay on the same page after submitting a form button.
Depending on the button the user clicks, I want to display certain information on that same page the button was clicked.
For some reason it keeps redirecting me back to my "ask_login.php" page after I click on the button.
I've read around and some people recommend using AJAX or JQuery but I don't really understand much about it. I'd be appreciated if I could get some help. Thanks.
loggedin.php
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if($username && $password) {
//info is provided
$queryget = mysql_query("SELECT * FROM users WHERE id='$username' AND password='$password'");
$numrows = mysql_num_rows($queryget);
if($numrows != 0) {
//something has been found
$_SESSION['id'] = $username;
} else {
echo "Wrong username/password";
echo "<script>alert('Username/Password are wrong');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
}
}
else {
echo "Wrong username/password";
echo "<script>alert('Username/Password are wrong');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
}
?>
<form method="POST" action="">
<input type="submit" name="details" value="Details">
</form>
<form method="POST" action="">
<input type="submit" name="optionB" value="option B">
</form>
<form method="POST" action="">
<input type="submit" name="optionC" value="option C">
</form>
<form action="#">. no action means 'submit to current url', the pound sign mean 'the current document' and should not navigate. though i'm not sure forms semantically allow this.
I would recommend posting the form data over ajax though. Its not hard to do, Jquery offers the most used ajax function and you basically loop though each input in a form and push the value into a uri-encoded string and post that via an ajax call.
I think this following code is not correct...
if($username && $password)
Try this
if(!empty($username) && !empty($password))
i think it shout be
<?php
if($_POST)
{
$username = $_POST['username'];
$password = $_POST['password'];
if($username && $password) {
//info is provided
$queryget = mysql_query("SELECT * FROM users WHERE id='$username' AND password='$password'");
$numrows = mysql_num_rows($queryget);
if($numrows != 0) {
//something has been found
$_SESSION['id'] = $username;
} else {
echo "Wrong username/password";
echo "<script>alert('Username/Password are wrong');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
}
}
else {
echo "Wrong username/password";
echo "<script>alert('Username/Password are wrong');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
}
}
?>
<form method="POST" action="">
<input type="submit" name="details" value="Details">
</form>
<form method="POST" action="">
<input type="submit" name="optionB" value="option B">
</form>
<form method="POST" action="">
<input type="submit" name="optionC" value="option C">
</form>
you can use jquery to process the form
$.post( "test.php", $( "#testform" ).serialize(),function(e){alert(e);} );
test.php
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if($username && $password) {
//info is provided
$queryget = mysql_query("SELECT * FROM users WHERE id='$username' AND password='$password'");
$numrows = mysql_num_rows($queryget);
if($numrows != 0) {
//something has been found
$_SESSION['id'] = $username;
} else {
echo "Wrong username/password";
echo "<script>alert('Username/Password are wrong');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
}
}
else {
echo "Wrong username/password";
echo "<script>alert('Username/Password are wrong');</script>";
echo "<script language='javascript'>window.location = 'ask_login.php';</script>";
}
?>
http://api.jquery.com/jquery.post/
beware, no input validation!
read this page
http://www.php.net/manual/en/function.mysql-real-escape-string.php

Login form not submitting properly in PHP

I'm new to PHP and I have a login page with a form. I want to authenticate the user and then redirect the user to another page with the season values. When I submit the page is not redirecting and if a pres F5 the page will popup the resubmission message of the form. This is my code.
<?php
session_start();
include('../includes/header.php');
$title="Login";
?>
<?php
include('../includes/authenticate.php');
include('../includes/dbschema.php');
//if the user has not logged in
if(!isLoggedIn())
{
if($_SERVER['REQUEST_METHOD']== 'POST'){
//include('../includes/authenticate.php');
$username = $_POST['username'];
$password = $_POST['password'];
//sanitize username
$username = mysql_real_escape_string($username);
if(isset($_POST['username']) && isset($_POST['password'])){
$query = "SELECT password, salt FROM user WHERE username = '$username';";
$result = mysql_query($query);
if(mysql_num_rows($result) < 1) //no such user exists
{
header('login.php');
$errmessage = "Invalid user";
print "<p id\"errmessage\"> $errmessage </p>";
}
$userData = mysql_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );
if($hash != $userData['password']) //incorrect password
{
header('login.php');
}
else
{
validateUser(); //sets the session data for this user
}
//redirect to another page or display "login success" message
header('Location: actividades.php');
}
}
else
{
$status = "logout";
print "<p id=\"usernamelink\">Bienvenido,<a id=\"usernamecolor\"> " . $_SESSION['username'] . " </a></p>";
print "<a id=\"logoutlink\" href=\"../includes/logout.php \">Log out</a>";
//page content follows
}
?>
</br>
<div id="logindiv">
<?php print "<h1 id=\"logintitle\">Login</h1>";?>
<form id="loginform" name="login" action="login.php" method="post" >
Username: <input id="inplogin" type="text" name="username" />
<br/><br/>
Password: <input id="inplogin" type="password" name="password" />
<br/>
<input id="btnlogin" type="submit" value="Login" />
</form>
</div>
<?php include('../includes/footer.php') ; ?>
You should exit; after redirecting. And pass the error to your login script, for example:
if(login_fails()){
header('Location: login.php?errorCode=1');
exit;
}
In your login.php script, check if $_GET['errorCode'] is present and display an error message:
$errors = array(
1 => 'Incorrect password',
);
if(isset($_GET['errorCode'])){
$code = $_GET['errorCode'];
print isset($errors[$code]) ? $errors[$code] : 'Unknown error';
}

Categories