Variable always being set to 0 despite conditional blocks - php

The following block of code is an attempt to give some feedback for what a user may be inputting incorrectly and that side of it is working alright.
The part I am having trouble with is the else block. It seems to always set the $MaxNum variable to 0. If I remove the declaration from the else block it works fine, although obviously doesn't allow my code above to validate the input. I am probably overlooking something quite basic so any help would be great.
global $MaxNum, $TheNum;
if (isset($_POST['Submit'])) {
if (empty($_POST['maxnum'])){
$error[] = "<p>Please enter at least something!";
if($_POST['maxnum'] == 0){
$error[] = "<p>Zero doesn't count!";
}
}
if (!is_numeric($_POST['maxnum'])){
$error[] = "<p>You didn't enter a number!";
}
if (is_numeric($_POST['maxnum'])){
if(($_POST['maxnum'])>2147483647){
$error[] = "<p>2.14 Billion jellybeans is a little excessive, right?";
}
}
else{
$MaxNum = $_POST['maxnum'];
}
}

Some tips:
Try to use functions and early returns in your code, it makes your flow easier.
Try to use less nested if statements and use else if
An example with function and early returns:
global $MaxNum, $TheNum;
function handleFormSubmit(): string
{
if (!isset($_POST['Submit']) || !isset($_POST['maxnum'])) {
return "<p>Please enter at least something!</p>";
}
if(empty(['maxnum'])) {
return "<p>Please fill in a number</p>!";
}
if($_POST['maxnum'] == 0) {
return "<p>Zero doesn't count</p>!";
}
if (!is_numeric($_POST['maxnum'])) {
return "<p>You didn't enter a number!";
}
if (is_numeric($_POST['maxnum']) && $_POST['maxnum'] > 2147483647) {
return "<p>2.14 Billion jellybeans is a little excessive, right?";
}
$MaxNum = $_POST['maxnum'];
return '';
}
$errorMessage = handleFormSubmit();

Used #robbert van den Bogerd's tips to clean up my if statements and then implemented that. Still had the issue of the input being passed as there was nothing stopping that.
Created a new variable called $ValidInput and used it to hold a bool.
Through the checking I set it to False if it met any conditions.
Then at the end of the checks I attach the input to $MaxNum if $ValidInput remains True through the checking, if it made it to that point and was True it must meet our requirements.
global $MaxNum, $TheNum, $ValidInput;
$ValidInput = True;
if (isset($_POST['Submit'])) {
if (empty($_POST['maxnum'])) {
$error[] = "<p>Please enter at least something!</p>";
$ValidInput = False;
}
if(empty($_POST['maxnum']) && (!is_numeric($_POST['maxnum']))) {
$error[] = "<p>Please enter a number!</p>";
$ValidInput = False;
}
if($_POST['maxnum'] == 0) {
$error[] = "<p>Zero doesn't count!</p>";
$ValidInput = False;
}
if (!is_numeric($_POST['maxnum']) && (!empty($_POST['maxnum']))) {
$error[] = "<p>That's not a number!</p>";
$ValidInput = False;
}
if (is_numeric($_POST['maxnum']) && $_POST['maxnum'] > 2147483647) {
$error[] = "<p>Anything over 2.14 Billion jellybeans is a little excessive, right?";
$ValidInput = False;
}
if($ValidInput == True){
$MaxNum = $_POST['maxnum'];
}
}

Related

PHP show full list of errors in a array

