I am using the following html form to get a login:
<!DOCTYPE html>
<!-- This is a html file for logging in to the virtual adviser -->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta charset="UTF-8">
<title> Pet Tracker Login</title>
<link rel="stylesheet" type="text/css" media='screen' href="css/login.screen.css">
</head>
<body>
<!-- The div that displays the login form-->
<div class="login">
<h1><strong>Welcome to the Pet Tracker System</strong></h1>
<form action="validateLogin.php" method="POST">
<fieldset>
<label for="user">Username</label>
<p><input type="text" required id = "user" name = "Username" value=""></p>
<label for="pass">Password</label>
<p><input type="password" required id = "pass" name = "Password" value=""></p>
<!-- <p>Forgot Password?</p> -->
<p><input type="submit" value="Login"></p>
</fieldset>
</form>
<!-- include the logo with green background -->
<img src="images/threeDeePawPrint.png" alt="paw Logo" style="width:194px;height:97px" class = "center">
</div>
</body>
</html>
but apparently this is not posting because I get an undefined index error on the validateLogin.php page:
<?php
// start the session for this page and create the array to hold error messages
session_start();
$errmsg_arr = array();
$errflag = false;
$username = 'root';
$password = '';
$url = 'localhost';
$database = 'pet_tracker';
/* Note that above variables are using single quote for string. When they
get replaced in the connection statement below, single quotes within
single quotes will fail, therefore, the string argument in $conn= statement
must be double quotes
*/
try
{
$conn = new PDO("mysql:host=$url; dbname=$database",$username,$password); //create PDO object (PHP Data Objects = PDO)
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); /*set the attribute that controls the error mode once the database
has been connected to, so that it throws exceptions (PDO switches to
"silent failure" mode after establishing a successful connection) */
$conn->exec('SET NAMES "utf8"'); /* PDO has a method exec that runs SQL scripts. Configure the character
encoding to UTF-8 for special characters like smart quotes */
}
catch (PDOException $e)
{
echo $e;
$output = 'Unable to connect to the database server.'. //the '.' is the concatenation operator for a string
$e->getMessage(); //the '->' is the equivalent of the dot operator in Java
include 'error.html.php';
exit();
}
//get the username and password posted from the login page (index.php)
if(isset($_POST['user'])) echo 'index user has value'.$_POST['user'];
if(isset($_POST['pass'])) echo 'index user has value'.$_POST['pass'];
$user = $_POST['user'];
$pass = $_POST['pass'];
//query the database for the posted data from form
$result = $conn->prepare("SELECT * FROM client WHERE username= :un AND password= :pw");
$result->bindParam(':un', $user);
$result->bindParam(':pw', $pass);
$result->execute();
$rows = $result->fetch(PDO::FETCH_NUM);
if($rows > 0)
{
$result = $conn->prepare("SELECT * FROM client WHERE username = :un"); //PDO can only handle a row of data at a time?? Cannot select first_name from students, etc.??
$result->bindParam(':un',$user);
$result->execute();
$name = $result->fetchColumn(1);
$_SESSION['name'] = $name;
$_SESSION['user'] = $user; //the next page employee.php will need the username to get information from the database
header("location: employee.php");
}
else{
$errmsg_arr[] = 'Username and Password are not found';
$errflag = true;
}
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: index.php");
exit();
}
?>
The errors I get are in the lines where I set the $user and $pass variables. The errors I get are:
Notice: Undefined index: user in C:\xampp\htdocs\PetTracker\validateLogin.php on line 41
Notice: Undefined index: pass in C:\xampp\htdocs\PetTracker\validateLogin.php on line 42
Index of $_POST variable should be exactly same as the name attribute of the HTML Input. Name of your input field is Username while you are trying to access it as $_POST['user'] which is entirely wrong.
Either change the name to user or the $_POST index to Username
Also consider reviewing your code, there are bunch of other mistakes as well. Just for instance, you need to capitalize the first letter of location as Location in the header function. Also consider checking the post-back by writing the following condition on the first line of validateLogin.php page
if($_SERVER['REQUEST_METHOD']=='POST'&&isset($_POST['submit'])){
//Your code
}else{
//redirect to somewhere else...
}
Html create input keys from name attribute.
Solution 1: change HTML
<input type="text" required id="user" name="user" value="">
Or solution 2: change PHP
$user = $_POST['Username'];
$pass = $_POST['Password'];
PHP Notice of Undefined Index means that the array Key does not find in the array. If you wish to view all the elements of array you can use print_r($_POST);
To fix your problem just change $_POST['user'] to $_POST['Username'] and $_POST['pass'] to $_POST['Password'];
Related
I'm trying to create a login page that queries the database to check if the username and password are valid and allowing access to the following pages using sessions. Currently, I'm just using XAMPP to test the login. This is the following code I have in a PHP page.
<?php
include("config.php");
session_start();
// Check for POST method
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = stripslashes($_POST['username']);
$username = mysqli_real_escape_string($con, $username);
$password = stripslashes($_POST['password']);
$password = mysqli_real_escape_string($con, $password);
//Search database for username and password
$stmt = $con->prepare("SELECT * FROM users
WHERE username = ? LIMIT 1"); // Prepared statement
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_object();
if(password_verify($_POST['password'], $user->password)) {
echo("working");
$_SESSION['loggedin'] = true;
$_SESSION['user'] = $user->username;
header("Location: index.php");
} else {
echo("no user");
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Login</title>
</head>
<body>
<form id="loginForm" method="post" action="">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<input type="submit" name="submit" value="Login">
</form>
</body>
</html>
I added an echo statement just to see if it would output "no user" for both user/passwords sets in the database and not in it. They both display "no user" so I don't think I'm searching the database correctly. I'm sort of new to PHP and I used this code.
UPDATE
Thanks to comments, fixed passwords so that they were hashed.
When it still was not working:
Set password datatype in database to VARCHAR(60), recommended VARCHAR(255)
I realized it was because I had password datatype set to VARCHAR(40). Since I was using bycrypt to hash, it is a 60 character string. I set my password to the recommended VARCHAR(255) in case I decided to use PASSWORD_DEFAULT in the future. I failed to realize this is all mentioned in password_hash() documentation when initially creating the database and fields.
Added session_start() to all pages referencing $_SESSION[]
Echoed var_dump() to display the result of password_verify() that returned true when I entered the correct information, however, the page stil kept redirecting me to login. In the PHP I was redirecting to I had this section of code:
<?php
if($_SESSION['loggedin'] == false) {
header("Location: login.php");
} else {
}
?>
I forgot to put session_start(); in the PHP page so it kept redirecting me to the login.
I am new to PHP and can't find answers as to why the following code doesn't work. This should be easy, but I can't figure this out. This code produces no errors, and the SQL statement is correct in the phpAdmin SQL console. I've searched web & StackOverflow, but can't find a good answer. What's wrong?
ALL users (whether in the db or not) get ignored and stuck on login page.
<?php
session_start();
//create function to check login form for admin or other type of user.
//Redirect the admin user to the welcome page.
function login()
{
//strip login and password using in-build htmlspecialchars function
$value1 = htmlspecialchars($_POST['login']);
$value2 = htmlspecialchars($_POST['password']);
//set variables for the db connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";
$loggedin = '';
//Create new connection to db
$conn = new mysqli($servername, $username, $password, $dbname);
//Check connection and handle any error
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
header('Locatin: login.php');
}
else {
//check if super admin user exists in db
$sql = "SELECT count(*) FROM admins WHERE AdminLevel = 1";
$result = mysqli_query($conn,$sql);
//check to see if query returns any rows
if(mysql_num_rows(($result) > 0) {
include 'welcome.php';
}
//check if the password and username match
if(($username === $value1) && ($password === $value2)) {
$_SESSION['loggedin'] = TRUE;
echo "Hello ".$value1.", you are logged in!<br>";
}
//send user error message if login/username and password wrong
else {
echo "Incorrect username or password<br>";
include 'login.php';
}
//close the db connection
$conn->close();
}
?>
Login Form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Admin Login</title>
<script>
//function to check the form
function chkForm()
{
//determine the number of elements in the user login form
var intFormLen = document.forms[0].elements.length;
//loop through the form fields to see that a value has been input
for (var i = 0; i < intFormLen; i++) {
if (document.forms[0].elements[i].value == "") {
//send user an error message if login field empty
document.getElementById(document.forms[0].elements[i].name).innerHTML="Required Field";
document.forms[0].elements[i].focus();
return false;
}
}
//clear the form fields
function clearWarn(fieldName)
{
document.getElementById(fieldName).innerHTML = "";
return true;
}
return;
}
</script>
</head>
<body>
<h2>Admin Login</h2>
<div class="phpEcho">
<div class="formLayout">
<form action="#" method="post" onsubmit="return chkForm();">
<label for="login">Login:</label>
<input type="text"name="login" onchange="return clearWarn('fieldName')">
<div id="login" style="color:red"></div><br>
<label for="password">Password:</label>
<input type="password" name="password" onchange="return clearWarn('fieldName')">
<div id="password" style="color:red"></div><br><br>
<input type="submit" name="cmdSubmit" value="Log in">
</form>
</div>
</div>
</body>
</html>
You set your form action="#" and don't submit it in JavaScript.
As noted by Jason, chkForm() will never return true, which would also prevent the form from submitting.
This script has a lot of issues that should be addressed. I will go over a couple things that may help you:
1) I would suggest using some kind of config / bootstrap file to include in your documents that contains reusable elements and start session. Require/include only once.
/config.php
define("_DS_",DIRECTORY_SEPARATOR);
define("DBUSER",'root');
define("DBPASS",'');
define("DBHOST",'localhost');
define("DBDATABASE",'mydb');
// Start session
session_start();
2) You will want to separate out your functions, importantly your database connection, whether by class or by function. You want to keep tasks separate so it's easy to reuse.
Here is an example (I am going to use PDO because I am more familiar with it but principle is the same):
/functions/connection.php
function connection()
{
// This is just a really basic connection, one could expand on this
return new PDO('mysql:host='.DBHOST.';dbname='.DBDATABASE, DBUSER, DBPASS);
}
/functions/login.php
/*
** #param $username [string] by making this a param, you can manually log in users outside of POST
** #param $password [string] same as username
** #param $conn [resource] You will want to inject your connection into this
** in order to use it. Don't make the connection
** inside. May as well reuse resources already active
** #return [bool] If you return TRUE or FALSE, that will tell your script
** whether the login succeeded or failed for notification
*/
function login($username,$password,$conn)
{
// Don't worry about stripping down the username/pass, just bind
// the username and match the password
// You need to select from your user table (or whatever table
// you are storing your usernames for your site)
$query = $conn->prepare("select * from `users` where `username` = :0");
$query->execute(array(':0'=>$username));
$result = $query->fetch(PDO::FETCH_ASSOC);
if(empty($result))
return false;
// You will want to use password_hash to save passwords
if(!password_verify($password,$result['password']))
return false;
// I use htmlspecialchars here so I don't forget when echoing to page
// but you can do it at the time you echo to browser
$_SESSION['first_name'] = htmlspecialchars($result['first_name']);
//etc....
return true;
}
To use:
/index.php
// Include our soon-to-be-used files
require_once(__DIR__._DS_.'config.php');
require_once(__DIR__._DS_.'functions'. _DS_.'connection.php');
require_once(__DIR__._DS_.'functions'. _DS_.'login.php');
// Set connection
$con = connection();
// See if a post has been made
if(isset($_POST['login'])) {
$loggedin = login($_POST['login'],$_POST['password'],$con);
}
// If the login attempt made
if(isset($loggedin)) {
// If successful
if($loggedin) {
header('Location: welcome.php');
exit;
}
else
// If failed, you can note in a variable an echo in the html section
$error = 'Login failed';
}
For the client-side validation, I would suggest jQuery Validate, it's easy and works very well.
This might be a stupid problem but i'm new to this (this is a homework ^^) and i can't find a solution :)
i have a .php file with an html form plus some php code to execute a query and insert the values from the form in my DB. And it works, but every time the page is loaded the php code is executed and this insert in the DB a "blank" line, because obviously the form was not filled yet. This is the code
<html>
<head>
<meta charset="utf-8">
<meta name="generator" content="AlterVista - Editor HTML"/>
<title></title>
</head>
<body>
<form action="myPage.php" method="post">
ID: <input type="text" name="id" /> <br />
<input type="submit" name="Submit" value="Go" /> <br />
</form>
<?php
$user = "DB";
$password = "";
$host = "";
$database = "my_DB";
$connessione = mysql_connect($host, $user, $password);
#mysql_select_db($database, $connessione) or die( "Unable to select database");
$id = $_REQUEST['id'];
$query = "INSERT INTO myTable (ID) VALUES ('".$id."')";
mysql_close();
?>
</body>
</html>
Is there a way to execute the php code only once the "Go" button on the form is executed?
Try:
if(isset($_POST['Submit'])) {
$user = "DB";
$password = "";
$host = "";
$database = "my_DB";
$connessione = mysql_connect($host, $user, $password);
#mysql_select_db($database, $connessione) or die( "Unable to select database");
$id = $_REQUEST['id'];
$query = "INSERT INTO myTable (ID) VALUES ('".$id."')";
mysql_query($query, $connessione);
mysql_close();
}
PHP will work before the page is rendered. You need to set up a condition to stop the PHP you don't want running until you submit the form.
if(isset($_POST['myform'])) {
// process the form
}else{
// html for form goes here
}
Hope that helps.
Assuming the form points to the script itself, there are numerous options :) Among others:
This first example just checks if a form was posted. If a normal (GET) request is received, it will do nothing, because it will not fall into your if-clause
// your form here
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// your php code
}
And this example checks if a variable with the name 'Submit' has been posted, and if so, if it has the value 'Go' in it. It is a slightly stricter check, but in your current example behaviour is exactly the same (so you can pretty much choose which one you like most ;))
// your form here
if(array_key_exists('Submit', $_POST) && $_POST['Submit'] == 'Go') {
// your php code
}
I am trying to add a new row to a table in my database, there is only two columns in the table and i am using a form to get one of the fields. here is the form i am using
<form action="add_list.php" method="post">
Name: <input type="text" name="listname">
<input type="submit" value="Add List">
</form>
and here is add_list.php
<?php
/* Execute a prepared statement by binding PHP variables */
$username = "mydb";
$password = "mydb";
$member = $_SESSION['SESS_MEMBER_ID'];
$listname = $_POST["listname"];
try {
$dbh = new PDO('mysql:;dbname=mydb', $username, $password);
$sth = $dbh->prepare('INSERT INTO lists VALUES (:member_id, :listname)');
$sth->execute(array(':member_id' => $member, ':listname' => $listname));
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();}
?>
I am currently getting an error on line five
Undefined variable: _SESSION in /home/danu2_cj3/public_html/add_list.php on line 5
how to I identify the session variable?
Here is the part of the login code i have set the session in
if($result) {
if(mysql_num_rows($result) == 1) {
//Login Successful
session_regenerate_id();
$member = mysql_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $member['member_id'];
$_SESSION['SESS_FIRST_NAME'] = $member['firstname'];
$_SESSION['SESS_LAST_NAME'] = $member['lastname'];
session_write_close();
header("location: lists.php");
exit();
}else {
//Login failed
header("location: login-failed.php");
exit();
}
Messages in the form of:
Undefined variable: _SESSION ...
are often caused by the lack of a session_start call at the beginning of the script (before the headers are sent and before any attempt to access a $_SESSION key is done).
I have tried that but it just give me a blank page and does not add it to the table.
Well, that means that you have at least solved the above problem. For the blank page you should search for white screen of death, which is well documented here as one of the most common problems in the PHP environment.
I'm having some trouble with my login feature. I've been searching for hours and I could'nt find any problem. I hope you guys will help me.
I want to get users' login and check if it exists in my DB. Problem is it keeps returning me : "Password was probably incorrect!".
I tried an "echo ($count)", it doesn't return anything. Same thing for "echo($result)".
I'm pretty lost right, I can't understand why this doesn't work...
PS : I'm french so you might see some french words.
Here's my login form :
<?php
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Applications</title>
<!--Chargement des feuilles de style-->
<link rel="stylesheet" type="text/css" href="./css/style.css" />
<link rel="stylesheet" type="text/css" href="./css/styleLogin.css" />
<script src="./js/login/modernizr.custom.63321.js"></script>
</head>
<body>
<div class="container">
<header></header>
<section class="main">
<form class="form-2" id="loginForm" action="./controller/checkLogin.php" method="post">
<h1><span class="log-in">Se connecter</span></h1>
<p class="float">
<label for="loginLabel"><i class="icon-user"></i>Nom d'utilisateur</label>
<input type="text" name="login" id="login">
</p>
<p class="float">
<label for="passwordLabel"><i class="icon-lock"></i>Mot de passe</label>
<input type="password" name="password" class="showpassword" id="password">
</p>
<p class="clearfix">
<input type="submit" name="submit" value="Se connecter">
<input type="button" name="submitVisit" value="Accès utilisateur">
</p>
</form>
</section>
</div>
</body>
And here's my checkLogin.php :
<?php
session_start();
try {
$bdd = new PDO('mysql:host=localhost;dbname=stage','root','');
}
catch (Exception $e){ //en cas d'erreur de connexion, afficher le message
die('Erreur : '.$e->getMessage());
}
if(isset($_POST['submit'])){
// username and password sent from form
$login = $_POST['login'];
$pass = $_POST['password'];
$qry = "SELECT login FROM users WHERE login = 'admin'";
$result = mysql_query($qry);
// Mysql_num_row is counting table row
$count = mysql_num_rows($result);
if($count == 0){
die("Password was probably incorrect!");
}
// If result matched $myusername and $mypassword, table row must be 1 row
elseif($count == 1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
$_SESSION['login'] = $login;
header("location: ./login_success.php");
}
else {
echo "Wrong Username or Password";
}
}
mysql_close($bdd);
?>
I want to log in with this couple : admin/admin.
Thank you in advance.
There are a few problems with your script.
First off, you start by using PDO to connect to the database, then you use mysql_* functions (which are deprecated, stick to PDO !!!). Plus, you are not properly escaping your data, and your code is potentially vulnerable to SQL injection.
Secondly, the query you are using is ... not good.
// this is not checking for either the user input data !!!
$qry = "SELECT login FROM users WHERE login = 'admin'";
Your verification code should be something like this:
$ps = $bdd->prepare("SELECT COUNT(*) FROM users WHERE login = :login AND pass = :password");
$params = array("login" => $_POST['login'], "password" => $_POST['password']);
$ps->execute($params);
$status = (bool) $ps->fetchColumn(0);
if ($status) {
// login successful
} else {
// login failed
}
Read up on PDO and prepared statements (they automatically escape your data, so you don't have to).
Note:
If you don't use prepared statements in future code, remember to always escape input from users and pretty much any other source of information.
1) You are mixing mysql and PDO which is a disaster. Mysql_ interface is deprecated use mysqli or pdo please...
2)
"SELECT login FROM users WHERE login = 'admin'";
finds only users with login admin... So you have to
"SELECT login FROM users WHERE login = '$login'";
3) $_POST variables are not safe. Users can inject malicious code...
For instance If you use mysqli then
$login = mysqli_real_escape_string($_POST['login']);
To sanitize login entry and do the same for password too.
since everybody gave advice on general issues i cut to the chase
change:
$login = $_POST['login'];
$pass = $_POST['password'];
$qry = "SELECT login FROM users WHERE login = 'admin'";
assuming the password ist saved to a database field named "passwort" to:
$login = $_POST['login'];
$pass = $_POST['password'];
$qry = "SELECT login FROM users WHERE login = '".mysql_real_escape_string($login)."' and password= '".mysql_real_escape_string($password)."'";
mysql_real_escape_string keeps you from beeing hacked and the database query now uses the values from the post ...
The problem is, that you are mixing mysql_* functions and PDO.. the code should looks like this:
Note the prepare function which binds parameters to your SQL query - it prevents SQL injections.
session_start();
try {
$pdo = new PDO('mysql:host=localhost;dbname=stage','root','');
}
catch (Exception $e){ //en cas d'erreur de connexion, afficher le message
die('Erreur : '.$e->getMessage());
}
if(isset($_POST['submit'])){
// username and password sent from form
$login = $_POST['login'];
$pass = $_POST['password'];
$sql = "SELECT login FROM users WHERE login = :login AND password = :password";
$params = array( 'login' => $login, 'password' => $pass );
$sqlprep = $pdo->prepare($sql);
if($sqlprep->execute($params)) {
$count = $sqlprep->rowCount();
if($count != 1){
die("Incorrect login!");
} else {
$_SESSION['login'] = $login;
header("location: ./login_success.php");
}
}
}