Everytime I submit my form my PHP file does not post - php

I am new to PHP, but I am working on a login system for this website. I am currently working on the account creation page and I can not get the .php file to post to my database. Can anyone out there give me a hand? My code is below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>EDAViewer Login Console</title>
<link rel="stylesheet" href="/CSS/styles.css">
</head>
<body>
<div class="container">
<div class="main-wrapper">
<div class="header">
<header>
<img src="/Assets/BGLogo.png" alt="EDAViewer Logo">
<img src="/Assets/accountCreation.png" alt="Create Account" class="console-img">
</header>
</div>
<div class="login-container">
<fieldset class="login-form">
<form class="form" action="newAccount.php" method="POST">
<ul>
<li>
<label for="username">Username</label>
<input type="text" name="username" required>
</li>
<li>
<label for="password">Password</label>
<input type="text" name="password" required>
</li>
<li>
<label for="verify-password">Verify Password</label>
<input type="text" name="verify-password" required>
</li>
<li>
<input type="submit" value="Create Account">
</li>
</ul>
</form>
</fieldset>
</div>
</div>
</div>
<div class="footer">
<footer>
<p>Copyright &copy 2018 EDA Technologies, Ltd</p>
</footer>
</div>
</body>
</html>
here is the PHP:
<?PHP
$dbConn = mysqli_connect("ServerName(Changed it to post here) ", "UserName",
"Password", DBname);
if (mysqli_connect_errno()){
printf("Connection failed: %s\n", mysqli_connect_error());
exit();
}else{
printf("Host information: %s\n", mysqli_get_host_info($mysqli));
mysqli_close($dbConn);
}
$username = mysqli_real_escape_string($dbConn, $_POST['username']);
$password = $_POST['password'];
$vpass = $_POST['verify-password'];
if($password !=== $vpass){
echo "Your passwords did not match."
}else{
$userSQL = "INSERT INTO user_list (username)
VALUES ('".$username"')";
$passSQL = "INSERT INTO user_list (password)
VALUES ('".$password."')";
$res = mysqli_query($dbConn, $userSQL, $passSQL);
if ($res === TRUE){
echo "Account Created";
}else{
printf("There was an error creating this account: %s\n", mysqli_error($dbConn));
}
mysqli_close($dbConn);
}
?>
The problem I am running into is everytime I press the submit button, I get the CANNOT POST newAccount.php error. What am I doing wrong? I have been trying to get this to work on my own for the last 2 days. I even included the database connection code to this file to see if I referenced it wrong in the beginning.