I use OOP and i wanted to ask you guys how this would be done! I keep trying but its still not working ;(
Here is my class file:
class Signup {
// Error
public $error = array();
public function validate($username, $email_mobile, $password) {
if(!empty($username) || !empty($email_mobile) || !empty($password)){
if(strlen($username) < 3 || strlen($username) > 50){
$this->error = "Username is too short or too long!";
return $this->error;
}elseif(strlen($email_mobile) < 3 || strlen($email_mobile) > 50) {
$this->error = "Email is too short or too long!";
return $this->error;
}elseif(strlen($password) < 3 || strlen($password) > 50){
$this->error = "Password is too short or too long!";
return $this->error;
}
} else {
$this->error = "Please fill are required feilds";
return $this->error;
}
}
Here is my signup file
$error[] = $signup->validate($username, $email_mobile, $password);
<?php
// require('lib/function/signup.php');
if(isset($error)){
var_dump($error);
foreach ($error as $value) {
echo $value . "<br>";
}
}
?>
I know That im calling the $error in the same file and not the property error. But i dont know how to send this array to the other file! Please help me! Also i have Called everything and the problem is just with my code(i think), i only included my file and made a var to call my signup class
It is never too early in your development career to study coding standards. Jump straight to PSR-12, and adopt all of these guidelines to write beautiful, professional code.
Use data type declarations in your classes where possible, it will improve the data integrity throughout your project(s).
You appear to prefer returning an array of errors. For this reason, I see no benefit in caching the errors long-term in a class property. This coding style is fine to do, but you could choose to return nothing (void) and instead populate a class property $errors, then access it directly after the $signup->validate() call via $signup->errors or use a getter method.
The empty() checks are too late in the flow. Once the values have been passed to the class method, these values must already be declared. For this reason empty() is needless overhead to check for mere "falsiness". Just check the values' string length.
Your data quality checks seem a little immature (email and password checks should be much more complex), but I won't confuse you with any new complexity, but I do expect that your validation rules will increase as you realize that users cannot be trusted to put good values in forms without be forced to do so. For this reason, it is probably unwise to use a loop to check the value lengths because you will eventually need to write individual rules for certain values.
A possible write up:
class Signup
{
public function validate(
string $username,
string $email,
string $password
): array
{
$errors = [];
$usernameLength = strlen($username);
if ($usernameLength < 3 || $usernameLength > 50) {
$errors[] = "Username must be between 3 and 50 characters";
}
$emailLength = strlen($email);
if ($emailLength < 3 || $emailLength > 50) {
$errors[] = "Email must be between 3 and 50 characters";
}
$passwordLength = strlen($password);
if ($passwordLength < 3 || $passwordLength > 50) {
$errors[] = "Password must be between 3 and 50 characters";
}
return $errors;
}
}
When calling this method...
$signup = new Signup();
$errors = $signup->validate(
$_POST['username'] ?? '',
$_POST['email'] ?? '',
$_POST['password'] ?? ''
);
if ($errors) {
echo '<ul><li>' . implode('</li><li>', $errors) . '</li></ul>';
} else {
echo 'No errors';
}
You should add elements to the array, instead of overwriting it, and returning, on all the branches.
class Signup {
public $errors = [];
public function validate($username, $email_mobile, $password) {
if (empty($username)) {
$this->error[] = "Username cannot be empty";
} else {
$strlenUsername = strlen($username);
if ($strlenUsername < 3 || $strlenUsername > 50){
$this->errors[] = "Username is too short or too long!";
}
}
if (empty($email_mobile)) {
$this->error[] = "Email cannot be empty";
} else {
$strlenEM = strlen($email_mobile);
if ($strlenEM < 3 || $strlenEM > 50) {
$this->errors[] = "Email is too short or too long!";
}
}
if (empty($password)) {
$this->errors[] = "Password cannot be empty";
} else {
$strlenPass = strlen($password);
if ($strlenPass < 3 || $strlenPass > 50) {
$this->errors[] = "Password is too short or too long!";
}
}
return $this->errors;
}
}
If you always keep the same constrains for the three fields, you can shorten it:
class Signup {
public function validate($username, $email_mobile, $password) {
$errors = [];
$fields = [
'Username' => $username,
'Email' => $email_mobile,
'Password' => $password
];
foreach($fields as $key => $value) {
if (empty($value)) {
$errors[] = "$key cannot be empty";
} else {
$strlen = strlen($value);
if ($strlen < 3 || $strlen > 50) {
$errors[] = "$key is too short or too long!";
}
}
}
return $errors;
}
}
The above code guesses at what you are trying to do, if you just wanted a fix for not getting any results on $error see the original answer below.
Original answer.
Updating your code to this should give you the results you expect.
class Signup {
// Error
public $error = array();
public function validate($username, $email_mobile, $password) {
if (!empty($username) || !empty($email_mobile) || !empty($password)){
$strlenUsername = strlen($username);
$strlenEM = strlen($email_mobile);
$strlenPass = strlen($password);
if ($strlenUsername < 3 || $strlenUsername > 50){
$this->error[] = "Username is too short or too long!";
} elseif ($strlenEM < 3 || $strlenEM > 50) {
$this->error[] = "Email is too short or too long!";
} elseif ($strlenPass < 3 || $strlenPass > 50){
$this->error[] = "Password is too short or too long!";
}
} else {
$this->error[] = "Please fill are required feilds";
}
return $this->error;
}
}
Keep in mind that, since you are using if-else you will always have, at most, one element in the array, it is hard to tell what you are trying to do with certainty, so I didn't change the logic and just fixed the most obvious problem.
If you want to add error messages to the array, get rid of the else keyword on the conditionals.
If you want to only receive one error message, consider using a string instead of an array.

PHP - Check if one of two form fields is filled?

My form has Phone and Email fields.
Many people might not be wanting/able to put both,
so I thought, that the validator would require only
one of those two filled, instead of requiring the both filled.
I've tried thinking of different ways to do it but I'm pretty new to PHP,
so I couldn't come with any.
Would this be possible?
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{$name = test_input($_POST["name"]);}
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{$email = test_input($_POST["email"]);}
if (empty($_POST["phone"]))
{$phone = "";}
else
{$website = test_input($_POST["website"]);}
if (empty($_POST["comment"]))
{$comment = "";}
else
{$comment = test_input($_POST["comment"]);}
}
Thank you.
As your title states, 1 / 2 form fields is filled in.
$i = 0; // PUT THIS BEFORE YOUR IF STATEMENTS
Inside of your statements:
if (empty($_POST["phone"])) {
$phone = "";
} else {
$i++; // PUT THIS IN ALL YOU WANT TO COUNT, IT WILL ADD 1 to $i EACH TIME YOU CALL IT
$website = test_input($_POST["website"]);
}
Now at the end, if
// YOU NEED TO CHANGE YOUR NUMBERS TO WHATEVER COUNT YOU WANT
if ($i < 2) { // IF $i IS LESS THAN 2
// YOUR CODE HERE
} else { // IF $i IS 2 OR MORE
// YOUR CODE HERE
}
Hope this is somewhat useful!
or as stated above, you can use an
if (#$A && #$B) { // REQUIRES BOTH TO BE TRUE
// YOUR CODE HERE
} elseif (#$A || #$B) { // REQUIRES ONLY ONE TO BE TRUE
// YOUR CODE HERE
} else { // NONE ARE TRUE
// YOUR CODE HERE
}
if you are wondering about the # signs above, they are simply checking if they are set, you could change the code to !empty($A) which is what you used above. Putting the ! before the empty function checks that it is false or that $A is actually set.
If i would have to check a form like you, i'd do it this way:
$res = '';
if(empty($_POST['name']))
$res .= 'The name is required.<br>';
if(empty($_POST['email']))
$res .= 'The email is required.<br>';
if(empty($_POST['phone']) && empty($_POST['email']))
$res .= 'You need to enter phone or email.<br>';
if(strlen($res) > 0) {
echo 'We have these errors:';
echo $res;
}
else {
echo 'No Errors!';
}
If you want to show only one error each time, use this code:
$res = '';
if(empty($_POST['name']))
$res = 'The name is required.<br>';
elseif(empty($_POST['email']))
$res = 'The email is required.<br>';
elseif(empty($_POST['phone']) && empty($_POST['email']))
$res = 'You need to enter phone or email.<br>';
if(strlen($res) > 0) {
echo $res;
}
else {
echo 'No Error!';
}
Even if i think it's very basic, i'll explain the mentioned part, even if you could look it up from php.net:
$res .= 'The name is required';
The ".=" operator adds the part 'The name is required' to the variable $res. If this happens the first time, the variable will be empty, because i initialized it as an empty string. With every ongoing line, another error Message will be added to the string.
if(strlen($res) > 0) {
strlen() will return the length of the string in $res. If no error occured, it would still be empty, so strlen() would return 0.

Function to validate username and password not working [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Regular Expression matching for entire string
On my form page, I am trying to make it only accept alphanumeric characters for my username and password and require that they be from 6 to 15 characters. When I type in invalid data, it will insert it into the database rather than throw the user error that I defined in my CheckAlNum function.
functions.php
function checkAlNum($whichField)
{
if (preg_match('/[A-Za-z0-9]+/', $_POST[$whichField])){
if ( (!count(strlen($whichField) >= 6)) OR (!count(strlen($whichField) <= 15 ))) {
$message1 = '<p> Username and password must be between 6 and 15 characters </p>';
return user_error($message1);
}
else{
return true;
}
}
else {
$message = '<p>Username and password can only be numbers or letters</p>';
return user_error($message);
}
}
Form.php
if (count($_POST) > 0) {
//Validate the inputs
$errorMessages = array();
//Validate the username
$item5 = checkAlNum('username');
if($item5 !== true) {
$errorMessages[] = $item5;
}
//Validate the password
$item6 = checkAlNum('password');
if($item6 !== true) {
$errorMessages[] = $item6;
}
//Validate the firstName and lastName
$item1 = checkNameChars('firstName');
if ($item1 !== true) {
$errorMessages[] = $item1;
}
$item2 = checkNameChars('lastName');
if ($item2 !== true) {
$errorMessages[] = $item2;
}
//Validate the office name
$item3 = checkOfficeChars('office');
if ($item3 !== true) {
$errorMessages[] = $item3;
}
//Validate the phone number
$item4 = validate_phone_number('phoneNumber');
if($item4 !== true) {
$errorMessages[] = $item4;
}
//Check to see if anything failed
if (count($errorMessages) == 0) {
$newEmployee = new Person;
$newEmployee -> insert();
}
else { //Else, reprint the form along with some error messages
echo "<h2><span>Error</span>: </h2>";
foreach($errorMessages as $msg) {
echo "<p>" . $msg . "</p>";
}
}
}
?>
I've tried playing around with the nesting of the if-else statements of the checkAlNum function and also the regex (although I'm pretty sure the regex is right). Maybe I'm just missing something really silly?
function checkAlNum($whichField)
{
if (preg_match('/^[a-z0-9]{6,15}$/i', $_POST[$whichField])) {
return true;
}
else {
$message = '<p>Username and password can only be numbers or letters, 6-15 characters long</p>';
return user_error($message);
}
}
Without the ^ and $ anchors, your regex only checks whether there are alphanumerics anywhere in the field, not that the whole thing is alphanumeric. And changing + to {6,15} implements the length check here, so you can remove that extra check in your code.
I think the second if statement is incorrect. It should be like this:
if ( !( (!count(strlen($whichField) >= 6)) OR (!count(strlen($whichField) <= 15 )) ) ) {
// ... do something
}
This is due to De Morgan Rule which states
A AND B = !( !A OR !B )
In any case, I would not do my checks this way, strucurally you will end up with too many nested if statements that are hard to maintain and make your code look unpretty. Try avoiding nested conditions in your code.
Barmar's answer is the best. But if you want to keep your if statement to check string length, you need to remove the count() as you are already checking the length using strlen().
if ( (!(strlen($whichField) >= 6)) OR (!(strlen($whichField) <= 15 ))) {

email validation in php

I'm trying to validate my username as an email address, however PHP isn't letting me do this! what's wrong here?
//This checks if all the fields are filled or not
if (!empty($_POST['username']) ||
!empty($_POST['password']) ||
!empty($_POST['repassword']) ||
!empty($_POST['user_firstname']) ||
!empty($_POST['user_lastname']) ){
header('Location: register.php?msg=You didn\'t complete all of the required fields');
}
if (filter_var($_POST['username'], FILTER_VALIDATE_EMAIL) === false){
$errors[] = 'The email address you entered is not valid';
}
here is the form i used in register.php
<form action="createuser.php" method="post" name="registration_form" id="registration_form">
<label>Email</label>
<input name="username" type="text" id="username" size="50" maxlength="50" /><br />
Typo?
header('Location: register.php?msg=You didn't complete all of the required fields');
^---unescaped embedded quote
Your empty logic is also faulty. You're checking if any fields are NOT empty (e.g. filled out) and then complaining that they're not filled out. remove the ! to invert the logic.
if (empty(...) || empty(...) || etc...)
instead of this use regular expression for validating your email address
function check_email_address($email) {
// First, we check that there's one # symbol,
// and that the lengths are right.
if (!preg_match("^[^#]{1,64}#[^#]{1,255}$", $email)) {
// Email invalid because wrong number of characters
// in one section or wrong number of # symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("#", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if
(!preg_match("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&
↪'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$",
$local_array[$i])) {
return false;
}
}
// Check if domain is IP. If not,
// it should be valid domain name
if (!preg_match("^\[?[0-9\.]+\]?$", $email_array[1])) {
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) {
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++) {
if
(!preg_match("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|
↪([A-Za-z0-9]+))$",
$domain_array[$i])) {
return false;
}
}
}
return true;
}
and then check if it return true redirect it to location if not then simply throw an error
You would not get to Validate the email because your if statement is wrong .. it is checking if any of the post is not empty.
Replace it with
if (empty($_POST['username']) || empty($_POST['password']) || empty($_POST['repassword']) || empty($_POST['user_firstname']) || empty($_POST['user_lastname'])) {
For starters, look at the syntax highlighting for why you're getting parse errors.
header('Location: register.php?msg=You didn't complete all of the required fields');
needs to become:
header('Location: register.php?msg=You didn\'t complete all of the required fields');
How about you use javascript window.location? Sometimes header function is sensitive.And also put a submit button in your form since by default fields are empty when loaded.
if(isset($_POST['your_submit_button_name'])){
if (empty($_POST['username']) ||
empty($_POST['password']) ||
empty($_POST['repassword']) ||
empty($_POST['user_firstname']) ||
empty($_POST['user_lastname']) ){
?>
<script>
window.location = 'register.php?msg=You didn\'t complete all of the required fields';
</script>
<?php
}
if (filter_var($_POST['username'], FILTER_VALIDATE_EMAIL) === false){
$errors[] = 'The email address you entered is not valid';
}
}
NOTE: I remove "!" before your empty function since youre trapping the fields that are empty.
Try to use this solution:
$FormData = $_POST;
if(isset($FormData['button_name'])){
$Errors = array();
foreach ($$FormData as $key => $value) {
if(empty($value)) $Errors[] = 'Some message';
if($key = 'username'){
if(filter_var($value, FILTER_VALIDATE_EMAIL){
$Errors[] = 'The email address you entered is not valid';
}
}
}
if(empty($Errors)){
// #todo Do some action
} else {
header('Location: register.php?msg=You didn\'t complete all of the required fields');
}
}
function check_email($check) {
$expression = "/^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$/";
if (preg_match($expression, $check)) {
return true;
} else {
return false;
}
}
Now use this method as :
if(!check_email($_REQUEST['ContactEmail'])){
$register_error .="Enter the correct email address!<br />";
$reg_error=1;
}

preg_matchvalidation

Okay, everything I've checked on this site referring to validation isn't what I'm looking for.
What I'm looking to do is a minimum length and maximum length of a value in firstname and secondname, this is the code which I currently have.
if (isset($_POST['submit'])) {
$errors = array();
if (isset($_POST['firstname'])) {
$fn = $_POST['firstname'];
} else {
$errors[] = "You have not entered a first name";
}
if (isset($_POST['secondname'])) {
$sn = $_POST['secondname'];
} else {
$errors[] = "You have not entered a second name";
}
I was just wondering how would I apply preg_match to those which the minimum is 4 letters and the maximum is 15?
I do know it's something to do with
if(preg_match('/^[A-Z \'.-]{4,15}$/i', $_POST['firstname']))
In doing this I tried to do
if (isset($_POST['firstname']) && preg_match('/^[A-Z \'.-]{4,15}$/i', $_POST['firstname')) {
But that also gave me an error :/
Could anyone give me a solution for this?
Thanks!
UPDATE:-
Nvm, I found a way around it. I just did this
if (isset($_POST['firstname'])) {
if (preg_match('/^[A-Z \'.-]{4,15}$/i', $_POST['firstname'])) {
$fn = $_POST['firstname'];
} else {
$errors[] = "<center> <h3> You must enter between 4 and 15 characters! </h3></center>";
}
} else {
$errors[] = "You have not entered a name";
}
For both the firstname and secondname. :)
Why don't you just use strlen() to get the string length, and then test it against your limits ?
$length = strlen($nick);
if ($length > 3 AND $length < 16) {
//Do STuff
} else {
//Do stuff for failed requirement
}
I found a way around it. I just did this
if (isset($_POST['firstname'])) {
if (preg_match('/^[A-Z \'.-]{4,15}$/i', $_POST['firstname'])) {
$fn = $_POST['firstname'];
} else {
$errors[] = "<center> <h3>You must enter between 4 and 15 characters!</h3> </center>";
}
} else {
$errors[] = "You have not entered a name";
}
For both the firstname and secondname.

Categories