Can't Log in on Usercake - php

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.

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😡

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

PHP blank page after the login

I'm building a CMS for a website. The problem is that after the login a blank page appears and it stays until I hit refresh. Then it loads to the correct menu page and everything else is working correctly except this little detail. Any tips to solve this? Thanks, my code is below:
<?php
session_start();
include_once('../includes/connection.php');
if(isset($_SESSION['logged_in'])) {
//display index
?>
<html>
<head>
<meta charset="UTF-8">
<title>AdminENG</title>
<link rel ="stylesheet" href="../assets/style.css"/>
</head>
<body>
<div class="container">
CMS - ENG
<ol>
<li>Add Article</li>
<li>Delete Article</li>
<li>Logout</li>
</ol>
</div>
</body>
</html>
<?php
}
else {
//display login
if(isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
if (empty($username) || empty($password)) {
$error = "All fields are required!";
}
else {
$query = $pdo->prepare("SELECT * FROM users WHERE user_name = ? AND user_password = ?");
$query->bindValue(1, $username);
$query->bindValue(2, $password);
$query->execute();
$num = $query->rowCount();
if($num == 1) {
//user entered the correct details
$_SESSION['logged_in'] = true;
header('Location: index.php');
exit();
}
else {
//user entered false details
$error = "Incorrect details!";
}
}
}
?>
<html>
<head>
<title>AdminENG</title>
<meta charset="UTF-8">
<link rel ="stylesheet" href="../assets/style.css"/>
</head>
<body>
<div class="container">
CMS
<br><br>
<?php
if (isset($error)) { ?>
<small style="color:#aa0000"><?php echo $error; ?></small>
<?php } ?>
<br><br>
<form action="index.php" method="post">
<input type ="text" name="username" placeholder="Username"/>
<input type="password" name="password" placeholder="Password"/>
<input type="submit" value="Login"/>
</form>
</div>
</body>
</html>
<?php
}
?>
Your header() redirection is probably not working. Check error log to see what the problem is. There must be absolutely no characters sent to the browser before the header() redirection, else it will fail.
My guess would be that those few spaces before <? in your script (if they are not copy/paste error) could interfere with head() redirection.
Anyway, check your error.log and see what do you have there.
You can't use Header after you execute html to the browser.
Try replace this: header('Location: index.php');
With this:
<script>window.location="index.php";</script>

Why am I getting an error message?