I am not sure if this is the problem causing it not to work in your script, but it seems like that a ; is missing here
if($password !=== $vpass){
echo "Your passwords did not match."; //<---
}else{
$userSQL = "INSERT INTO user_list (username)
VALUES ('".$username"')";
$passSQL = "INSERT INTO user_list (password)
VALUES ('".$password."')";
Also,you should not do <input type=text ... for your password. Instead, you should use <input type=password>
EDIT: just found out another mistake that may cause your script not to work...
According to http://php.net/manual/zh/language.operators.comparison.php, there're only !== and != in php,
you should do if($password !== $vpass) or if($password != $vpass) instead of if($password != $vpass)
note: (sth!==sth mean !(sth===sth) and sth!=sth mean !(sth==sth))
EDIT 2: as stated by Robin Zigmond, you shouldn't save the password with plain text in your database... you could use
$passSQL = "INSERT INTO user_list (password)
VALUES ('".password_hash($password)."')";
instad to make it safer. When you are logging in, you can use
if(password_verify($_POST['password'], $encrypted_password)){
//correct password
}else{
//incorrect password
}
to verify the password.
More information can be found on http://php.net/manual/en/function.password-hash.php & http://php.net/manual/en/function.password-verify.php

Just use
if($password != $vpass){
echo "Your passwords did not match.";
}else{
$userSQL = "INSERT INTO user_list (username)
VALUES ('".$username"')";
$passSQL = "INSERT INTO user_list (password)
VALUES ('".$password."')";
}

I think you have an issue with the directory.
You can refer here
Also, you are sending multiple queries using mysqli_query() instead of this use mysqli_multi_query() you can find more here
I hope this will solve your issue.

Related

How to echo an error in my page so that I can style it?

In my php script, I have a simple username/ email exists condition, but I want to put the error (should it exist) somewhere in my html, so that I can style it and position it over my form. Echo just puts it top-left. How can I do that? Setting a variable seems like not the optimal solution.
<?php
require('connect.php');
if(isset($_POST["register"])){
$username = $_POST["username"];
$password = $_POST["password"];
$email = $_POST["email"];
$username = mysqli_real_escape_string($conn, $username);
$password = mysqli_real_escape_string($conn, $password);
$email = mysqli_real_escape_string($conn, $email);
$conflictUserQuery = "SELECT username FROM members WHERE username='$username'";
$conflictUserResult = mysqli_query($conn, $conflictUserQuery);
$conflictUserRow = mysqli_fetch_array($conflictUserResult, MYSQLI_ASSOC);
$conflictMailQuery = "SELECT email FROM members WHERE email='$email'";
$conflictMailResult = mysqli_query($conn, $conflictMailQuery);
$conflictMailRow = mysqli_fetch_array($conflictMailResult, MYSQLI_ASSOC);
if(mysqli_num_rows($conflictMailResult) ==1){
echo "Could not be registered. Mail exists.";
}
elseif(mysqli_num_rows($conflictUserResult) ==1){
echo "Could not be registered. Username exists.";
}
else{
$registerQuery = mysqli_query($conn, "INSERT INTO members (username, password, email) VALUES ('$username', '$password', '$email')");
if($registerQuery){
echo "Thank You! you are now registered.";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/style.css">
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<title>Blog</title>
</head>
<body>
<div class="flex-enable flex-center">
<div class="flex-enable flex-center semiOverride flex-center px100">
<div class="flex-enable flex-center flex-column">
<h2 class="big-white-title">Register.</h2>
<h3 class="medium-white-title">Be a part of this.</h3>
<form class="flex-enable flex-center flex-column" method="POST">
<input class="form-input-text small-white-title" type="text" name="username" placeholder="Username">
<input class="form-input-text small-white-title" type="text" name="password" placeholder="Password">
<input class="form-input-text small-white-title" type="text" name="email" placeholder="e-mail">
<input class="form-button small-white-title" type="submit" name="register" value="Register">
</form>
<h3 class="small-white-subtitle">Or <a id="register" href="">login</a> if you have an account.</h3>
</div>
</div>
</div>
<div id="attribution">Photo by Sebastian Kanczok</div>
</body>
</html>
As I stated in comments:
This could be is as simple as assigning a variable to it then, while using an inline CSS styling method:
$error = "<span style=\"color:red;\">Error message here.</span>";
You could also use a stylesheet with an .error class (that can be used for multiple instances as opposed to an #id) and apply it to an error element and simply place the $error variable where you would like it to appear and with an isset().
Note: The use of isset() is important since it will avoid a possible undefined variable notice.
You could also use a ternary operator:
http://php.net/manual/en/language.operators.comparison.php
which also works quite well for something like this, since you could set a default message for it.
As noted in comments, it'd be better to use a prepared statement and using a safe password storing/hashing method is highly advised.
References:
https://en.wikipedia.org/wiki/Prepared_statement
http://php.net/manual/en/faq.passwords.php

Failed Mysqli query in login php script : cannot successfully login

I have this PhP script called checklogin.php which is supposed to query 'Email' and 'motdepasse' values from a table called 'membres' (not members), the variables type are varchar (50) for Email and char (120) for motdepasse.
index.html :
<!DOCTYPE html>
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=us-ascii">
<title> Welcome to Pop </title>
<link href="normalize.css" rel="stylesheet" />
<link href="style.css" rel="stylesheet" />
</head>
<body>
<form action = "checklogin.php" method="post" name="login_form">
<section class="loginform cf">
<ul>
<li><label for="usermail">Email</label> <input name="usermail" placeholder="yourname#email.com" required="" type="email" /></li>
</ul>
<ul>
<li><label for="password">Password</label> <input name="password" placeholder="password" required="" type="password" /></li>
<li></li>
</ul>
<input type="submit" name="submit" value="Login" />
<ul>
</ul>
<p><a accesskey="N" href="Newaccount.html" title="Redirecting ">Create an account</a></p>
</section>
</form>
</body>
</html>
checklogin.php :
<?php
session_start();
$link = new MySQLi("localhost", "DBusername", "DBpassword", "DBname") ;
error_reporting(E_ALL);
if ( mysqli_connect_error() )
{
$logmessage = 'MySQL error : ' . mysqli_connect_error() ;
die('could not connect to database');
}
$Email = $_POST['Email'];
$Password = $_POST['Password'];
$query= "SELECT Email, motdepasse FROM membres WHERE Email='".$Email."' AND motdepasse='".$Password."' LIMIT 1 ";
if ($result = mysqli_query($link,$query ))
{
if( mysqli_num_rows($result) == 1 )
{
echo "login successful" ;
}
else
{
echo "wrong username or password" ;
}
}
else
{
echo' Couldnt select from table. Please check query';
}
?>
My problem is that even though the connection to the DB is made without any problem whatsoever, I get the wrong username/password message even when information typed are matching the ones in 'membres' , Email and motdepasse columns. I since added error report function but only get notices.
In your HTML there are inputs named usermail and password but in your PHP code you are trying to get $_POST['Email'] and $_POST['Password']. So just change that two lines to this:
$Email = $_POST['usermail'];
$Password = $_POST['password'];
you send data from form like
<input name="usermail" ...
so the variable is usermail but in your script you handle $_POST['Email'] and it really does not exist... first check your names of your form elements and debug what you sent via top line
var_dump($_POST); exit();
tip: always test what you have with what you expect and compare

How do I create a random generated salt?

I would very much like to know how to add a random salt to the following code, I've been looking around the Internet, but I haven't figured it out yet, at least not the "PDO way" (if it even makes a difference)?
Anyway, I've got this code:
login.php:
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/style.css" />
</head>
<body>
<div id="loginForm">
<?php
// form is submitted, check if acess will be granted
if($_POST){
try{
// load database connection and password hasher library
require 'libs/DbConnect.php';
require 'libs/PasswordHash.php';
// prepare query
$query = "select email, password from users where email = ? limit 0,1";
$stmt = $con->prepare( $query );
// this will represent the first question mark
$stmt->bindParam(1, $_POST['email']);
// execute our query
$stmt->execute();
// count the rows returned
$num = $stmt->rowCount();
if($num==1){
//store retrieved row to a 'row' variable
$row = $stmt->fetch(PDO::FETCH_ASSOC);
// hashed password saved in the database
$storedPassword = $row['password'];
// salt and entered password by the user
$salt = "whatever";
$postedPassword = $_POST['password'];
$saltedPostedPassword = $salt . $postedPassword;
// instantiate PasswordHash to check if it is a valid password
$hasher = new PasswordHash(8,false);
$check = $hasher->CheckPassword($saltedPostedPassword, $storedPassword);
/*
* access granted, for the next steps,
* you may use my php login script with php sessions tutorial :)
*/
if($check){
echo "<div>Access granted.</div>";
}
// $check variable is false, access denied.
else{
echo "<div>Access denied. <a href='login.php'>Back.</a></div>";
}
}
// no rows returned, access denied
else{
echo "<div>Access denied. <a href='login.php'>Back.</a></div>";
}
}
//to handle error
catch(PDOException $exception){
echo "Error: " . $exception->getMessage();
}
}
// show the registration form
else{
?>
<!--
-where the user will enter his email and password
-required during login
-we are using HTML5 'email' type, 'required' keyword for a some validation, and a 'placeholder' for better UI
-->
<form action="login.php" method="post">
<div id="formHeader">Website Login</div>
<div id="formBody">
<div class="formField">
<input type="email" name="email" required placeholder="Email" />
</div>
<div class="formField">
<input type="password" name="password" required placeholder="Password" />
</div>
<div>
<input type="submit" value="Login" class="customButton" />
</div>
</div>
<div id='userNotes'>
New here? <a href='register.php'>Register for free</a>
</div>
</form>
<?php
}
?>
</div>
</body>
</html>
register.php
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/style.css" />
</head>
<body>
<div id="loginForm">
<?php
// save the username and password
if($_POST){
try{
// load database connection and password hasher library
require 'libs/DbConnect.php';
require 'libs/PasswordHash.php';
/*
* -prepare password to be saved
* -concatinate the salt and entered password
*/
$salt="whatever";
$password = $salt . $_POST['password'];
/*
* '8' - base-2 logarithm of the iteration count used for password stretching
* 'false' - do we require the hashes to be portable to older systems (less secure)?
*/
$hasher = new PasswordHash(8,false);
$password = $hasher->HashPassword($password);
// insert command
$query = "INSERT INTO users SET email = ?, password = ?";
$stmt = $con->prepare($query);
$stmt->bindParam(1, $_POST['email']);
$stmt->bindParam(2, $password);
// execute the query
if($stmt->execute()){
echo "<div>Successful registration.</div>";
}else{
echo "<div>Unable to register. <a href='register.php'>Please try again.</a></div>";
}
}
//to handle error
catch(PDOException $exception){
echo "Error: " . $exception->getMessage();
}
}
// show the registration form
else{
?>
<!--
-where the user will enter his email and password
-required during registration
-we are using HTML5 'email' type, 'required' keyword for a some validation, and a 'placeholder' for better UI
-->
<form action="register.php" method="post">
<div id="formHeader">Registration Form</div>
<div id="formBody">
<div class="formField">
<input type="email" name="email" required placeholder="Email" />
</div>
<div class="formField">
<input type="password" name="password" required placeholder="Password" />
</div>
<div>
<input type="submit" value="Register" class="customButton" />
</div>
<div id='userNotes'>
Already have an account? <a href='login.php'>Login</a>
</div>
</div>
</form>
<?php
}
?>
</div>
</body>
</html>
Now, how do I create a randomly generated salt?
Use password_hash (as of PHP 5.5). It will take care of everything for you.
There is a compatibility wrapper for older PHP versions.

PHP error whilst confirming successful row insertion

people
Overview i am crating a dummy website for learning purposes therefore its functionalists are basic and security in not on the agenda atm.
I am experiencing this minor problem that i cant resolve. So why i am trying to do is to add a new account and echo a message saying that the insertion was suspenseful, but i get an error message in a place where i want to add a new record saying that the variable which suppose to hold the message is undefined.
A lil more: So when i am in the Home page of the wbesite and click a register button that is when the error message pops up but when i actually submit a query to add a account that error message changes to the message i want to show.
<?php
if(isset($_POST['submited'])){
include('connect_mysql.php');
$username= $_POST['username'];
$password = $_POST['password'];
$firstname = $_POST['first_name'];
$lastname = $_POST['last_name'];
$email = $_POST['email'];
$NewAccountQuery = "INSERT INTO users (username, password, first_name, last_name, email) VALUES ('$username','$password', '$firstname', '$lastname', '$email')";
if(!mysql_query($NewAccountQuery)){
die(mysql_error());
}//end of nested if statment
if($NewAccountQuery){
echo $confirm = "1 record added to the database";
}
}//end of if statment
?>
<html>
<head>
<title>Home Page</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="wrapper">
<header><h1>E-Shop</h1></header>
<article>
<h1>Welcome</h1>
<h1>Create Account</h1>
<div id="login">
<ul id="login">
<form method="post" action="register.php" >
<fieldset>
<legend>Fill in the form</legend>
<label>Select Username : <input type="text" name="username" /></label>
<label>Password : <input type="password" name="password" /></label>
<label>Enter First Name : <input type="text" name="first_name" /></label>
<label>Enter Last Name : <input type="text" name="last_name" /></label>
<label>Enter E-mail Address: <input type="text" name="email" /></label>
</fieldset>
<br />
<input name="submited" type="submit" submit="submit" value="Create Account" class="button">
</form>
</div>
<form action="index.php" method="post">
<div id="login">
<ul id="login">
<li>
<input type="submit" value="back" onclick="index.php" class="button">
</li>
</ul>
</div>
</form>
</article>
<aside>
<?php print $confirm; ?>
</aside>
<div id="footer">This is my site i Made coppyrights 2013 Tomazi</div>
</div>
</body>
</html>
ok here is the image before i submit the query:
Image after i submit the query:
echo $confirm = "1 record added to the database";
Should be:
$confirm = "1 record added to the database";
echo $confirm;
It looks like you don't need the echo there as you echo it else where. If all you want to do is assign $confirm to 1 record added to the database, then you just need to assign it, without the echo. Echo basically outputs it to the html in the same way print does.
I think that the error message is pretty clear. $confirm is not defined. You only define it in the "successful query" section. A simple solution is to define it before the entire if(isset($_POST['submited'])){ block. Just put $confirm = ''; and nothing will be printed out.
Some notes:
Since you are learning and this is all new, you should stop using ext/mysql now and use PDO or mysqli as your DB engine (I prefer the former).
Also, if($NewAccountQuery){ is not very meaningful. It will always be true since it's just a string you define earlier. If you switch to PDO you could check PDOStatement::rowCount.
Basically the problem is when you load the homepage for the first time - it won't go into the if(isset($_POST['submited'])) condition since $_POST['submitted'] is not set. And since you are setting the $confirm inside this loop, This statement <?php print $confirm; ?> won't find $confirm variable set. Hence it will give out PHP NOTICE.. So like someone said here either set $confirm = ''; before if condition or you can do something like this while printing
<?php
if(isset($confirm))
print $confirm;
?>
If you are just echoing or printing the string you don't need to assign it to a variable first. Either of these would work:
echo '1 record added to the database';
OR
$confirm = '1 record added to the database';
echo $confirm;
<?php
if(isset($_POST['submited'])){
include('connect_mysql.php');
$username= $_POST['username'];
$password = $_POST['password'];
$firstname = $_POST['first_name'];
$lastname = $_POST['last_name'];
$email = $_POST['email'];
$NewAccountQuery = "INSERT INTO users VALUES ('$username','$password', '$firstname', '$lastname', '$email')"; // simplified query if those are only 5 cols in order
$result = mysql_query($NewAccountQuery);
if($result){
$confirm = "1 record added to the database";
} else {
exit('error inserting row');
}
}
?>

PHP insert data to Mysql

I am experimenting with PHP and Mysql. I have created a database and table at mu localhost using xampp. I have also created a file that suppose to populate my table by executing a query, but the strange thing is that i get no errors but at the same time no DATA has been inserted into my DataBase:
CODE:
register.php:
<?php
session_start();
if(isset($_POST['submitted'])){
include('connectDB.php');
$UserN = $_POST['username'];
$Upass = $_POST['password'];
$Ufn = $_POST['first_name'];
$Uln = $_POST['last_name'];
$Uemail = $_POST['email'];
$NewAccountQuery = "INSERT INTO users (user_id,username, password, first_name, last_name, emial) VALUES ('$UserN','$Upass', '$Ufn', '$Uln', '$Uemail')";
if(!mysql_query($NewAccountQuery)){
die(mysql_error());
}//end of nested if statment
$newrecord = "1 record added to the database";
}//end of if statment
?>
<html>
<head>
<title>Home Page</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="wrapper">
<header><h1>E-Shop</h1></header>
<article>
<h1>Welcome</h1>
<h1>Create Account</h1>
<div id="login">
<ul id="login">
<form method="post" action="register.php" >
<fieldset>
<legend>Fill in the form</legend>
<label>Select Username : <input type="text" name="username" /></label>
<label>Password : <input type="password" name="password" /></label>
<label>Enter First Name : <input type="text" name="first_name" /></label>
<label>Enter Last Name : <input type="text" name="last_name" /></label>
<label>Enter E-mail Address: <input type="text" name="email" /></label>
</fieldset>
<br />
<input type="submit" submit="submit" value="Create Account" class="button">
</form>
</div>
<form action="index.php" method="post">
<div id="login">
<ul id="login">
<li>
<input type="submit" value="Cancel" onclick="index.php" class="button">
</li>
</ul>
</div>
</article>
<aside>
</aside>
<div id="footer">This is my site i Made coppyrights 2013 Tomazi</div>
</div>
</body>
</html>
I have also one include file which is connectDB:
<?php
session_start();
$con = mysql_connect("127.0.0.1", "root", "");
if(!$con)
die('Could not connect: ' . mysql_error());
mysql_select_db("eshop", $con) or die("Cannot select DB");
?>
Database structure:
database Name: eshop;
only one table in DB : users;
users table consists of:
user_id: A_I , PK
username
password
first_name
last_name
email
I spend a substantial amount of time to work this out did research and looked at some tutorials but with no luck
Can anyone spot what is the root of my problem...?
It is because if(isset($_POST['submitted'])){
you dont have input field with name submitted give the submit button name to submitted
<input name="submitted" type="submit" submit="submit" value="Create Account" class="button">
Check your insert query you have more fields than your values
Change :
$NewAccountQuery = "INSERT INTO users (user_id,username, password, first_name, last_name, email) VALUES ('$UserN','$Upass', '$Ufn', '$Uln', '$Uemail')";
to :
$NewAccountQuery = "INSERT INTO users (user_id,username, password, first_name, last_name, email) VALUES ('','$UserN','$Upass', '$Ufn', '$Uln', '$Uemail')";
Considering user_id is auto increment field.
Your email in query is written wrongly as emial.
Is error reporting turned on?
Put this on the top of your screen:
error_reporting(E_ALL);
ini_set('display_errors', '1');
Some good answers above, but I would also suggest you make use of newer MySQLi / PDO instead of outdated 2002 MySQL API.
Some examples: (i will use mysqli since you wrote your original example in procedural code)
connectDB.php
<?php
$db = mysqli_connect('host', 'user', 'password', 'database');
if (mysqli_connect_errno())
die(mysqli_connect_error());
?>
register.php -- i'll just write out an example php part and let you do the rest
<?php
//i'll always check if session was already started, if it was then
//there is no need to start it again
if (!isset($_SESSION)) {
session_start();
}
//no need to include again if it was already included before
include_once('connectDB.php');
//get all posted values
$username = $_POST['username'];
$userpass = $_POST['password'];
$usermail = $_POST['usermail'];
//and some more
//run checks here for if fields are empty etc?
//example check if username was empty
if($username == NULL) {
echo 'No username entered, try again';
mysqli_close($db);
exit();
} else {
//if username field is filled we will insert values into $db
//build query
$sql_query_string = "INSERT INTO _tablename_(username,userpassword,useremail) VALUES('$username','$userpass','$usermail')";
if(mysqli_query($db,$sql_query_string)) {
echo 'Record was entered into DB successfully';
mysqli_close($db);
} else {
echo 'Ooops - something went wrong.';
mysqli_close($db);
}
}
?>
this should work quite nicely and all you need to add is your proper posted values and build the form to post it, that's all.
<?php
$db = mysqli_connect('host', 'user', 'password', 'database');
if (mysqli_connect_errno())
die(mysqli_connect_error());
?>
register.php -- i'll just write out an example php part and let you do the rest
<?php
//i'll always check if session was already started, if it was then
//there is no need to start it again
if (!isset($_SESSION)) {
session_start();
}
//no need to include again if it was already included before
include_once('connectDB.php');
//get all posted values
$username = $_POST['username'];
$userpass = $_POST['password'];
$usermail = $_POST['usermail'];
//and some more
//run checks here for if fields are empty etc?
//example check if username was empty
if($username == NULL) {
echo 'No username entered, try again';
mysqli_close($db);
exit();
} else {
//if username field is filled we will insert values into $db
//build query
$sql_query_string = "INSERT INTO _tablename_(username,userpassword,useremail) VALUES('$username','$userpass','$usermail')";
if(mysqli_query($db,$sql_query_string)) {
echo 'Record was entered into DB successfully';
mysqli_close($db);`enter code here`
} else {
echo 'Ooops - something went wrong.';
mysqli_close($db);
}
}
?>

Categories