I'm trying do develop a simple log in form in order to learn php.
I've created the form and a function which send a query to a mysql database to retrieve username and password (stored in md5 encryption) and control it with data inserted by the user.
The problem is that this function (login() )is in a external file called fun_login.php and when I call it from the page login.php it opens the page fun_login.php and it doesn't come back to login.php (I think because there is some problem with the return value)
In login.php I've included the file fun_login.php with
<?php
include "fun_login.php";
?>
login.php
<div class="container">
<div class="row">
<div class="col-sm-2 col-sm-offset-5">
<form action="fun_login.php" role="form" method="post">
<div class="form-group">
<label for="nome">Username:</label>
<input type="textarea" class="form-control" id="username" name="username">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" id="password" name="password">
</div>
<button type="submit" class="btn btn-default" id="submitlogin" name="submitlogin">Log In</button>
</form>
<?php
if(isset($_POST['submitlogin'])) {
$control = login($_POST['username'], md5($_POST['password']));
if($control) header("Location: ./index.php");
else header("Location: ./login.php");
}
?>
</div>
</div>
</div>
fun_login.php
<?php
function login($username, $password) {
$myconn = mysql_connect(localhost, root, password);
mysql_select_db('portfolio', $myconn);
$query = "SELECT username,password,admin FROM utenti WHERE username = '" . $username . "' AND password = '" .$password . "';";
$result = mysql_query($query, $myconn)or die('Error, insert query failed');
// conto il numero di occorrenze trovate nel db
$numrows = mysql_num_rows($result);
// se il database è vuoto lo stampo a video
if ($numrows == 0) return false;
// se invece trovo delle occorrenze...
else return true;
}
?>
At the time you're calling
<?php
if(isset($_POST['submitlogin'])) {
$control = login($_POST['username'], md5($_POST['password']));
if($control) header("Location: ./index.php");
else header("Location: ./login.php");
}
?>
in your login.php the headers have been already sent so header('Location:') won't work.
You need to put that before any output (echo or html) gets displayed.
If you look in the error log you'll probably see Warning: Cannot modify header information - headers already sent by
By the looks of it that file is included in a layout or something so your login() call has to be even before that.
What's the error message you are receiving?
use this command at the beginning of your php files:
// Report all PHP errors
error_reporting(E_ALL);
Then you will know which error has occurred, if at all.
Related
I'm trying to make a simple login with a mySQL database. As of right now, I am able to connect to the database just fine, but for whatever reason I cannot for the life of me manage to figure out why it won't accept the data for the username and password (not worried about hashing right now, this is just practice). Each time I type it in it only gives me the error message, and I am trying to use the user 'test' with a password of '123', so I know I'm not spelling it incorrectly. Aside from my error message, it doesn't say anything else is wrong at all. This is what my login looks like currently:
<?php
//Start PHP session
session_start();
require_once("db_config.php");
function sanitize($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//Check if the form has been submitted
if(strtoupper($_SERVER['REQUEST_METHOD']) === 'POST') {
if (isset($_POST['pass']) && isset($_POST['user'])) {
//Predefine variables
$validationed = false;
$err_msg = "";
//Username and password has been submitted by the user
//Receive and sanitize the submitted information
$user = sanitize($_POST['user']);
$passwd = sanitize($_POST['pass']);
$user = mysqli_real_escape_string($conn, $user);
$sql = "SELECT * FROM user_logins WHERE username = '$user';";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
$row_count=mysqli_num_rows($result);
//If the record is found, check password.
if ($row_count > 0) {
$row = mysqli_fetch_assoc($result);
if (password_verify($passwd, $row['pass'])) {
$validationed = true;
}
}
if ($validationed === false) {
// If the check completes without finding a valid login, set the error message.
$err_msg = "Invalid Login...Please Try Again";
} else {
// redirect to the main page of the website.
header("Location: travel.php");
exit();
}
}
}
else {
session_destroy();
session_unset();
session_start();
}
?>
<body id="LoginForm">
<div class="container">
<div class="login-form">
<div class="main-div">
<div class="panel">
<h1>Login</h1>
<p>Please enter your username and password</p>
</div>
<?php
//If $err_msg is set, display the message
if(isset($err_msg)) {
echo('<div class="alert alert-danger" role="alert">');
echo(' <strong>' . $err_msg . '</strong>');
echo('</div>');
}
?>
<form id="Login" action="login.php" method="post">
<div class="form-group">
<input type="username" class="form-control" name="user" placeholder="Username">
</div>
<div class="form-group">
<input type="password" class="form-control" name="pass" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary" name='submit'>Login</button>
</form>
</div>
</div>
</div>
</body>
I am trying to access 'username' and 'pass' from the table 'user_logins'. There's obviously something I've done incorrectly, but I can't seem to pick it out. It would be a great help if someone could look over this and tell me if they see anything wrong! Thank you!
When using password_verify to compare password and hash, you must make sure that the hash value was created using the accompanying function password_hash. These two functions work hand-in-hand.
So either you compare both values directly or store the password in its hashed form into the DB (using password_hash).
if ($passwd == $row['pass']) {
$validationed = true;
}
I am trying to display a message if wrong username or password upon login, so I created to functions set_message and display message as following:
function set_message(){
if (!empty($msg)) {
$_SESSION['message'] = $msg;
}else
$msg = "";
}
function message_display(){
if (isset($_SESSION['message'])) {
echo $_SESSION['message'];
unset($_SESSION['message']);
}
}
I called set message function here:
function login_user(){
if (isset($_POST['submit'])) {
$username = escape_string( $_POST['username']);
$password = escape_string($_POST['password']);
global $connection;
$query = "SELECT * FROM users WHERE username = '{$username}' AND password = '{$password}' ";
$result = mysqli_query($connection, $query);
confirm($result);
if (mysqli_num_rows($result) == 0) {
set_message("Username or Password Are Wrong!");
message_display();
redirect('login.php');
}else{
set_message("WELCOM ADMIN");
redirect('admin');
}
}
I called display message function in login.php file inside form:
<form class="" action="" method="post" enctype="multipart/form-data">
<?php login_user(); ?>
<h3><?php message_display(); ?></h3>
<div class="form-group"><label for="">
username<input type="text" name="username" class="form-control"></label>
</div>
<div class="form-group"><label for="password">
Password<input type="text" name="password" class="form-control"></label>
</div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-primary" >
</div>
</form>
PROBLEM IS UPON WRONG USER/PASS REDIRECT SUCCESSFULLY EXECUTED BUT WITHOUT MESSAGE DISPLAY
You never call message_display() here:
}else{
set_message("WELCOM ADMIN");
redirect('admin');
)
But you immediately do a redirect (assuming that function is working) so the message would never get displayed unless this is a SPA.
Good day.
So below i have a php script that is supposed to query my db and look for user details. the db is set up and the data is available in it. the issue here seems that once i click the submit button with my user entered details, it fails on the first if statement, to see if the email exists. i am not sure why.
But here is the submit form.
<form action = "submit2.php" method="Post" >
<div class="row form-group">
<div class="col-md-12">
<!-- <label for="email">Email</label> -->
<input type="text" id="email" name="email" class="form-control" placeholder="Your user name">
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<!-- <label for="subject">Subject</label> -->
<input type="text" id="password" name="password" class="form-control" placeholder="Your Password">
</div>
</div>
<div class="form-group">
<input type="submit" value="Login" class="btn btn-primary">
</div></form>
and here is the submit2.php that is supposed to manipulate the data from the form and query the db.
<?php
session_start();
require_once('connect.php');
if(isset($_POST) & !empty($_POST)){
$useremail = mysqli_real_escape_string($connection,$_POST['email']);
$userpassword = mysqli_real_escape_string($connection, $_POST['password']);
if (empty($useremail) || empty($userpassword)){
header("Location: customerportal.php?login=empty");
exit();
}
else{
$sql = "SELECT * FROM 'USERS' where EMAIL ='$useremail';";
$emailresult = mysqli_query($connection, $sql);
$emailresultcheck = mysqli_num_rows($emailresult);
//check if email exists
if($emailresultcheck == 0){
header("Location: customerportal.php?login=invalidEmail");
}
else {
if($row = mysqli_fetch_assoc($emailresult)){
//dehash the password
$hashedPWDCheck = password_verify($userpassword,$row['ENCRYPTEDPWD']);
if($hashedPWDCheck == false){
header("Location: customerportal.php?login=passwordincorrect");
exit();
}
elseif($hashedPWDCheck == true){
$_SESSION['email'] = $email;
// header("Location: Landingpage.php");
echo "Success";
}
}
else{
header("Location: customerportal.php?login=invalid");
exit();
}
}
}
}
?>
The submit always fails else statement and returns the invalidEmail header location and i am not sure why. the Connection file is below.what am i missing?
<?php
$connection = mysqli_connect("localhost", "root", "");
if(!$connection){
echo "Failed to connect database" . die(mysqli_error($connection));;
}
$dbselect = mysqli_select_db($connection, "dhctest");
if(!$dbselect){
echo "Failed to Select database" . die(mysqli_error($connection));
}
?>
Change this
$sql = "SELECT * FROM 'USERS' where EMAIL = '$useremail';";
to this
$sql = "select * from users where email = $useremail";
Okay, so solved the issue, by running a var_dump() on everyone of my variables until i came across the error that was being outputted by my sql code.
On the line
$sql = "SELECT * FROM 'USERS' where EMAIL = '$useremail';";
I had to remove the '' and replace with ``.
And that seems to have solved the issue.
Thank you for everyone who assisted.
I have two pages. Index.php and my Login.php.
I am using dropdown menu form for logging in - when the user presses 'Sign in', the data gets sent to the Login.php. It's all okay when the password/username was correct (they get sent to the dashboard).
But how could I display an error right there, in the form? Currently when the username/password is wrong it sends you to a new blank page. I want the error to appear right there on the form.
My form:
<div class="form-group">
<label class="sr-only" for="username">Username</label>
<input type="text" class="form-control" name="user_name" placeholder="Username" required>
</div>
<div class="form-group">
<label class="sr-only" for="password">Password</label>
<input type="password" class="form-control" name="user_password" placeholder="Password" required>
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Remember me
</label>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success btn-block">Sign in</button>
</div>
My login.php:
error_reporting(E_ALL);
session_start();
$con = mysqli_connect("localhost", "root", "", "battlesql");
if (!$con) {
echo "<div>";
echo "Failed to connect to MySQL: ".mysqli_connect_error();
echo "</div>";
} else {
if (isset($_POST['user_name']) && isset($_POST['user_password'])) {
$username = stripslashes($username);
$username = mysqli_real_escape_string($con, $_POST['user_name']);
$pass = stripslashes($pass);
$pass = mysqli_real_escape_string($con, $_POST['user_password']);
$pass_hashed = hash('whirlpool', $pass);
$select_user = "SELECT * from accounts where name='$username' AND password='$pass_hashed' LIMIT 1";
$query = mysqli_query($con, $select_user);
$row = mysqli_num_rows($query);
if (!$row) {
echo "<div>";
echo "No existing user or wrong password.";
echo "</div>";
} else {
echo "<div>";
echo "You have been logged in.";
echo "</div>";
}
} else {
echo "MySQL error!";
}
}
In your login.php, instead of echoing "No existing user or wrong password", use this:
if(!$row)
{
die(header("location:index.php?loginFailed=true&reason=password"));
}
And in your index.php, you can generate the message as:
<button type="submit" class="btn btn-success btn-block">Sign in</button>
<?php $reasons = array("password" => "Wrong Username or Password", "blank" => "You have left one or more fields blank."); if ($_GET["loginFailed"]) echo $reasons[$_GET["reason"]]; ?>
There are dozens of ways to do this, but I'll provide you with one.
Looking at your PHP code, I'm not exactly sure where your redirect to the "dashboard" is, but say you have some code like this:
<?php
//Fetch stuff from the database
if($fetchedUsername == $username and $fetchedPassword == $password)
{
header("Location:/dashboard");
return;
}
?>
Then, to send them back to the login form, you would just put something in the else statement:
<?php
if(........)
{
//Redirect to dashboard
}
else
{
header("Location:/login");
return;
}
?>
This will send them back to the form. Now you want to show an error, so one way to do this is to set a GET variable, so in the else statement, change the header to:
header("Location:/login/?error=1");
This will let you check for the error code on the login page.
So onto your login page code. You can use isset() and inline-PHP echoes to print out an error directly into the form. Something like this:
<form>
//Form stuff
<?php if(isset($_GET["error"])):?>
<div class="error">Invalid Username or Password</div>
<?php endif; ?>
</form>
That way you can style div.error without worrying about an empty wrapper showing up when $_GET["error"] is not set.
You can also make the code to echo a bit shorter using inline PHP:
<?=(isset($_GET["error"])) ? "Invalid Username or Password" : ""?>
You can achieve what you want using ajax(asynchronous JavaScript and XML). Send login data to login.php from index.php using an ajax call. Read the reply the ajax call returns and show error/success message.
You can use the jquery $.ajax({}); function to implement this model. If you are having trouble in implementing the $.ajax() function then you can read all about it here.
Also, if you haven't already done it, I suggest you to encrypt the password before sending it login.php.
I have a CSS popup which brings up a login form. When I try to log in it just reloads the page and the popup appears again.
Here is the link to open the popup
Sign In
Here is the HTML for my popup login form.
<div class="popup">
<h2 class="modal-header">Sign In</h2>
<div class="modal-body">
<form class="signIn-form">
<div class="errorMessage alert alert-error" id="errorMsg">
<h4>Whoops</h4>
<p>
<?php echo $errorMsg; ?>
</p>
</div>
<fieldset class="l-formMain">
<ul>
<li>
<label class="applyForm-label" for="email">Email</label>
<input class="applyForm-input required" type="email" id="login_email" placeholder="name#example.com" tabindex="1" />
</li>
<li>
<label class="applyForm-label" for="password">Password</label>
<input class="applyForm-input required" type="password" id="login_password" tabindex="2" />
<span class="forgotPassLi">
Forgot your Password?
</span>
</li>
</ul>
</fieldset>
<div class="modal-buttonHolder">
<input type="submit" class="btn btn-large" id="login" value="Sign In" tabindex="3" />
</div>
</form>
</div>
×
</div>
Here is my PHP:
if(isset($_POST['login'])){
$login_email = $_POST['login_email'];
$login_password = $_POST['login_password'];
// error handling conditional checks go here
if ((!$login_email) || (!$login_password)) {
$errorMsg = 'Please fill in both fields';
} else { // Error handling is complete so process the info if no errors
include 'scripts/connect_to_mysql.php'; // Connect to the database
$email = mysql_real_escape_string($login_email); // After we connect, we secure the string before adding to query
$pass = md5($login_password); // Add MD5 Hash to the password variable they supplied after filtering it
// Make the SQL query
$sql = "SELECT * FROM members WHERE email='$email' AND password='$password' AND email_activated='1'";
$result = mysql_query($sql);
if($result){
$login_check = mysql_num_rows($result);
}
// If login check number is greater than 0 (meaning they do exist and are activated)
if($login_check > 0){
while($row = mysql_fetch_array($result)){
$id = $row["ID"];
$_SESSION['ID'] = $id;
// Create the idx session var
$_SESSION['idx'] = base64_encode("xxxxxxxxxxxxxxxxxxx$id");
// Create session var for their username
$email = $row["email"];
$_SESSION['email'] = $email;
$_SESSION['userId'] = $row["ID"];
mysql_query("UPDATE members SET last_log_date=now() WHERE ID='$id' LIMIT 1");
} // close while
// All good they are logged in, send them to homepage then exit script
if (isset($_SESSION["email"]) || count($_SESSION["email"]) > 0) {
header("Location: http://localhost/dashboard.php");
}
} else { // Run this code if login_check is equal to 0 meaning they do not exist
$errorMsg = "Either the email or password (or both) are incorrect. Make sure that you've typed them correctly and try again";
}
}// Close else after error checks
}
?>
Your form is not posting to anywhere. So by default it goes to the current page.
Try adding an action and method attribute to the form:
<form method="post" action="http://url.of.PHP.page/containing/login/code">