I wrote this "log in" page and last night everything worked fine except the error messages did not display. Today, I went to double check my work and I get this error message: Call to undefined function showForm() in E:\wwwroot\teamc\logIn.php on line 7. I did not change or alter my code from last night to this morning. Can anyone see why the error message is now showing up??
<?php
session_start();
//validate text was entered in UserName text box
if(empty($_POST['txtUserName']))
{
showForm('Please Enter A User Name.');
exit();
}
else
{
$UserName = $_POST['txtUserName'];
}
//validate text was entered in password text box
if(empty($_POST['txtPassword']))
{
showForm('Please Enter A Password.');
exit();
}
else
{
$Password = $_POST['txtPassword'];
}
if($Password != Password($UserName))
{
showForm('User Name And Password Do Not Match!');
exit();
}
function Password($UserName)
{
//database login
$dsn = 'mysql:host=XXX;dbname=XXX';
$username='XXX';
$password='XXX';
//variable for errors
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
//try to run code
try {
//object to open database
$db = new PDO($dsn,$username,$password, $options);
//check username against password
$SQL = $db->prepare("Select USER_PASSWORD FROM user WHERE user_name = :UserName");
$SQL->bindValue(':UserName', $UserName);
$SQL->execute();
$username = $SQL->fetch();
if($username === false)
{
$password = null;
}
else
{
$password = $username['USER_PASSWORD'];
include 'index.php';
}
return $password;
$SQL->closeCursor();
$db = null;
} catch(PDOException $e){
$error_message = $e->getMessage();
echo("<p>Database Error: $error_message</p>");
exit();
}
}
function showForm($formMessage)
{?>
<!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>WisCon Log In</title>
<link rel="stylesheet" href="styles/wiscon-default-styles.css" type="text/css" />
<link rel="stylesheet" href="styles/FormStyle.css" type="text/css" />
<script type="text/javascript" src="js/validateLogInForm.js/validateLogInForm.js"> </script>
</head>
<body id="logPage">
<div id="wrapper">
<?php include('includes/header.php'); ?>
<?php include('includes/topNavigation.php'); ?>
<div id="mainContent">
<div class="formDiv">
<form name="registerForm" id="registerForm" action="" method="post">
<h1 style="color:#FF530D; text-align: center">Log into your account here!</h1>
<fieldset id="security">
<legend>Security</legend>
<label for="txtUserName" class="boxLabel">User Name:</label>
<input type="text" id="txtUserName" name="txtUserName" autofocus="autofocus" required="required" />
<script type="text/javascript">
if(!("autofocus" in document.createElement("input")))
{
setTimeout(function(){
document.getElementById("txtUserName").focus();
}, 10);
}
</script>
<label for="txtPassword" class="boxLabel">Password:</label>
<input type="password" id="txtPassword" name="txtPassword" required="required" />
</fieldset>
<fieldset id="submission">
<div id="buttons">
<input type="submit" id="btnSubmit" name="btnSubmit" value="Submit" onclick="return validateLogInForm()"/>
<input type="reset" id="btnReset" name="btnReset" >
</div><!--end buttons-->
</fieldset>
</p>
</form>
</div><!--end div class=formDiv-->
</div><!--end div id=mainContent-->
<?php include('includes/footer.php'); ?>
</div><!--end div id=wrapper-->
</body>
</html>
<?php
}
?>
Why are you using exit() after calling the function?
Try removing it and see if it works.
Also the reason you are not seeing the error message inside the html code is simply because you are not calling the passed variable $formMessage somewhere inside the html output.
From the manual exit()
Output a message and terminate the current script
So anything after, including where you define the function will not be executed
It is not necessary to use exit() in an if/else as it will not execute the else when the if returns true.
Edit
If the exit() in the if/else's are necessary, move your function showForm($formMessage) above the if, to prevent it from not being executed / available to call.
Edit 2
To make the error message visible try adding something like this -
<?php if($formMessage !="") echo "<h2 style=\"color:#FF0000; text-align: center\">".$formMessage."</h2>"; ?>
between
...
<h1 style="color:#FF530D; text-align: center">Log into your account here!</h1>
<?php if($formMessage !="") echo "<h2 style=\"color:##FF0000; text-align: center\">".$formMessage."</h2>"; ?>
<fieldset id="security">
...

How do I clear the page content after a form is submitted?

I currently have this code in my project:
require_once('mysql.inc.php');
session_start();
if (!isset($_SESSION['username']) && !isset($_SESSION['uid']))
{
login_sequence();
}
else
{
login_check($_SESSION['username'], $_SESSION['uid']);
}
function login_sequence()
{
echo '<p>' . $pretext . '</p><form method="post" action="" /><label for="password">Password: </label><input type="password" name="password" id="password" /><input type="submit" value="Log In" /><input type="hidden" name="submitted" /></form>';
if (isset($_POST['submitted']))
{
$pword = hash('sha256', $_POST['password']);
$query = "SELECT pword FROM users WHERE user = 'guest'";
$result = mysql_query($query);
$return = mysql_fetch_assoc($result);
if ($return['pword'] == $pword)
{
pageout();
}
else
{
echo 'You entered the wrong password, if you are not a member, please leave.';
}
}
}
function login_check($username, $uid)
{
}
function pageout()
{
echo('
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en-US">
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="" />
</head>
<body>
<div id="header">
<p>WOOT</P>
</div>
<div id="">
</div>
<div id="navigation">
</div>
<div id="footer">
</div>
</body>
</html>
');
}
?>
There is a single "Guest" password stored in a database, it accesses the database and checks the password entered by the user against the one stored in the database. I want to have it so after the form is submitted and the information is correct, on the same page the form disappears and the page appears. How do I do it? How do I get rid of the form to make room for the new page?
header(location ...) on success, or a page display conditional on log in settings
simply do
at the end of your form and at the php code do this
if(!isset($_POST['s'])){
?>
your form here
<?php
}
else //form handle
I would make structure look slightly different:
//First
if (!isset($_POST['submitted'])) {
//include your form only
} else {
//Check if user submitted correct password
//If password is correct
if ($return['pword'] == $pword) {
pageout();
//OR write pageout code on different page and call header("Location: Yourpage.php");
} else {
//Include form or inform user about password mismatch
}
}
edit. Also if you use header("Location:") function make sure you're not echoing or including anything that outputs data. This will cause Headers already sent error.

Categories