Building a simple login page. If the user types in a password and password confirmation that don't match, I want to reset the registration form and print an message. Currently, the message does not print, but carries on through the script. This is what I've tried, by way of setting a SESSION variable when the error occurs, and showing this variable upon reload:
registration.php:
<?php
session_start();
if (isset($_SESSION['errmsg'])) {
print($_SESSION['errmsg']);
unset($_SESSION['errmsg']);
}
?>
<form name="register" action="register.php" method="post">
<label>Username</label><input type="text" name="username" maxlength="20" />
<label>Password</label><input type="password" name="pass" />
<label>Password Again</label><input type="password" name="pass_confirm" />
<input type="submit" value="Register" />
</form>
register.php:
<?php
function create_salt() {
$string = md5(uniqid(rand(), true));
return substr($string, 0, 3);
}
session_start();
$username = $_POST['username'];
$pass = $_POST['pass'];
$pass_confirm = $_POST['pass_confirm'];
if ($pass != $pass_confirm) {
$_SESSION['errmsg'] = "Passwords do not match.";
header('Location: registration.php');
}
if (strlen($username) > 20) {
header('Location: registration.php');
}
$hash = hash('sha256', $pass);
$salt = create_salt();
$hash = hash('sha256', $salt . $hash);
$conn = mysql_connect('localhost', 'test4', 'test4');
mysql_select_db('test4', $conn);
$username = mysql_real_escape_string($username);
$query = "INSERT INTO users (username, password, salt) VALUES ('$username', '$hash', '$salt');";
mysql_query($query);
mysql_close();
header('Location: index.php');
?>
The important part is the line if ($pass != $pass_confirm) { .... Currently if the passwords do not match this condition is met, but it will carry on through the script rather than reloading via header(Location: registration.php). I am aware that header() cannot be invoked after data has been sent, which is probably causing the problem.
If so, is there a better way to do this in PHP or should I be looking at alternatives?
A die(); or exit; solves the problem.
header('Location: registration.php');
die();
If you need to output some data and then possibly choose to redirect, you can use output buffering. This causes the output you've generated to be placed in a buffer instead of being sent to the user. If you need to redirect, it works because there's no data sent yet. If you don't redirect, you make use of what's in the buffer and output once the script is done.
See this PHP Manual page to lean much more about PHP output buffering:
http://www.php.net/manual/en/intro.outcontrol.php
Also, note that you're calling header() twice if you have the error - the second header call with the 'location' type will overwrite the first and send you to index.php.
Please see #talereader's answer above - the key is to determine that you're in the error state and call the header (which you do) and then terminate the script immediately.
Why not do all your checking and set a flag if something fails. i.e $failed = true; then before you do any actual processing do if (!$failed) { //process }.
Related
<?php
ini_set('display_errors', '1');
require_once 'core/init.php';
if(logged_in() === TRUE) {
header('location: dashboard.php');
}
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
if($username == "") {
echo "Username Field is Required <br />";
}
if($password == "") {
echo "Password Field is Required <br />";
}
if($username && $password) {
if(userExists($username) == TRUE) {
$login = login($username, $password);
if($login) {
$userdata = userdata($username);
$_SESSION['id'] = $userdata['id'];
header('location: dashboard.php');
exit();
} else {
echo "Incorrect username/password combination";
}
} else{
echo "Username does not exists";
}
}
} // /if
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles1.css">
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="scripts.js"></script>
<title>Login</title>
</head>
<body class="container">
<div class = "login-box">
<img src = "image/person1.png" class = "avatar">
<h1 id = "login-header">Login</h1>
<form id=registration_form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
<div>
<label for="username">Username</label>
<input type="text" name="username" id="form_username" autocomplete="off" placeholder="Username" />
<span id="username_error"></span>
</div>
<br />
<div>
<label for="password">Password</label>
<input type="password" name="password" id="form_password" autocomplete="off" placeholder="Password" />
<span id="password_error"></span>
</div>
<br />
<div>
<input type="submit" name="btnLogin" value = "Login">
</div>
Not yet a member? Register
</form>
</body>
</html>
Can somebody help me regarding to my PHP. I'm very new in PHP. My website must have a multi-login user. But I try to do it and I failed. I don't received any error. But the problem is when I press the login button nothing happen. If the user_type is equal to admin I want to link it to adminPanel.php and if user_type is equal to user I want to link it to userPanel.php. Can somebody fix my code below. I really appreciate it.
function login($username, $password) {
global $connect;
$userdata = userdata($username);
if($userdata) {
$makePassword = makePassword($password, $userdata['salt']);
$sql = "SELECT * FROM tbl_user WHERE username = '$username' AND password = '$makePassword'";
$query = $connect->query($sql);
if($query->num_rows == 1) {
$logged_in_user = mysqli_fetch_assoc($query);
if ($logged_in_user['user_type'] == 'admin') {
$_SESSION['user'] = $logged_in_user;
header('location: adminPanel.php');
}else{
$_SESSION['user'] = $logged_in_user;
header('location: userPanel.php');
}
}
}
$connect->close();
// close the database connection
}
Forword
I feel generous tonight...
This may not fix your issue. As I said in the comments, there are many things that can be wrong. Without more information on what is happening, how you do things there is no way to tell.
These are things that are important (things to check)
how you submit the post (the form)
fields could be named wrong, form could be setup wrong etc.
the form action could simply be wrong
the form method could simply be wrong
how you handle that submission
variables could be sent to login() incorrectly, login($password,$username) instead of login($username,$password)
vairables could simply be translated wrong, for example you could have $_POST['user'] insead of $_POST['username']
you could be doing validation checks on input, which may or may not remove data, could be wrong.
how you handle starting the session
you can't use session until you start it
what if any output you have when handling the submission
output before header location will prevent the redirect
header location does not exit the current code scope, stuff after it can run so you should call exit after doing a redirect.
how you connect to the DB
you may have DB error
what if any errors you get, what error reporting do you have
you could have errors your not reporting for any of the above, and many things I didn't mention.
You probably shouldn't roll you own login system until you have a better handle on the security implications ( and other things).
Password/Security
The makePassword function is not included (in your code), but in any case you should use the built in (PHP5.4+) password function. It's much more secure and saves a lot of work:
function makePassword($plaintext){
return password_hash($plaintext, PASSWORD_DEFAULT);
}
This will return a 60 char long hash, but it's recommended to use VARCHAR(255).
It will look something like this in the DB:
//$2y = BCRYPT (default), $10 Cost or iterations (default), that's all I can remember.
$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a
Then for login (MySqli):
//session_start(); //make sure this is called
function login($username, $password, \mysqli $connect) //use type hinting
{
//can fail because of syntax errors, missing privileges
$stmt = $connect->prepare('SELECT * FROM tbl_user WHERE username = ?') OR die($connect->error);
//can fail because of incorrect number of arguments, invalid types
$stmt->bind_param("s", $username) OR die($stmt->error);
//can fail for various reasons
$stmt->execute() OR die($stmt->error);
$result = $stmt->get_result();
if($result->num_rows == 1) {
$user = $result->fetch_assoc($query);
if(password_verify($password, $user['password'])){
$_SESSION['user'] = $user;
header('location: '.$user['user_type'].'Panel.php');
exit;
}else{
//password error
}
}else{
//username error
}
}
Personally I only use PDO these days. It's been several years sense I used MySqli (so forgive me if I got anything wrong here).
For PDO, this is how I connect with it:
$dsn = 'mysql:dbname=database;host=localhost';
$user = 'user';
$pass = 'pass';
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
];
try{
$PDO = new PDO($dsn, $user, $pass, $options);
}catch(PDOException $e){
//only show end user error codes
die("Error[{$e->getCode()}] connection to DB");
}
The options turn on, Exception error reporting and set the default fetch mode to fetch associative array. With those settings the same thing as above can be done like this:
//session_start(); //make sure this is called
function login($username, $password, \PDO $Pdo) //use type hinting
{
try{
$stmt = $Pdo->prepare('SELECT * FROM tbl_user WHERE username = :username');
$stmt->execute([':username' => $username]);
if($stmt->rowCount()){
$user = $stmt->fetch();
if(password_verify($password, $user['password'])){
$_SESSION['user'] = $user;
header('location: '.$user['user_type'].'Panel.php');
exit;
}else{
//password error, return an error, or throw an exception etc.
}
}else{
//username error
}
}catch(PDOException $e){
//only show end user error codes
die("Database Error[{$e->getCode()}]");
}
}
If you notice it takes around 5 calls to MySqi, and PDO takes only 3 calls. Besides that MySqi is dealing with 3 objects (mysqli, mysqli_stmt, mysqli_result), PDO deals with only 2 (PDO, PDOStatment). Error reporting is also much cleaner.
A few other notes.
use password_hash($plaintext, algo) to create hashes
use password_verify($plaintext, $hash) to check passwords (note plaintext)
use prepared statements
Do not lookup by password, it's not a secure way of verifing 2 hashes are the same (casing, encoding etc...)
use session_start() before using $_SESSION
Do not output anything (not even a single space) before using header
call exit; after using header as it doesn't exit the script it's called in, so it can run code beneath it and produce unexpected results
avoid using global it can be hard to debug your code, instead use dependency injection (pass in the DB connection)
use DRY principals (Dont Repeat Yourself)
And there is probably a bunch of stuff I am forgetting.
UPDATE
Based on the code you added, the part that handles the form submission can be done like this:
<?php
error_reporting(E_ALL); //unclear
ini_set('display_errors', '1');
require_once 'core/init.php';
if(true === logged_in()) { //put constant values on the left
header('location: dashboard.php');
}
if('POST' == $_SERVER['REQUEST_METHOD']){ //put constant values on the left
//ternary condition (shorthand if then)
$username = empty($_POST['username']) ? false : $_POST['username'];
$password = empty($_POST['password']) ? false : $_POST['password'];
//PHP7+ null coalescing can be used instead of above
//$username = $_POST['username'] ?? false;
if(!$username) {
echo "Username Field is Required <br />";
}
if(!$password) {
echo "Password Field is Required <br />";
}
if($username && $password) {
login($username, $password);
//don't forget the connection, if you use the functions without
//it as a global, (which I refuse to use). I once spent a week
//tracking down changes to a global variable in some code I was fixing, never again.
// global $connect;
// login($username, $password, $connect);
}
}
You don't need to do redirects after calling login it's already doing them. You don't need to check if the user exists because you are already checking when fetching there saved password. If you need to know that information there you can either throw exceptions (to much to cover) or you can have the login function return them. In the case that the login is successfule the code will exit before the errors can return.
Summery
My best guess, barring any errors (and assuming the session is started) is that this is happening
form submission, to self
call to login()
everything works, call to header('location: adminPanel.php'); (with no exit)
code returns to the form page (because no exit)
call to header('location: dashboard.php'); And exit();
But that is just a guess, because when yo say "when I press the login button nothing happen" that can mean many things.
One of these days I will put a tutorial for something like this on my website, but it will be more comprehensive.
Anyway, hope it helps you.
SO I am trying to learn myself MVC via the help of a book. Im still at a very basic level so please keep that in mind should you be kind enough to answer.
This is part of my application layout:
Now I have a simple login form
<form method="post" action="index.php">
<input type="text" name="action" value="login" style="display: none">
<label for="email">Email</label>
<input type="email" required="required" name="email" id="email" placeholder="Enter Your Email" />
<br />
<label for="password">Password</label>
<input type="password" required="required" name="password" id="password" placeholder="Enter Your Password" />
<button type="submit" name="submit">Login</button>
</form>
Note the first field name="action" value="login" since the redirect is dependent on that specific field.
MODEL
users_db.php
function login($email, $pword)
{
$sql = "SELECT * FROM users WHERE email = :email AND pword = :pword ";
$stmnt = $db->prepare($sql);
$stmnt->bindValue(':email', $email);
$stmnt->bindValue(':pword', $pword);
$stmnt->execute();
if ($stmnt->rowCount() > 0) {
return $stmnt->fetchAll();
} else {
return null;
}
}
Directory - users
index.php servers as controller. The following is a partial extract of the "controller" and is where the problem occurs.
require_once('../config/db.php');
require_once('../model/users_db.php');
if(isset($_POST['action'])) {
$action = $_POST['action'];
if ($action == 'login') {
$email = htmlspecialchars($_POST['email']);
$pword = htmlspecialchars($_POST['password']);
$users = login($email, $pword);
if (is_array($users)) {
foreach ($users as $user) {
session_start();
$_SESSION['firstname'] = $user['firstname'];
$_SESSION['lastname'] = $user['lastname'];
$_SESSION['username'] = $user['username'];
$_SESSION['email'] = $user['email'];
$_SESSION['userType'] = $user['userType'];
$_SESSION['userID'] = $user['userID'];
header('Location:welcome.php');
die();
}
APP FLOW / STEPS
User enters email and password in the form.
Form info gets passed to index.php the "controller" which includes email, pword. and hidden input field value
Inside the index.php file the controller checks whether the hidden input field action value is set to login which it is.
If login is set it calls the login function from the users_db model, which queries db and returns all user info .
Assuming correct email & pword is enterd, index.php redirects user to a welcome page and exit()
The following works perfectly in Chrome but all other browsers redirects to a 404 error index.php not found. This is rather strange for me, would greatly appreciate it if anyone can provide some input as to why the above error occurs?
Try this
error_reporting(E_ALL | E_WARNING | E_NOTICE);
ini_set('display_errors', TRUE);
flush();
header("Location: http://www.website.com/");
echo '<script>window.location.replace("http://www.example.com")</script>';
die('should have redirected by now');
PHP redirects use header codes to tell the browser to redirect. But if your PHP code echo (even a warning) before that header location, some browsers won't redirect.
In the above code it flushes everything and send the header location. It also tell browser to redirect using javascript, so it will work even the php header redirect didn't work.
Hope it helps
There are more than one problems with that code, other than the redirection.
The reason why the header function doesn't work is because the header needs to have an absolute URL, like http://www.example.com/replace.php, besides that, there needs to be a space between the Location: header name and the value, like:
header('Location: http://www.example.com/replace.php').
Note that in order to set a response header using the header function, no previous headers should've been sent, if you have anything as small as a space that is returned before you call the header function, it won't work.
Now, let's talk about the rest of the problems that this code has:
1 - The session_start() function needs to be called at the top of your page, way before you start working with the $_SESSION superglobal.
2 - You're calling die() in a foreach loop, meaning your code will iterate through the array only a single time and then the code will halt. Move the die() call outside of the loop.
3 - Validate the input using the filter_val function (http://php.net/manual/ro/function.filter-input.php) ~ I'm talking mostly about the email, but I think you can apply it to other inputs as well.
4 - Don't store the password in plain text format, use the password hashing API that PHP offers (https://www.sitepoint.com/hashing-passwords-php-5-5-password-hashing-api/)
Possibly another solution:
users_db.php
function login($email, $pword)
{
$sql = "SELECT * FROM users WHERE email = :email AND pword = :pword LIMIT 1";
$stmnt = $db->prepare($sql);
$stmnt->bindValue(':email', $email);
$stmnt->bindValue(':pword', $pword);
$stmnt->execute();
if ($stmnt->rowCount() > 0) {
return $stmnt->fetchAll();
} else {
return null;
}
}
index.php
require_once('../config/db.php');
require_once('../model/users_db.php');
if(isset($_POST['action'])) {
$action = $_POST['action'];
if ($action == 'login') {
$email = htmlspecialchars($_POST['email']);
$pword = htmlspecialchars($_POST['password']);
$user = login($email, $pword);
if ($user != null) {
session_start();
$_SESSION['firstname'] = $user['firstname'];
$_SESSION['lastname'] = $user['lastname'];
$_SESSION['username'] = $user['username'];
$_SESSION['email'] = $user['email'];
$_SESSION['userType'] = $user['userType'];
$_SESSION['userID'] = $user['userID'];
header('Location: welcome.php');
echo '<script>window.location.replace("http://www.example.com")</script>';
die();
}
}
}
At the end die() function in foreach --> remove it and then try.
Please check if your php code did not have error, and
look for white space after :
ex: header('Location: welcome.php');
recently revealed a problem in my login handler. The thing is, that even though the entered password is correct and matches the one in the database, script still sends me to the mistake page.
session_start();
include ("db.php");
if (isset($_POST['login'])) {
$login = $_POST['login'];
$login = stripslashes($login);
$login = htmlspecialchars($login);
$login = trim($login);
if ($login == '') {
unset($login);
}
}
if (isset($_POST['password'])) {
$password=$_POST['password'];
$password = stripslashes($password);
$password = htmlspecialchars($password);
$password = trim($password);
$password = hash("md5",$password);
if ($password =='') {
unset($password);
}
}
if (empty($login) or empty($password))
{
exit (header('location:index.php'));
}
$result = mysql_query("SELECT * FROM users_data WHERE login='$login'");
$row = mysql_fetch_array($result);
if (empty($row['password']))
{
exit (header('location:mistake.php'));
}
else {
if ($row['password']==$password) {
$_SESSION['login']=$row['login'];
$_SESSION['users_id']=$row['users_id'];
header('location:first.php');
}
else {
header('location:mistake.php');
}
}
The HTML form:
<form action="login.php" method="post" class="login">
<label><span>Login:</span>
<input name="login" type="text" size="20" maxlength="100">
</label>
<label><span>Password:</span>
<input name="password" type="password" size="20" maxlength="100">
</label>
<p>
<input type="submit" name="submit" class ="submit" value="Login">
</p>
UPD: Thank you for your answers, finally I've got where the problem was - I just specified not enough length of password values in the database.
First of all why would you store the password in the database without hashing them(e.g. md5).
If you would do that, then there would be no need to process the password and you could just compare the stored md5(password) with the md5 hash of the password posted by the user.
Also w.r.t it is most likely that you are being redirected to the mistake.php page instead of the success.php page because of the encoding.
It would help if you provide us with the password you are using to test the code (assuming you are testing it. ;) ).
Cheers!
EDIT: Please look at better encryption techniques, as suggested by #jayblancard in the comments below.
try to use isset() instead of empty
if (isset($row['password']))
I will just advice you to try to debug your code, mistake DOT php is called in multiple places so use a die("die message") to see which one is being fired.
Since you don't have tests to your code debug output of valid and invalid input and check output.
Once you are satisfied with the inputs and outputs, check if conditions if they are behaving as expected like previously using die condition maybe.
NB: your code is messy look at this to lean basics
Also look at OO programming
Upon entering the "secure" page, I have an if statement asking if the user is logged in, as shown below.
This statement baffles me as the outcome of both statements are the same, but it is the only way for me to end session when refreshing page. So if I change the statement to if (!session == user) {session_destroy} else { continue with session}, refreshing the page will have the session going.
edit The if/else statement in session.php is the one I do not understand. How can I have an if/else statement with two equal outcomes and yet receive two different outcomes in practice. As I enter my login credentials, I enter the session.php. If I refresh, I end up back at index.php. However, my statement claims that if I have session variables, then destroy session. If I do not have session variables, destroy session. What am I overlooking? edit
Secure page session.php below.
<?php
// To connection
require("includes/functions.php");
// Is the user logged in?
if(!isset($_SESSION['user'])) {
//If user not set, destroy session.
session_destroy();
header("Location: index.php");
exit();
} else {
//Here is the funky part, why have if condition with two predicted equal statements, but have two different outcomes.
// If set, destroy session.
session_destroy();
} //Then the anything below should be secure.
?>
My functions.php (the included one) file is actually a connect to db with a session_start(). The login_process.php page looks as follows.
<?php
// Connection
require_once("functions.php");
//Once form has been clicked, the submitted name reappears, but first empty.
$submitted_username = '';
// IS form submitted?
if(!empty($_POST['login']))
{
// Find username
$query = "
SELECT
id,
username,
password,
salt,
email
FROM users
WHERE
username = :username
";
// The parameter values
$query_params = array(
':username' => $_POST['username']
);
try
{
// Execute the query against the database
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
// Login bad first
$login_ok = false;
// Find user
$row = $stmt->fetch();
if($row)
{
// Check password
$check_password = hash('sha256', $_POST['password'] . $row['salt']);
for($round = 0; $round < 65536; $round++)
{
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password'])
{
// If match, login good.
$login_ok = true;
}
}
// If allgood session start.
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
//Issue here?
$_SESSION['user'] = $row;
// Redirect user to secret page.
header("Location: session.php");
exit;
}
else
{
// Tell the user they failed
$login_failed = "<p class='clear floatleft'>Login Failed.</p>";
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
} ?>
The require_once in login_process.php is due to login_form.php being added as an include on every page. Thus always creating a session_start();. See login_form below.
<?php include('login_process.php'); ?>
<form action="" method="post">
<!-- Sign in form -->
<label>Username</label>
<input type="text" name="username" value="<?php echo $submitted_username; ?>">
<label>Password</label>
<input type="password" name="password" value="">
<input class="inline" type="submit" name="login" value="Login">
<input class="inline" type="submit" name="signup" value="Sign Up">
</form>
<?php if(isset($login_failed)) {
echo $login_failed;
}
?>
The form is picked up from a tutorial, please understand that I am not as of yet capable of producing such a login form rendering. I like to think that I understand the blocks of code by the comments I have created.
But I digest, I do not understand how the if/else statement in session.php can have two equal values and render differently. So any help on this particular subject would be greatly appreciated.
This question may be a duplicate, I have read so many questions regarding sessions that I feel blind to finding any help.
Thanks in advance.
Digress
Your code is doing exactly what it is written to do. Just as you think it is.
When a user inputs their credentials and is successful in login_process.php at -
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
//Issue here?
$_SESSION['user'] = $row;
// Redirect user to secret page.
header("Location: session.php");
exit;
}
else
{
The user is redirected to session.php to have their session destroyed. Why? Because the code says that if the user has nothing in $_SESSION['user']
if(!isset($_SESSION['user'])) {
//If user not set, destroy session.
session_destroy();
header("Location: index.php");
exit();
then destroy the session.
OTHERWISE destroy session.
So no matter what the user session is destroyed. Successful or not.
The reason you don't get redirected until a refresh is because after you log in --successfully-- your session is destroyed. Then on refresh(of the same page) you satisfy the check for
if(!isset($_SESSION['user'])) {
//If user not set, destroy session.
session_destroy();
header("Location: index.php");
exit();
because $_SESSION['user'] no longer exists. Thus it redirects you to the homepage.
TL;DR session_destroy() cleared $_SESSION['user'] and a refresh on the same page causes user to clear first check of if statement.
I have completed a login form and it works 100% on my WAMP server. However when I run it on a live server everything works 100%, apart from when I log in it does not redirect my page to the page it should (just displays a blank HTML page). It is however logged in, because if I enter the url of the page it should go, it displays like it should. The path to the file is correct. I hope my problem is clear. Here is the code for my login form:
<?php
include_once "includes/scripts.php";
session_start();
include_once ("includes/connect.php");
if(isset($_SESSION['logged_in'])) {
header('location: admin_cms.php');
exit();
} else {
if(isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
if(empty($username) or empty($password)) {
$error = '<p>NOTE: Fields are blank</p>';
} 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) {
$_SESSION['logged_in'] = true;
header('location: admin_cms.php');
exit();
} else {
$error = "<p>NOTE: The username or password is incorrect</p>";
}
}
}
?>
<div id="login_container">
<br><img src="images/camelhorst_logo_full.png" style="margin-top:38px;">
<h1>LOGIN<img src="images/three_column_grid_line.png" alt="line"></h1>
<form acton = "admin.php" method="post" autocompleate="off">
<label>Username:</label>
<input type="text" name="username" placeholder="Your Username" required autocomplete="off">
<label>Password:</label>
<input type="password" name="password" placeholder="Your Password" required autocomplete="off">
<input type="submit" value="Login" name="submit_login">
</form>
<?php
if(isset($error)) {
echo $error;
}
?>
<p id="copyright_admin"> © CAMELHORSE CREATIVE STUDIO 2013 </p>
</div><!--login_container-->
<?php
}
?>
</body>
</html>
Firstly, the
session_start()
must be at the very top of the page. There can be nothing, no whitespace before it.
Secondly,
if (empty($username) or empty($password)){
needs to be replaced with this
if (empty($username) || empty($password)){
Try that and see if it works
Also, this is a bit off topic and I'm sure that it's not what's causing your problem, but md5() is very outdated. Try using
sha1();
for encryption instead. sha1() is also a bit old, but it's better than md5().
This too, is kind of off topic. But, it seems notable. You have
if(isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = md5($_POST['password']);
if(empty($username) or empty($password)){
$error = '<p>NOTE: Fields are blank</p>';
}
By default, md5 returns a 32 character hex number even if the value of what's being encrypted is empty. So, the condition
empty($password)
is kind of redundant. What's better to have is this:
if(isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$pass_enc = md5($_POST['password']);
if(empty($username) || empty($password)){
$error = '<p>NOTE: Fields are blank</p>';
}
change redirection to this.
echo "<script>window.location='admin_cms.php'<script>";
Most times, when your header() redirection fails, it is because there has been previous output (even a whitespace matters here), so you may need to be sure there has been no previous output on the file or any included files.
<?php include_once "includes/scripts.php"; ?>
include_once ("includes/connect.php");
NB: Any space outside the <?php ?> tags is considered output.
E.g.
<?php ...some php code... '
//space below causes output to be written to html
?>
<?php
...more php code here...
?>
Iqbal Malik is right. you should use
echo "window.location='admin_cms.php'";
for the redirection however if you want to keep the header() thing you must put
ob_start()
on top of the page, right under
session_start()
it will work like a charm.
edit:
About the md5 / sha1 thing, Ijust started using:
hash("sha512", md5($password))
for my password encryption.