I have an output_errors function on my website which outputs all the "set" errors in a variable.
It pretty much works exactly how it should except for one thing; for one error in particular, it will output that error more than once (which it shouldn't).
How it is supposed to work is: if the user that is registering does not input any information into a certain part of the form, it needs to output (once) the error Fields marked with an asterisk(*) must be filled in., along with any other errors that the user has come across. All of this is displayed in an unordered list.
This is the function that I have created:
function output_errors($errors){
return '<ul><li>' . implode('</li><li>', $errors) . '</li></ul>';
}
This is the code in which I specify when an error should be output:
$required = array('fname', 'username', 'password', 'password_again', 'email');
$reqCCNo = array('ccno');
// validation
foreach($_POST as $key=>$value){
if(empty($value) && in_array($key, $required) === true){
$errors[] = 'Fields marked with an asterisk(*) must be filled in.';
}
if(empty($value) && in_array($key, $reqCCNo) === true){
$errors[] = 'Please select a country.';
}
}
if(empty($errors)){
// credentials
if(preg_match('/[^a-z_\-0-9]/i', $fnp) || preg_match('/[^a-z_\-0-9]/i', $lnp)){
$errors[] = 'Credentials must only contain letters and numbers.';
}
// username
$result = mysqli_query($conn, "SELECT username FROM users WHERE username = '$user'");
$count = mysqli_num_rows($result);
if($count !== 0) {
$errors[] = 'That username is already taken.';
}
if(strlen($user) < 4){
$errors[] = 'Your username must be more than 4 characters long.';
}
if(strlen($user) > 16){
$errors[] = 'Your username must not be more than 16 characters long.';
}
if(preg_match('/[^a-z_\-0-9]/i', $user)){
$errors[] = 'Your username can only contain Alphanumeric characters.';
}
// email
if(filter_var($emailNex, FILTER_VALIDATE_EMAIL) === false){
$errors[] = 'That is not a valid email type.';
}
$email_result = mysqli_query($conn, "SELECT email FROM users WHERE email = '$emailNex'");
$email_count = mysqli_num_rows($email_result);
if($email_count !== 0) {
$errors[] = 'That email is already in use.';
}
// password
if(strlen($pass) < 6){
$errors[] = 'Your password must be more than 6 characters long.';
}
if($pass !== $_POST['password_again']){
$errors[] = 'Those passwords do not match!';
}
}
and, this is the code that I use to output all of those errors:
if(!empty($errors)){
echo output_errors($errors);
}
Say that I leave all the fields blank and input a username less than 4 characters long, this is how it should be output:
Fields marked with an asterisk(*) must be filled in.
Your username must be more than 4 characters long.
this is how it is being output right now:
Fields marked with an asterisk(*) must be filled in.
Fields marked with an asterisk(*) must be filled in.
Fields marked with an asterisk(*) must be filled in.
Please select a country.
Your username must be more than 4 characters long.
All help is appreciated!
Thanks
Problem is with your foreach loop. it insert error message for every Required file.
You need to create a flag outside your foreach loop and set it to true when it comes inside your condition as
$flag=FALSE;// set it false
foreach($_POST as $key=>$value){
if(empty($value) && in_array($key, $required) === true){
$flag=TRUE;// set true if fulfill your condition
}
}
if($flag){// set your message
$errors[] = 'Fields marked with an asterisk(*) must be filled in.';
}
It will set your error message once instead of multiple
Related
I am struggling to understand why my code is telling me that my username is undefined whenever I try to load up this page. the error is Notice: Undefined index: username in /home/jmask072/public_html/login.php on line 12. Any help is appreciated.
<?php
$users = array("user" => '$2y$10$yHL4GKr4pKxnBJ1L2xlqYuI/k0kviae2NbIQNJLFeXgVclT2hZeDi');
$isLoggedIn = false;
$errors = array();
$required = array("username", "pass");
foreach ($required as $key => $value) {
if (!isset($_POST[$value]) || empty($_POST[$value])) {
$errors[] = "please fill out the form";
}
}
if (array_key_exists($_POST['username'],$users)) {
$userPassword = $_POST['pass'];
$dbPass = $users[$_POST['username']];
if (password_verify($userPassword,$dbPass) === true) {
$isLoggedIn = true;
} else {
$isLoggedIn = false;
$errors[] = "Username not found or password incorrect";
}
} else {
$errors[] = "Username not found or password incorrect";
}
require_once("Template.php");
$page = new Template("My Login");
$page->addHeadElement("<link rel=\"stylesheet\" href=\"styles.css\">");
$page->addHeadElement("<script src='hello.js'></script>");
$page->finalizeTopSection();
$page->finalizeBottomSection();
print $page->getTopSection();
if (count($errors) > 0) {
foreach ($errors as $error) {
print "Error";
}
}
else if ($isLoggedIn === true) {
print "Hello, you are logged in";
}
print "<form action =\"login_action.php\" method =\"POST\" class=\"form-signin\">";
print "<h1>Please sign in</h1>\n";
print "<label for=\"inputUser\">Username</label>";
print "<input type=\"password\" name=\"pass\" id=\"inputPassword\" placeholder=\"password\">";
print "<button type=\"submit\"> Sign in</button>";
print $page->getBottomSection();
?>
first you should use a single quotes ' '
it is a very good alternative for backslash
and
print "<label for='inputUser'>Username</label>";
here you add label for inputUser but i dont see any input ??
You do need to make the script work even if the page is not requested correctly because you have no control on the requests it will get. Then you have to make sure that YOU call it correctly when you do it (right now this is not the case).
You are seeing the notice because, even if your code does check for the existence of the POST variables it needs (lines 6-10), even if the check fails it still attempts to read them at line 12.
The whole code block if...then...else starting at line 12 should only be executed if the checks went well (i.e. if(empty($errors)) {...). Now if the page is requested incorrectly at least you will get a useful error message that will help you understand where the problem is.
In this case the error message is "please fill out the form". In fact the code expects a form with two input fields but the one it displays only has the password field (which is unhelpfully labelled "Username") and has no username field. You need to provide both fields and make sure that the name attributes match the POST variables you want to get the data from (the for attribute in the label tags should also match the field name exactly).
I've started learning PHP and MySQL for a while but I still consider myself a beginner!
I created a simple register form and I also wrote PHP code to validate it...
I want to know if there is a better and smarter way to accomplish my goal.
My form is based on 5 inputs: username, password, repeat password, email, repeat email and it sends through POST, their content and a button's value. It must check these conditions when a submit is performed:
show error "All fields empty" if all inputs are empty
show error "Some fields empty" if one or more inputs, but not all, are empty
username length must be up to 20 chars
password and repeat password must be equal
passwords must be between 8 and 20 chars
email and repeat email must be valid emails and must be equal
show an error message of what went wrong
I wrote this function (it's inside a class) which does everything I said above but can I improve it to reduce repetitive code? Are there other PHP functions which can be used for this? And finally, how secure is my code?
Here is it!
public function processRegisterInfo($POSTArray = array())
{
if (count(array_filter($POSTArray)) > 1) // button don't have to be counted
{
if (count(array_filter($POSTArray)) < 6)
{
$this->errorMsg = "Some fields are empty";
return FALSE;
}
else
{
$username = $POSTArray["username"];
$password = $POSTArray["password"];
$repPassword = $POSTArray["repPassword"];
$email = $POSTArray["email"];
$repEmail = $POSTArray["repEmail"];
$isValid = TRUE;
// Checking username length
if (strlen($username) > 20)
{
$this->errorMsg .= " Username too long.";
$isValid = FALSE;
}
// Checking password length and equality
if (strcmp($password, $repPassword) == 0)
{
if (strlen($password) < 8)
{
$this->errorMsg .= " Password must be at least 8 characters.";
$isValid = FALSE;
}
else if (strlen($password) > 20)
{
$this->errorMsg .= " Password must be max 20 characters long.";
$isValid = FALSE;
}
}
else
{
$this->errorMsg .= " Passwords don't match.";
$isValid = FALSE;
}
// Checking email validation and equality
if (strcmp($email, $repEmail) == 0)
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$this->errorMsg .= " Email provided is not valid.";
$isValid = FALSE;
}
}
else
{
$this->errorMsg .= " Emails don't match.";
$isValid = FALSE;
}
if (isset($this->errorMsg) && !empty($this->errorMsg))
$this->errorMsg = substr($this->errorMsg, 1);
return $isValid;
}
}
else
{
$this->errorMsg = "All fields are empty";
return FALSE;
}
}
Thank you so much for your help! :)
If you are only able to use php it's as good as it's going to get i think.
These check can be performed by Jquery(javasript) to.
The pros of using jquery are, you don't have to submit it first and you can easily mark which field has a wrong value.
im writing this php script to update user passwords, requiring old pasword, new and new confirmation. It all works it seems up to the actual UPDATE mysql statement. Not sure what I've done wrong, al help appreciated!
Also, I am aware its not secure and such, I am just trying ot make it work first im a php newbie!
I'm tearing my hair out, when I run this, everything seems to work except it breaks just before if (empty($error)){ , i have tested the echo for session email and it displays that, however it does not update the database with the new password. Please help! below is my code:
<?php
session_start();
include('database_connection.php');
$error = array();
if (empty($_POST['oldpassword'])){
$error[] ='You did not enter your current password!';
} else {
$oldpassword = $_POST['oldpassword'];
}
if (empty($_POST['newpassword'])){
$error[] = 'You did not enter a new password!';
} else {
if(preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $_POST["newpassword"])){
$newpassword = $_POST['newpassword'];
} else{
$error[] = 'Password must be at least 8 characters and must contain at least one lower case letter, one upper case letter and one digit!';
}
}
if (empty($_POST['newpasswordcon'])){
$error[] = 'You did not enter your new password confirmation!';
} else {
if(preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $_POST["newpasswordcon"])){
$newpasswordcon = $_POST['newpasswordcon'];
} else{
$error[] = 'Password must be at least 8 characters and must contain at least one lower case letter, one upper case letter and one digit!';
}
}
if($_POST['newpassword'] != $_POST['newpasswordcon']){
$error[] ='New password and confirmation do not match!' ;
}
$sql = "SELECT password FROM users WHERE email='" . $_SESSION['email'] . "'";
$result = mysql_query($sql);
if( $r = mysql_fetch_array($result) ) {
extract($r);
if($_POST['oldpassword'] != $password);{
$error[] ='Incorrect current password!';
}
//breaks here
echo $_SESSION['email'];
if (empty($error)){
echo $_SESSION['email'];
mysql_query("UPDATE users SET password='$newpassword' WHERE email='" . $_SESSION['email'] . "'");
echo '<p class ="alert alert-success fade in">Success! Your password has been updated!</p>';
}
} else{
foreach ($error as $key => $values) {
echo '<p class ="alert alert-error fade in">'.$values.'</p>';
}
}
?>
There is a semicolon which should not be there.
if ($_POST['oldpassword'] != $password);{ // <- remove this semicolon after )
$error[] ='Incorrect current password!';
}
I don't see any addslashes() in your code and am wondering if you get any matches? http://www.php.net/manual/en/function.addslashes.php
I am having issues with my PHP code. I am trying to insert data into a mysql database using two session variables that I will need at a later time in the form. However whenever I submit the form I am returned with a "Unknown column in 'field list'" error.
The code is lengthy but you will likely need all of it to understand the issue.
<?php
session_start();
// Check for hazards and put them in an array if there is one selected
if($_SERVER['REQUEST_METHOD'] == 'POST') {
require ('../mysqli_connect.php'); //connect to the db
//Check for offender first name
if (empty($_POST['pris_firstname'])) {
$errors[] = 'You forgot to enter offender first name.';
} else {
$prisf=$_POST['pris_firstname'];
}
//Check for offender last name
if (empty($_POST['pris_lastname'])) {
$errors[] = 'You forgot to enter offender last name.';
} else {
$prisl=$_POST['pris_lastname'];
}
//Check for offender date of birth
$dob = ($_POST['pris_dateofbirth']);
//Check for offender phone number
if (empty($_POST['pris_phonenum'])) {
$errors[] = 'You forgot to enter offender Phone Number.';
} else {
$prisphone=trim($_POST['pris_phonenum']);
}
//Check for offender address
if (empty($_POST['pris_address'])) {
$errors[] = 'You forgot to enter offender Address.';
} else {
//$prisaddress=trim($_POST['pris_address']);
foreach($_POST["pris_address"] as $value) {
$prisaddress .= $value . '\n';
}
}
//Check for offender next of kin first name
if (empty($_POST['pris_kinfirstname'])) {
$errors[] = 'You forgot to enter next of kin first name.';
} else {
$kinfirst=trim($_POST['pris_kinfirstname']);
}
//Check for offender next of kin last name
if (empty($_POST['pris_kinlastname'])) {
$errors[] = 'You forgot to enter next of kin last name.';
} else {
$kinlast=trim($_POST['pris_kinlastname']);
}
//Check for offender next of kin phone number
if (empty($_POST['pris_kinphone'])) {
$errors[] = 'You forgot to enter next of kin area code.';
} else {
$kinphone=trim($_POST['pris_kinphone']);
}
if (empty($_POST['pris_kinrelation'])) {
$errors[] = 'You forgot to enter next of kin relation.';
} else {
$kinrelation=trim($_POST['pris_kinrelation']);
}
//Check for offender next of kin address
if (empty($_POST['pris_kinaddress'])) {
$errors[] = 'You forgot to enter next of kin street address.';
} else {
foreach($_POST["pris_kinaddress"] as $value2) {
$kinaddress .= $value2 . '\n';
}
}
if (empty($errors)) { //if everyhing is ok
$q = "INSERT INTO prisoner_profile (pris_status,
pris_firstname,
pris_lastname,
pris_dateofbirth,
pris_phonenum,
pris_address,
pris_kinfirstname,
pris_kinlastname,
pris_kinphone,
pris_kinaddress,
pris_kinrelation
) VALUES (
'$status',
".$_SESSION['pris_firstname'].", ".$_SESSION['pris_lastname'].",
'$dob',
'$prisphone',
'$prisaddress',
'$kinfirst',
'$kinlast',
'$kinphone',
'$kinaddress',
'$kinrelation'
)";
$r = #mysqli_query ($dbc, $q); //Run the query.
Hope someone can help!
The error is pretty much self-explanatory, it means that you have got a column name wrong in your database. I recomend you echo out the error for your query just for this case as:
$r = mysqli_query ($dbc, $q) or die (mysqli_error());
One of the columns that are listed in your INSERT statement does not actually exist in the prisoner_profile. Check your table schema.
The one obvious issue I can see here is that you haven't handled the escape characters in your query, and you have used a few \n characters in your code.
Use mysqli_real_escape_string to handle that when inputting the data to the database.
Something like
$q = mysqli_real_escape_string($q);
I'd like to make a registration input field that only accepts certain types of email addresses (e.g., one that only accepts email addresses that end with #yahoo.com) so that I can provide some security in terms of who can access my website (e.g., I want to only accept email addresses that are from students from my school, i.e., they must end in #school.edu).
Here's what i have so far, but this does not discriminate for a specific type of email:
<?php
// configuration
require("../includes/config.php");
// if form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// validate inputs
if (empty($_POST["username"]))
{
apologize("You must provide a username.");
}
else if (empty($_POST["password"]))
{
apologize("You must provide a password.");
}
else if (empty($_POST["confirmation"]) || $_POST["password"] != $_POST["confirmation"])
{
apologize("Those passwords did not match.");
}
// try to register user
$results = query("INSERT INTO users (username, hash, cash) VALUES(?, ?, 10000.0000)",
$_POST["username"], crypt($_POST["password"])
);
if ($results === false)
{
apologize("That username appears to be taken.");
}
// get new user's ID
$rows = query("SELECT LAST_INSERT_ID() AS id");
if ($rows === false)
{
apologize("Can't find your ID.");
}
$id = $rows[0]["id"];
// log user in
$_SESSION["id"] = $id;
// redirect to portfolio
redirect("/");
}
else
{
// else render form
render("register_form.php", ["title" => "Register"]);
}
?>
You can use the substr() function combined with the strrpos() to get the last part of the email:
if(substr($email, strrpos($email, "#")) == "#school.edu") {
//all good
}
Once you have done that, you can email them a confirmation link to the email provided to make sure it's not a bogus one.
You can also use simple regex to verify user's email
if(preg_match('#^(.*)\#school\.edu$#', $_POST['email'])) {
echo 'email is valid';
} else {
echo 'this is not valid email!';
}