I'm making a login system. Everything works, but when i use a email (username) in the login that is not in the database it will go to the URL with filename and then just the form data (email and password). I need to set the header with an error so i can say that login was failed. Does anyone see the problem?
<?php
ob_start();
if (isset($_REQUEST['password'])) {
require 'connect.php';
$password = $_REQUEST['password'];
$mail = $_REQUEST['email'];
if (empty($mail) || empty($password)) {
header('location: ../login.php?error=empty');
exit();
} else {
$sql = "SELECT * FROM account WHERE email = ?;";
$stmt = mysqli_stmt_init($connect);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../login.php?error=sqlError");
exit();
} else {
mysqli_stmt_bind_param($stmt, "s", $mail);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)) {
$passwordCheck = password_verify($password, $row['wachtwoord']);
if ($passwordCheck == false) {
header("Location: ../login.php?error=passwordWrong");
exit();
} elseif ($passwordCheck == true) {
session_start();
$_SESSION['userId'] = $row['account_id'];
$_SESSION['username'] = $row['gebruikersnaam'];
header("Location: ../index.php?login=succes");
exit();
}
} else {
header("Location login.php?error=noUser");
exit();
}
}
}
} else {
header("Location: ../login.php?error=");
exit();
}
Since your login form is working.
Let me ask you:
Is Your form action using get method or post method?.
Remember when you send a form with GET method to backend eg to a php file, all the form parameters are seen in the url okay.
So You can check this below.
1.) Ensure that your form is using Post method eg method="POST"
2). Why are you using $_REQUEST[..]. in php
its better you used $_POST method for http request coming from form inputs
Something like
if(isset($_POST['submit'])){
require 'connect.php';
$password = $_POST['password'];
$mail = $_POST['email'];
OR
if (isset($_POST['password'])) {
require 'connect.php';
$password = $_POST['password'];
$mail = $_POST['email'];
Note: The variables in $_REQUEST are provided to the script via the GET, POST, and COOKIE input mechanisms and
therefore could be modified by the remote user and cannot be trusted. Therefore proper validation and sanitization should be
done on both front and backend.
see php manual warnings
Finally,
If any of this suggestion does not work for you, you can then upload also all your form fields and I will get it working for you. Thank You
Related
I'm so close to completing the login/registration section of my site but I've got some bugs that don't show up in error_log or anything.
About an hour ago, the script worked for the most part. It would validate, insert into/check database, and redirect to index.php (located in user directory along with login and register forms).
Contents of index.php:
/*
If validation script is successful, continue to $destinationUrl, otherwise, go back to try
again. Ultimately, the TRUE statement's output will be the referring page's URL stored as
$_SESSION['Return_Url'] to send users back to where they were, simply as a convenience.
*/
session_start();
if(isset($_SESSION['UserData'])) {
exit(header("location:" . $destinationUrl));
} else {
exit(header("location:" . $loginUrl));
}
That's exactly what I want except one detail: it won't show any user input errors. While trying to fix that, I've managed to screw everything up again and now it still submits data and inserts into the database but doesn't insert $email, and doesn't redirect or anything. On top of that, I don't get any PHP errors so I'm at a loss.
I know the login and registration will work because it did before, but I don't know what I did to cause this issue due to know errors being thrown. I just want the input errors to show up. I'm going to post the original code I copied and edited because what I'm messing with right now is a mess but the validation section is the same.
I did not write these, they were found online after hours of trying script after script. Only this one worked. Therefore, I don't understand exactly what's going on with every part of the script, but I do understand the basic mechanics of what happens, or is supposed to happen as far as validation of input data and adding to/checking data against the database when the form is submitted. The only thing that I have absolutely no idea what and how it works is the output($var) function
Included Scripts
$db= mysqli_connect($dbhost,$dbuser,$dbpwd,$dbase); }
function safe_input($db, $data) {
return htmlspecialchars(mysqli_real_escape_string($db, trim($data)));
}
/*
Currently, I have no idea about JSON or any other languages. Only a decent
portion of PHP, and HTML, of course. Can I just forget this function and use
{return $var;} instead? Because that would make everything so much easier
and I probably wouldn't even be posting these questions... but it's a new
language to me that I couldn't tell you the first thing about.
*/
function output($Return=array()){
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
exit(json_encode($Return));
}
Validation Scripts
(Both scripts are in one file)
<?
require 'config.php';
require 'functions.php';
if(!empty($_POST) && $_POST['Action']=='login_form'){
$Return = array('result'=>array(), 'error'=>'');
$email = safe_input($db, $_POST['Email']);
$password = safe_input($db, $_POST['Password']);
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$Return['error'] = "Please enter a valid email address.";
}elseif($password===''){
$Return['error'] = "Please enter password.";
}
if($Return['error']!=''){
output($Return);
}
$result = mysqli_query($db, "SELECT * FROM tbl WHERE email='$email' AND password='".md5($password)."' LIMIT 1");
if(mysqli_num_rows($result)==1){
$row = mysqli_fetch_assoc($result);
$Return['result'] = $_SESSION['UserData'] = array('id'=>$row['id']);
} else {
$Return['error'] = 'Invalid Login Credential.';
}
output($Return);
}
if(!empty($_POST) && $_POST['Action']=='registration_form'){
$Return = array('result'=>array(), 'error'=>'');
$name = safe_input($db, $_POST['Name']);
$email = safe_input($db, $_POST['Email']);
$password = safe_input($db, $_POST['Password']);
if($name===''){
$Return['error'] = "Please enter Full name.";
}elseif (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$Return['error'] = "Please enter a valid Email address.";
}elseif($password===''){
$Return['error'] = "Please enter Password.";
}
if($Return['error']!=''){
output($Return);
}
$result = mysqli_query($db, "SELECT * FROM tbl WHERE email='$email' LIMIT 1");
if(mysqli_num_rows($result)==1){
$Return['error'] = 'The email you entered already belongs to an account, please login.';
}else{
mysqli_query($db, "INSERT INTO tbl (GUID, email, password, entry_date) values(MD5(UUID()), '$email', '".md5($password)."' ,NOW() )");
$id = mysqli_insert_id($db);
mysqli_query($db, "INSERT INTO `tbl' (id,name) VALUES('$id','$name')");
$Return['result'] = $_SESSION['UserData'] = array('id'=>$id);
}
output($Return);
}
?>
I'm not sure how I would echo the $Return array values. I tried making a function out of it like so:
function inputErr($Return) {
if($Return['error']!=''){
output($Return);
}
}
but that didn't work either. Is there a special way to echo an array value? Without the index name attached
Also, if you have any ideas why the email $var is not being added to db while everything else is, please, do share! With the script not throwing any PHP errors, I have no idea where to start.
I assume this can simply be done with permissions, but I cannot seem to get it to work. I was trying to make the page check the user for a permission using the code below, otherwise it redirects to home. It always redirects though and I do not know why.
<?php
if(!isset($_SESSION))
{
session_start();
}
if ($_SESSION['permission'] == 0) {
header("Location: ./index.php");
exit;
} else {
if (!isset($_SESSION['authemail'])) {
header("Location: ./index.php");
exit;//Redirect to the index
}
Edit: I added a session dump and both the userID and permission are null. What am I missing from here as I cannot figure it out?
<?php
session_start();
include ('../config/config.php');
/* basic field validation */
$email = trim($_POST["email"]);
$password = trim ($_POST["password"]);
/* check if details are empty, redirect if they are */
if (empty($email) or empty($password)) {
$_SESSION["message"] = "You must enter your email and password";
//Redirect to index
header("Location: ../index.php");
exit;
}
/* sanitise the input */
$email = strip_tags($email);
$password = strip_tags($password);
/* SQL user selection query, with error handling for the SQL */
$query = "SELECT * FROM users WHERE email = '$email' AND password = '$password'";
$result = mysqli_query($mysqli,$query) or exit("Error in query: $query. " . mysqli_error());
/* on query success, set sessions for email and userid */
if ($row = mysqli_fetch_assoc($result)) {
$_SESSION["authemail"] = $email;
$_SESSION["userid"] = $id;
$_SESSION["permission"] = $permission;
/* redirect the user to the secured page */
header("Location: ../loggedin.php");
} else {
/* display error if login was not successful and redirect to index */
$_SESSION["message"] = "Could not log in as $email - $query";
header("index.php");
}
?>
Try to set a flag in the database for someone who is an admin. Then on any specific page that only admins can access you should check this user variable.
if(!$user->isAdmin()){
header("Location: ./login.php");
exit;
}
If you do not have a $user object available, simply call a function that can query the database for the necessary variable.
if(!isUserAdmin()){
header("Location: ./login.php");
exit;
}
Also since both cases of yours redirect to index.php, you can combine the statements:
if($_SESSION['permission'] == 0 || !isset($_SESSION['authemail'])){
header("Location: ./index.php");
exit;
}
Make sure you are debugging to make sure the SESSION values are set/get as expected. Your code is redirecting because one of the conditions is true. Debug and find the bug.
So I have index.php has my default page. It works fine on xampp. So I uploaded my whole site to 1&1 (my domain/hosting provider) and when I try to go to my domain I get an empty alert with no message and a completely blank page.
I changed the name of the file to index.html and the webpage loaded just fine. So I know it must be something with the .php extention or my code up top.
I also added a file called .htaccess and it contains only:
DirectoryIndex index.php
Here is my php code at the top of index.php (replaced sensitive infow with *s):
<?php
//Connect to a database
$host_name = "******.db.1and1.com";
$database = "db****";
$user_name = "dbo******";
$password = "***z.0**";
$connect = mysqli_connect($host_name, $user_name, $password, $database);
// echo("nice job");
//Take the values from the html form and assign them to variables
$ID = $_POST['name'];
$userpassword = $_POST['password'];
//If no passsowrd entered then go straight to index.php
echo "<script type='text/javascript'>alert($userpassword);</script>";
if ($userpassword == null) {
header("Location: http://localhost:82/index3.php");
die();
}
//Check to see if the password matches the hashes
if (md5($userpassword) === '******************'
or md5($userpassword) === '***********'
or md5($userpassword) === '****************'
or md5($userpassword) === '**************')
{
//Add the visitor name to our list
mysqli_query($connect, "INSERT INTO `WebsiteVisitors` (`Name`) VALUES ('$ID')") or die("Error in INSERT: ".mysqli_error($connect));
// echo "You have entered the correct password, congrats.";
// Start the session so they can access other pages
session_start();
$_SESSION['loggedIn'] = true;
// Redirect them to rest of site
header("Location: http://localhost:82/home.php");
die();
}
else {
header("Refresh: 0; url=index2.php");
echo "<script type='text/javascript'>alert(\"Wrong Password. Check your invitation card.\");</script>";
}
?>
Since $_POST request comes only after submitting form in your case, you need to only execute the username and password checks if $_POST["name"] and $_POST["password"] exists.
So give an if statement if(isset($_POST['name']) && isset($_POST['password'])) before using and manipulating $_POST variables. Alson session_start() should be given at top of your script.
Below is your complete code including the check
<?php
session_start();
// session start should be at top of your script
error_reporting(E_ERROR); // reports only errors
//Connect to a database
$host_name = "******.db.1and1.com";
$database = "db****";
$user_name = "dbo******";
$password = "***z.0**";
$connect = mysqli_connect($host_name, $user_name, $password, $database);
// $_POST request comes only when form is submitted in your case. So check for $_POST['name'] and $_POST['password']
if(isset($_POST['name']) && isset($_POST['password']))
{
$ID = $_POST['name'];
$userpassword = $_POST['password'];
//If no passsowrd entered then go straight to index.php
if ($userpassword == null)
{
echo "<script type='text/javascript'>alert("Empty Password");</script>";
header("Location: http://localhost:82/index3.php");
die();
}
//Check to see if the password matches the hashes
if (md5($userpassword) === '******************'
or md5($userpassword) === '***********'
or md5($userpassword) === '****************'
or md5($userpassword) === '**************')
{
//Add the visitor name to our list
mysqli_query($connect, "INSERT INTO `WebsiteVisitors` (`Name`) VALUES ('$ID')") or die("Error in INSERT: ".mysqli_error($connect));
$_SESSION['loggedIn'] = true;
// Redirect them to rest of site
header("Location: http://localhost:82/home.php");
die();
}
else
{
echo "<script type='text/javascript'>alert(\"Wrong Password. Check your invitation card.\");</script>";
header("Refresh: 0; url=index2.php");
}
}
?>
I have created the following scenario.
I have the index.php file which shows the mainpage. On this there are two fields - User Id and password enclosed in a form tag. The submit button calls the login.php file.
Login.php validates the user id, password etc
Once validation is successful, I want the login.php page to take me to MyDashboard.php page (passing the User Id and Password along).
I tried Header in PHP but does not work. I also tried to do a Javascript window.location.href and tried to call it on $(document).ready but nothing happens.
Please help.
--- Edit ----
here is the code after modification
<?php
include_once('./library/Common.php');
$_EmailId = trim($_POST['validemailid']);
$_Password = trim($_POST['password1']);
$_Rememberme = trim($_POST['rememberme']);
// Get the username from the Email Id by searching for #
$_UName= substr($_EmailId, 0, strpos($_EmailId, '#'));
$_Password = md5($_Password);
session_start();
$_SESSION['username'] = $_UName;
$query = "select username, firstname, password_hash,userstatus from users where username = ? and emailid = ?";
$dbconn = new mysqli('localhost', 'root', '','myDB');
if($dbconn->connect_errno)
{
print getHTML('ERROR', "Error in connecting to mysql".$dbconn->connect_error);
}
if(!($stmt=$dbconn->prepare($query)))
{
print getHTML('ERROR',"error in preparing sql statement".$dbconn->error);
}
if(!($stmt->bind_param('ss',$_UName,$_EmailId)))
{
print getHTML('ERROR',"error in binding params in sql statement".$stmt->error);
}
if(!$stmt->execute())
{
print getHTML('ERROR',"Execute failed: (" . $stmt->errno . ") " . $stmt->error);
}
$result=$stmt->get_result();
$row = $result->fetch_assoc();
$_dbpwd = $row['password_hash'];
$_userstatus = $row['userstatus'];
$errstatus = false;
if ($row['username'] != $_UName)
{
print getHTML('ERROR',"User does not exist with the given email id: ".$_EmailId);
$errstatus = true;
}
if(($row['password_hash'] != $_Password) && !$errstatus)
{
print getHTML('ERROR',"Password does not match");
$errstatus = true;
}
if(($row['userstatus'] != 'ACTIVE') && !$errstatus)
{
print getHTML('ERROR',"User is inactive. Please check your email for activation");
$errstatus = true;
}
if(!$errstatus)
{
$_SESSION['firstname'] = $row['firstname'];
$chksession = "SELECT sessionid FROM USERSESSIONS WHERE USERNAME = ? AND ENDDATE IS NULL";
if(!($sessionstmt=$dbconn->prepare($chksession)))
{
print "error in preparing sql statement".$dbconn->error;
exit();
}
$sessionstmt->bind_param('s',$_UName);
$sessionstmt->execute();
$sessionresult=$sessionstmt->get_result();
$sessionrow= $sessionresult->fetch_assoc();
$currdate = date('y-m-d H:i:s');
if($sessionrow['sessionid'] == 0)
{
$insertstmt = $dbconn->query("INSERT INTO USERSESSIONS(USERNAME,STARTDATE,ENDDATE) VALUES ('".$_UName."','".$currdate."',null)");
$insertstmt->close();
}
}
$sessionstmt->close();
$stmt->close();
$dbconn->close();
header("Location :MyDashboard.php");
exit;
?>
--- End of Edit -----
Amit
You should use session variables to store variables within a login session. Passing a password along to other pages is not recommended, nor necessary. Read up on Sessions, and take a look at already existing login scripts. Below is a very simple example, redirecting to the next page using the header() function.
<?php
// Validate user credentials and save to session
session_start();
$_SESSION['userId'] = $userId;
// Redirect to next page
header("Location: dashboard.php");
// Make sure that code below does not get executed when we redirect
exit;
?>
If user authenticated,
In PHP:
header('Location:MyDashboard.php');
Try include()
This function allows you to include code from other php scripts.
The header function is the correct way. As long as you don't have any output before calling the header function, it should work.
http://us3.php.net/manual/en/function.header.php
Post your code, and let's see what it is that isn't working!
Header should work in your condition.
Tou can use following code:
header("Location:filename");
exit();
Im trying to understand how to build a user registration with PHP and MySQL.
I have built a form that the user can fill out and the information is then stored in my table.
error_reporting(E_ALL);
include_once ('connection.php');
// Required field names
$required = array('firstname', 'lastname', 'email', 'password', 'accounttype');
// Loop over field names, make sure each one exists and is not empty
$error = false;
foreach($required as $field) {
if (empty($_POST[$field])) {
$error = true;
}
}
if ($error) {
echo "All fields are required.";
} else {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = md5($_POST['password']);
$accounttype = $_POST['accounttype'];
$query = "INSERT INTO users(firstname,lastname,email,password,accounttype) VALUES (:firstname,:lastname,:email,:password,:accounttype)";
$stmt = $dbh->prepare($query);
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':password', $password);
$stmt->bindParam(':accounttype', $accounttype);
$stmt->execute();
if(!$query){
echo 'Whoops, something went wrong!';
} else {
echo $accounttype;
if($accounttype == '1'){
header ('Location: /england/dashboard.php');
exit;
};
if($accounttype == '2'){
header ('Location: /ireland/dashboard.php');
exit;
};
};
};
When the users completes the form they're either reidrected to a different page based on their account type.
On those pages I need to somehow check to see if the user is of accounttype 'X'. So if they land in
header ('Location: /ireland/dashboard.php');
their account type value will be equal to 2, so only people with an account type of 2 can visit the above mentioned.
I've read about session variables, but where do I set these?
session_start(); // this at top of page
if($accounttype == '1'){
$_SESSION['accountType'] = 1; // or $accounttype
header ('Location: /england/dashboard.php');
exit();
};
if($accounttype == '2'){
$_SESSION['accountType'] = 2; // or $accounttype
header ('Location: /ireland/dashboard.php');
exit();
};
In england/dashboard.php
session_start();
if($_SESSION['accountType'] !== 1) header('location: login.php');
In ireland/dashboard.php
session_start();
if($_SESSION['accountType'] !== 2) header('location: login.php');
Start the session where you built form ,
session_start();
$_SESSION['account_type'] = 2;
and in the dashboard.php just get your session variable to check the account type.
if(($_SESSION['account_type'] == 2)) {
header('`dashboard.php');
} else {
// someother page or restrict access
}
simply begin your php script with session_start();
assign session vars with $_SESSION['whatever'] = "something";
You must begin your script with session_start(); on any page you wish to use session variables though.
To destroy a session and all associated vars simply use session_destroy();
One way to do this:
Use a 'Head/Config' file that you require_once() on every page
In this file store info in the session variable like this:
$_SESSION['myCustomValue'] = $accountType;
Then based on what is stored in there you can redirect:
if ($_SESSION['myCustomValue'] = 2):
header ('Location: /ireland/dashboard.php'); // oh yea!
endif;
First at least SHA1 hash the password. Store the result of that and not the actual password in your database. To test for login, you SHA1 hash what they gave you and compare the hashes. You should also salt the password before hashing, but just hashing would be a good start.
Also give your user record an id that can be used as the primary key.
You basically do a start_session() first thing in your script. This will either start a new one or attach to the one they have.
Then after they login/register and you know what their user id is store it in the session with $_SESSION['userid'] = $userid;
To test for login: isset($_SESSION['userid']) will return true.
Edit
Once you alter your table to have the id as an auto incrementing, primary key, your insert above does not need to change, but you get that ID by calling $dbh->lastInsertId()
You need to decide what you want to store in session data. When a person completes the form, passes validation and is saved in the DB, you might want to do this:
if(!$query) {
echo 'Whoops, something went wrong!';
} else {
session_start();
$_SESSION['account_type'] = $accounttype;
// Carry on functionality...
}
And at the beginning of your script, you can prevent existing users accessing the registration form:
session_start();
if(isset($_SESSION['account_type'])) {
header('Location: /ireland/dashboard.php');
}