Why do i have to click twice? - php

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.

Related

How to properly validate a login request?

I wrote a code for a login page in PHP and MySQL. The code that I wrote is given below.
logintest.php:
<?php
session_start();
require_once('csrf.php');
?>
<?php
//session_start();
require_once('connect.php');
$csrf = new csrf();
// Generate Token Id and Valid
$token_id = $csrf->get_token_id();
$token_value = $csrf->get_token($token_id);
// Generate Random Form Names
$form_names = $csrf->form_names(array('email', 'password'), false);
if(isset($_POST[$form_names['email']], $_POST[$form_names['password']])) {
// Check if token id and token value are valid.
if($csrf->check_valid('post')) {
// Get the Form Variables.
$email = $_POST[$form_names['email']];
$password = $_POST[$form_names['password']];
// Form Function Goes Here
}
// Regenerate a new random value for the form.
$form_names = $csrf->form_names(array('email', 'password'), true);
}
if(isset($_POST) && !empty($_POST)) {
if(!isset($email) || empty($email)) {
$error[] = "email is required";
}
if(empty($email) && empty($password)) {
die("Please Enter your email and Password");
}
if(empty($email)) {
die("Please Enter your E-mail");
}
if(empty($password)) {
die("Please Fill in the password field");
}
if(!isset($password) || empty($password)) {
$error[] = "password is required";
}
if(!isset($error) || empty($error)) {
$sql = "SELECT email, password FROM loginsystem WHERE email = ? AND password = ?";
if($stmt = $connection->prepare("$sql")) {
$bound_params = $stmt->bind_param("ss", $email, $password);
$execute = $stmt->execute();
$storeResult = $stmt->store_result();
$rows = $stmt->num_rows();
} else {
"";
}
if($rows === 1) {
$_SESSION['email'] = $email;
header("location: home.php"); //redirects to home.php if everything's okay.
} else {
echo "Sorry $email, Wrong email & Password combination";
}
$stmt->close();
}
$connection->close();
}
?>
<html>
<head>
<title>Login System Test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
</head>
<body>
<div class="container">
<div class="row">
<form class="" method="post" >
<div class="form-group">
<input type="hidden" name="<?= $token_id; ?>" value="<?= $token_value; ?>" />
<label for="form-element">Email</label>
<input type="text" name="<?= $form_names['email']; ?>" class="form-control" id="email" placeholder="Email">
</div>
<div class="form-group">
<label for="form-element">Password</label>
<input type="password" name="<?= $form_names['password']; ?>" class="form-control" id="password" placeholder="Password">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
</body>
</html>
Now the following is the code for home.php that I wrote:
<?php
session_start();
$email = $_SESSION['email'];
?>
<!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=iso-8859-1" />
<title>Untitled Document</title>
<style type="text/css">
<!--
.style1 {
font-size: 36px;
font-weight: bold;
}
-->
</style>
</head>
<body>
<p><center>hello <?php echo $_SESSION['email'] ?></center></p>
<p align="center">logout</p>
</body>
</html>
Now by principle, we are allowed to enter the home.php file if and only if we provide the correct username and password and it does the same here too. But the problem is that if I go to home.php using this url : http://localhost/path/to/file/home.php , I come across this type of screen:
A Session ID is assigned and the login succeeds even if email or password are not provided through logintest.php. It clearly shows that I am missing out on some checkgates through which I can avoid happening that thing.
So, for avoiding this thing I want to make my code do a redirect to the logintest.php if anyone tries to access the home.php directly without providing proper credentials in the logintest.php file.
How can I achieve this? Early help will greatly be appreciated.
[P.S: I am new to PHP, so I often fall in such type of silly mistakes that ruin a day or two or my entire week.]
create a page called session.php and add this code
<?php
// check if the session is avilable if not go to login
$site = 'url address';// website address
if (!(isset($_SESSION['email']) && $_SESSION['email'] != '')) {
#header ("location: ".$site."login/");
}
// if you don't want any page redirection put this code to your page
session_start();
if (!(isset($_SESSION['email']) && $_SESSION['email'] != '')) {
//echo 'please login'; // heady login page
}else {
//echo 'logged in'; // go to member page
// logged in
// getting the logged in user - session
if($_SESSION['email']){
$welc = $_SESSION['email'].'';
}
//echo 'Welcome user:'.$welc. '<br>';
?>
Then call the page to every page you want to be accessed by the member. you may use require.
then to get the active session.
session_start();
if($_SESSION['email']){
$welc = $_SESSION['email'].'';
}
//echo 'Welcome user:'.$welc. '<br>';
update your login checks with this. i think it will help you
It was done right by setting a session variable and checking its presence in every page. This was easy and it consumed my whole week😡

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/HTML help, not logging in

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.

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 !!!

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