PHP/HTML help, not logging in - php

The database is set up correctly but I the error handler when I dont enter a username or password is not working. I always get Invalid username and/or password
The following code doesn't go the the "loginhandler.php" link
Any ideas to why?
No matter the input the code executes`
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<link rel="stylesheet" type="text/css" href="css/login.css">
</head>
<body>
<?php
$okay = FALSE;
$username = ($_POST['username']);
$password = ($_POST['password']);
$onError = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (empty($_POST['username'])) {
$onError = 'Please Enter your Username';
$okay = FALSE;
}
if (empty($_POST['password'])) {
$onError = 'Please Enter your password';
$okay = FALSE;
}
if($okay == FALSE)
{
$dbc = mysql_connect('localhost', 'user', 'pass');
mysql_select_db('db_name', $dbc);
$query = "SELECT * FROM signup WHERE username = '" . $username . "' AND password='" . $password . "'";
if ($result = mysql_query($query, $dbc)) {// Run the query.
while ($row = mysql_fetch_array($result)) {
$okay = true;
}
} else {
}
}
if ($okay) {
// session_start();
$_SESSION['username'] = $username;
header('Loction: loginhandler.php');
exit() ;
} else {
$onError = "Invalid username and/or password";
}
}
?>
<!-- Begin Page Content -->
<div id="container">
<form id='login' action='login.php' method='post' accept-charset='UTF-8'>
<div class="error"><?php echo $onError; ?></div>
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<div id="lower">
<input type="checkbox"><label class="check" for="checkbox">Keep me logged in</label>
<input type="submit" value="Login">
<p>Click here to Signup.</p>;
</div><!--/ lower-->
</form>
</div><!--/ container-->
<!-- End Page Content -->
</body>
</html>`
$onError = "Invalid username and/or password";

First, you are using session. add session_start() at the top of the page.
header('Location: loginhandler.php'); you wrote Location wrong.
if($okay == FALSE) Should be if($okay == TRUE)
And you alweyes getting the invalid message because you have "$onError = "Invalid username and/or password";" at the bottom of the code outside any PHP tags.

Related

Can't Log in on Usercake

Im trying to integrate usercake onto my website. I installed it and registered an account. When i try to login with that account, the browser loads then nothing happens and i cant get into an account.
<?php
/*
UserCake
http://usercake.com
Developed by: Adam Davis
*/
require_once("models/config.php");
//Prevent the user visiting the logged in page if he/she is already logged in
if(isUserLoggedIn()) { header("Location: account.php"); die(); }
?>
<?php
/*
Below is a very simple example of how to process a login request.
Some simple validation (ideally more is needed).
*/
//Forms posted
if(!empty($_POST))
{
$errors = array();
$username = trim($_POST["username"]);
$password = trim($_POST["password"]);
//Perform some validation
//Feel free to edit / change as required
if($username == "")
{
$errors[] = lang("ACCOUNT_SPECIFY_USERNAME");
}
if($password == "")
{
$errors[] = lang("ACCOUNT_SPECIFY_PASSWORD");
}
//End data validation
if(count($errors) == 0)
{
//A security note here, never tell the user which credential was incorrect
if(!usernameExists($username))
{
$errors[] = lang("ACCOUNT_USER_OR_PASS_INVALID");
}
else
{
$userdetails = fetchUserDetails($username);
//See if the user's account is activation
if($userdetails["Active"]==0)
{
$errors[] = lang("ACCOUNT_INACTIVE");
}
else
{
//Hash the password and use the salt from the database to compare the password.
$entered_pass = generateHash($password,$userdetails["Password"]);
if($entered_pass != $userdetails["Password"])
{
//Again, we know the password is at fault here, but lets not give away the combination incase of someone bruteforcing
$errors[] = lang("ACCOUNT_USER_OR_PASS_INVALID");
}
else
{
//Passwords match! we're good to go'
//Construct a new logged in user object
//Transfer some db data to the session object
$loggedInUser = new loggedInUser();
$loggedInUser->email = $userdetails["Email"];
$loggedInUser->user_id = $userdetails["User_ID"];
$loggedInUser->hash_pw = $userdetails["Password"];
$loggedInUser->display_username = $userdetails["Username"];
$loggedInUser->clean_username = $userdetails["Username_Clean"];
//Update last sign in
$loggedInUser->updateLastSignIn();
$_SESSION["userCakeUser"] = $loggedInUser;
//Redirect to user account page
header("Location: account.php");
die();
}
}
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login</title>
<link href="cakestyle.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="wrapper">
<div id="content">
<div id="left-nav">
<?php include("layout_inc/left-nav.php"); ?>
<div class="clear"></div>
</div>
<div id="main">
<h1>Login</h1>
<?php
if(!empty($_POST))
{
?>
<?php
if(count($errors) > 0)
{
?>
<div id="errors">
<?php errorBlock($errors); ?>
</div>
<?php
} }
?>
<div id="regbox">
<form name="newUser" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<p>
<label>Username:</label>
<input type="text" name="username" />
</p>
<p>
<label>Password:</label>
<input type="password" name="password" />
</p>
<p>
<label> </label>
<input type="submit" value="Login" class="submit" />
</p>
</form>
</div>
</div>
<div class="clear"></div>
</div>
</div>
</body>
</html>
Its ok. The problem was with my web host and their php sessions configuration.

PHP Login System Issue, Possible Sessions Issue

Hi i have got a sample php login system script. Unfortunately when i enter correct login credentials, it refreshes and remains on the index.php prompting me to login again. My guess is that the seession may not be storing properly.
Please Find the source code below:
index.php
<?php include "base.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" />
<title>User Management System (Tom Cameron for NetTuts)</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="main">
<?php
if(empty($_SESSION['LoggedIn']) && empty($_SESSION['Username']))
{
?>
<h1>Member Area</h1>
<p>Thanks for logging in! You are <b><?=$_SESSION['Username']?><b> and your email address is <b><?=$_SESSION['EmailAddress']?></b>.</p>
<ul>
<li>Logout.</li>
</ul>
<?php
}
elseif(!empty($_POST['username']) && !empty($_POST['password']))
{
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
$checklogin = mysql_query("SELECT * FROM users WHERE Username = '".$username."' AND Password = '".$password."'");
if(mysql_num_rows($checklogin) == 1)
{
$row = mysql_fetch_array($checklogin);
$email = $row['EmailAddress'];
$_SESSION['Username'] = $username;
$_SESSION['EmailAddress'] = $email;
$_SESSION['LoggedIn'] = 1;
echo "<h1>Success</h1>";
echo "<p>We are now redirecting you to the member area.</p>";
echo "<meta http-equiv='refresh' content='=2;index.php' />";
}
else
{
echo "<h1>Error</h1>";
echo "<p>Sorry, your account could not be found. Please click here to try again.</p>";
}
}
else
{
?>
<h1>Member Login</h1>
<p>Thanks for visiting! Please either login below, or click here to register.</p>
<form method="post" action="index.php" name="loginform" id="loginform">
<fieldset>
<label for="username">Username:</label><input type="text" name="username" id="username" /><br />
<label for="password">Password:</label><input type="password" name="password" id="password" /><br />
<input type="submit" name="login" id="login" value="Login" />
</fieldset>
</form>
<?php
}
?>
</div>
</body>
</html>
register.php
<?php include "base.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">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>User Management System (Tom Cameron for NetTuts)</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="main">
<?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
{
?>
<h1>Register</h1>
<p>Please enter your details below to register.</p>
<form method="post" action="register.php" name="registerform" id="registerform">
<fieldset>
<label for="username">Username:</label><input type="text" name="username" id="username" /><br />
<label for="password">Password:</label><input type="password" name="password" id="password" /><br />
<label for="email">Email Address:</label><input type="text" name="email" id="email" /><br />
<input type="submit" name="register" id="register" value="Register" />
</fieldset>
</form>
<?php
}
?>
</div>
</body>
</html>
base.php
<?php
session_start();
$dbhost = "MY HOST"; // this will ususally be 'localhost', but can sometimes differ
$dbname = "MY DB"; // the name of the database that you are going to use for this project
$dbuser = "MY DB USER"; // the username that you created, or were given, to access your database
$dbpass = "MYPASSWORD"; // the password that you created, or were given, to access your database
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
?>
logout.php
<?php include "base.php"; $_SESSION = array(); session_destroy(); ?>
<meta http-equiv="refresh" content="0;index.php">
Please note that the registration is working correctly. its just that when i log in with the correct username and password its accepts but when refreshing asks me to login again. I would like for it to remain on the members area, until the logout is clicked.
Your if condition (in your index.php file) checks if it's empty; that is wrong.
Try this:
if(isset($_SESSION['LoggedIn']) && isset($_SESSION['Username']))
or
if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username']))
instead of
if(empty($_SESSION['LoggedIn']) && empty($_SESSION['Username']))
It look like your first condition is not correct.
The condition should be, if not empty then you are logged !!!

Creating a very simple 1 username/password login in php

I want to make a single login for just 1 user without storing in a database but I can't seem to get this to work.
My code: login.php
<html>
<head>
<title>Login</title>
</head>
<h3>Add entry</h3>
<p> Add another Article</p>
<form action="trylog.php" method = "post">
<label for="username">Username</label> <input type="username" id="usename" name="username"><br /><br />
<label for="password">Password:</label> <input type="text" id="password" name="password"><br /><br />
<button type = "submit">Login</button>
</form>
</html>
trylog.php
<html>
<title>Login</title>
<body>
<?php
$usr = "admin";
$psw = "password";
$username = '$_POST[username]';
$password = '$_POST[password]';
//$usr == $username && $psw == $password
session_start();
if ($_SESSION['login']==true || ($_POST['username']=="admin" && $_POST['password']=="password")) {
echo "password accepted";
$_SESSION['login']=true;
}else {
echo "incorrect login";
}
?>
<form name="input" action="adminportal.php" method="get">
<input type="submit" value="Home">
</form>
</body>
</html>
Your code could look more like:
<?php
session_start();
$errorMsg = "";
$validUser = $_SESSION["login"] === true;
if(isset($_POST["sub"])) {
$validUser = $_POST["username"] == "admin" && $_POST["password"] == "password";
if(!$validUser) $errorMsg = "Invalid username or password.";
else $_SESSION["login"] = true;
}
if($validUser) {
header("Location: /login-success.php"); die();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>Login</title>
</head>
<body>
<form name="input" action="" method="post">
<label for="username">Username:</label><input type="text" value="<?= $_POST["username"] ?>" id="username" name="username" />
<label for="password">Password:</label><input type="password" value="" id="password" name="password" />
<div class="error"><?= $errorMsg ?></div>
<input type="submit" value="Home" name="sub" />
</form>
</body>
</html>
Now, when the page is redirected based on the header('LOCATION:wherever.php), put session_start() at the top of the page and test to make sure $_SESSION['login'] === true. Remember that == would be true if $_SESSION['login'] == 1 as well.
Of course, this is a bad idea for security reasons, but my example may teach you a different way of using PHP.
Here is a simple php script for login and a page that can only be accessed by logged in users.
login.php
<?php
session_start();
echo isset($_SESSION['login']);
if(isset($_SESSION['login'])) {
header('LOCATION:admin.php'); die();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Login</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h3 class="text-center">Login</h3>
<?php
if(isset($_POST['submit'])){
$username = $_POST['username']; $password = $_POST['password'];
if($username === 'admin' && $password === 'password'){
$_SESSION['login'] = true; header('LOCATION:admin.php'); die();
} {
echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
}
}
?>
<form action="" method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="password" required>
</div>
<button type="submit" name="submit" class="btn btn-default">Login</button>
</form>
</div>
</body>
</html>
admin.php ( only logged in users can access it )
<?php
session_start();
if(!isset($_SESSION['login'])) {
header('LOCATION:login.php'); die();
}
?>
<html>
<head>
<title>Admin Page</title>
</head>
<body>
This is admin page view able only by logged in users.
</body>
</html>
Firstly, you need to put session_start(); before any output to the browser, normally at the top of the page. Have a look at the manual.
Second, this won't affect your results, but these lines aren't being used anywhere and should be removed:
$usr = "admin";
$psw = "password";
$username = '$_POST[username]';
$password = '$_POST[password]';
...and the last two lines there wouldn't work, you need to put the quotes inside the square brackets:
$username = $_POST['username'];
If you put session_start() at the top of your page (i.e. before the <html> tag etc), this should work fine.
Your code could look more like:
<?php
session_start(); $username = $password = $userError = $passError = '';
if(isset($_POST['sub'])){
$username = $_POST['username']; $password = $_POST['password'];
if($username === 'admin' && $password === 'password'){
$_SESSION['login'] = true; header('LOCATION:wherever.php'); die();
}
if($username !== 'admin')$userError = 'Invalid Username';
if($password !== 'password')$passError = 'Invalid Password';
}
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Login</title>
<style type='text.css'>
#import common.css;
</style>
</head>
<body>
<form name='input' action='<?php echo $_SERVER['PHP_SELF'];?>' method='post'>
<label for='username'></label><input type='text' value='<?php echo $username;?>' id='username' name='username' />
<div class='error'><?php echo $userError;?></div>
<label for='password'></label><input type='password' value='<?php echo $password;?>' id='password' name='password' />
<div class='error'><?php echo $passError;?></div>
<input type='submit' value='Home' name='sub' />
</form>
<script type='text/javascript' src='common.js'></script>
</body>
</html>
<?php
session_start();
mysql_connect('localhost','root','');
mysql_select_db('database name goes here');
$error_msg=NULL;
//log out code
if(isset($_REQUEST['logout'])){
unset($_SESSION['user']);
unset($_SESSION['username']);
unset($_SESSION['id']);
unset($_SESSION['role']);
session_destroy();
}
//
if(!empty($_POST['submit'])){
if(empty($_POST['username']))
$error_msg='please enter username';
if(empty($_POST['password']))
$error_msg='please enter password';
if(empty($error_msg)){
$sql="SELECT*FROM users WHERE username='%s' AND password='%s'";
$sql=sprintf($sql,$_POST['username'],md5($_POST['password']));
$records=mysql_query($sql) or die(mysql_error());
if($record_new=mysql_fetch_array($records)){
$_SESSION['user']=$record_new;
$_SESSION['id']=$record_new['id'];
$_SESSION['username']=$record_new['username'];
$_SESSION['role']=$record_new['role'];
header('location:index.php');
$error_msg='welcome';
exit();
}else{
$error_msg='invalid details';
}
}
}
?>
// replace the location with whatever page u want the user to visit when he/she log in

Why do i have to click twice?

I have a login page where i have to : insert user and password (1 time); click the button(the login button) twice to actually login.I use Xamp with PHP 5.3 and HeidiSQL .If i'm already in session, it skips the login window and redirects to content page else the form is submitted(which is what i want it to do).This is my code :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php
session_start();
include("../conect.php");
if(isset($_SESSION['name']))
{
$username = $_SESSION['name'];
$pass = $_SESSION['pass'];
$check = mysql_query("SELECT * FROM users WHERE username = '$username'")or die(mysql_error());
while($info = mysql_fetch_array( $check ))
{
if ($pass != $info[2]){
header('.<?php $_PHP_SELF ?>.');
}
else
{ if($_SESSION['role']==0)
header("Location: content0.php");
if($_SESSION['role']==1)
header("Location: content1.php");
if($_SESSION['role']==2)
header("Location: content2.php");
}
}
}
//if the login form is submitted
if (isset($_POST['login'])) {
$nume=mysql_real_escape_string($_POST['username']);
$parola=md5(mysql_real_escape_string($_POST['pass']));
if((!$_POST['username']) || (!$_POST['pass'])) {
die('You did not fill in a required field.');
}
$check_pass = mysql_query("SELECT * FROM users WHERE username = '$nume'")or die(mysql_error());
$check2 = mysql_num_rows($check_pass);
if ($check2 == 0) {
die("That user does not exist in our database");
}
while($data = mysql_fetch_array( $check_pass )) {
//gives error if the password is wrong
if ($parola != $data[2]) {
die('Incorrect password, please try again.');
}
else {
$result = mysql_query("SELECT * FROM users WHERE username = '$nume'")or die(mysql_error());
while($data=mysql_fetch_row($result)){
$_SESSION['name']=$data[1];
$_SESSION['pass']=$data[2];
$_SESSION['role']=$data[3];
}
}
}
}
mysql_close($con);
?>
<html>
<head>
<title>Login</title>
<link rel="stylesheet" href="/css/butoane.css" type="text/css" />
<link rel="stylesheet" href="/css/admin_tools.css" type="text/css" />
<script>
</script>
</head>
<body id="login_background">
<div id="ambele">
<div class="form_box">
<form action="<?php $_PHP_SELF ?>" method="post">
<label for="username">Username</label><input type="text" id="username" name="username" maxlength="40"/>
<label for="password">Password</label><input type="password" id="password"name="pass" maxlength="20"/>
<input type="submit" name ="login" value="Login" class="button"/>
</form>
</div>
<div id="register">
Not registered yet? Go to Registration
</div>
</div>
</body>
</html>
I think you need to exit your script to do redirection.
<?php
header('Location: content.php');
die();
?>
Also, you put the PHP tag in the wrong position.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php
[...]
?>
[...]
This will cause the Headers already sent error in PHP because you already send something to the client before you do redirection.

Processing forms in PHP on the same page

So this time I decided to go with a web programming language.
I always liked the way PHP worked, so I started learning it. I've started making a login page but I just don't know whats wrong with it. No errors if I use symbols.
I don't even think the form is processed. Is this the correct way to handle a form on the same page?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php
session_start();
include("includes/connect.php");
if (isset($_SESSION['uid'])) {
header('Location:member.php');
}
if (isset($_POST['submit'])) {
$error = array();
//username
if (empty($_POST['username'])) {
$error[] = 'You cant have no username can you';
} else if (ctype_alnum($_POST['username'])) {
$username = $_POST['username'];
} else {
$error[] = 'Username cannot contain symbols';
}
//password
if (empty($_POST['password'])) {
$error[] = 'YOU NEED A PASSWORD';
} else {
$password = sha1(mysql_real_escape_string($_POST['password']));
}
//error
if (empty($error)) {
$result = mysql_query("SELECT * FROM user_info WHERE username='$username' AND password='$password'") or die(mysql_error());
if (mysql_num_rows($result) == 0) {
$error_message='Username or Password wrong';
} else {
$_SESSION['username'] = $username;
$_SESSION['user_id'] = mysql_result($result, 0, 'user_id');
}
} else {
foreach($error as $key => $values) {
$error_message.= "$values";
}
}
}
?>
<html>
<head>
<title>Login :)</title>
</head>
<body>
<div style="background-color:#A0A0A0" align="center">
<form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>">
<h3>Login</h3>
<div>
<label for="username">Username:</label>
<input type="text" name="username" maxlength="10"/>
</div>
<div>
<label for="password">Password:</label>
<input type="password" name="password" maxlength="20"/>
</div>
<div>
<input type="submit" name="submit "value="Login"/>
</div>
</form>
<?php echo $error_message; ?>
</div>
</body
</html>
your body tag isn't closed you forgot >
</body>
and delete the space in the submit button's name :)

Categories