PHP array not outputting properly - php

I am trying to do form validation but when I try to print out the contents of an array when there is an error it doesnt output anything.
$errors = array();
if (strlen($password) >= 6) {
array_push($errors, "Your password is not long enough! Must be over 6 characters!");
}
if(count($errors) !== 0) {
...
} else {
echo "There is errors<br/>";
foreach($errors as $er){
echo $er . "<br/>";
}
}
What I do get is "There is errors" so I know that the if else is working.

I just have to correct the argument of the if:
if(count($errors) === 0) {
// everything is okay
} else {
echo "There are errors<br/>";
foreach($errors as $er){
echo $er . "<br/>";
}
}
In this way, when your error count is 0, the content of the if is executed. When it isn't 0, the content of the else is executed and the errors are printed. It's just the opposite of what you did.
(I also corrected the sentence: it's ‘there are errors’, not ‘there is errors’ :P)
Furthermore, the other if is wrong as well, it should be the opposite:
if (strlen($password) <= 6) {
since you need to check when the password is less than 6 characters.

Shouldn't it be:
if (strlen($password) < 6) {
array_push($errors, ...);
?
BTW you should use at least constants instead of magic numbers, e.g.
define('MIN_PASSWORD_LENGTH', 6);
// ...
if (strlen($password) < MIN_PASSWORD_LENGTH) {
array_push($errors, "Your password is not long enough!"
. " Must be over ".MIN_PASSWORD_LENGTH." characters!");
}
This way, if your minimal required length changes, you just have to change it once.

Your if statement is messed up. You are checking for errors, then doing nothing, then the else is where it is displaying the errors. Try this:
if(count($errors) >0) { //there are errors
echo "There is errors<br/>";
foreach($errors as $er){
echo $er . "<br/>";
}
}else{
//there are no errors
}
Also, your password length should be <=6 not greater than or equal to if it is too short.

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.

Showing the last error first instead of first(php)

I have a login form currently setup that confuses my users.
The way i handle errors is like this;
if (!($result->total > 0)) {
$err[] = "License key is not in our system.";
}
if ($claimed == 1) {
err[] = 'License key has been claimed already.';
}
if ($userID > 0) {
$err[] = 'License key is already connected to a user.';
}
if ($banned == 1) {
$err[] = 'License key is banned';
}
so for example, if one of my users would input a invalid license key instead of showing that it is not in our system it would show banned(creating confusion). Because i'm not exiting the code and letting it run.
I'm wondering how to go on about error handling when my functions are set up like this.
update -
Forgot to show how i'm displaying the error.. my fault!
if (empty($err)) {
//no errors
} else {
echo $err; //this will show the last error instead of the first error generated
}
OK Bob,
It would be helpful if you were showing us how you are presenting your errors, as what you are explaining would suggest that your $err array would then contain two values, not just (the last) one.
However, what I think is going on here is that your $banned condition will always be met; unless you add another = to your if statement, like this:
if (!($result->total > 0)) {
$err[] = "License key is not in our system.";
}
if ($claimed == 1) {
err[] = 'License key has been claimed already.';
}
if ($userID > 0) {
$err[] = 'License key is already connected to a user.';
}
if ($banned == 1) { # <-- Here
$err[] = 'License key is banned';
}
Then for testing purposes you can view the array of errors:
if(isset($err) && !empty($err)){
print_r($err);
}
If you want to loop through each potential error:
if(isset($err) && !empty($err)){
foreach($err as $error){
echo "Error because: {$error}".PHP_EOL;
}
}
So you are adding all the errors to the array err.
To display the first item in an array, just use [0] to access the first index.
if (empty($err)) {
//no errors
} else {
echo $arr[0];
}

PHP syntax error - using elseif [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 5 years ago.
This is the code that I wrote and it's not working. it's suppose to ask the user a odd number and check is it correct.
Code:
$guess = $_POST['guess'];
$submit = $_POST['submit'];
if(isset($submit)){
if ($guess/2 %0){
echo "the number you are guessing is not odd";
}elseif{
($guess<$rand)
echo "Your Guess is Smaller than the secret number";
}elseif{
($guess>$rand)
echo "Your Guess is bigger than the secret number";
}else{
($guess==$rand)
echo "you guessed currectly. now try anouthe number!";}
else
header("Location: index.php");
exit();}
?>
Can you try this?
You placed the '()' in your elseif wrong.
<?php
$rand = rand(1, 99);
$guess = $_POST['guess'];
$submit = $_POST['submit'];
if(isset($submit))
{
if($guess / 2 % 0)
{
echo "the number you are guessing is not odd";
}
elseif($guess < $rand)
{
echo "Your Guess is Smaller than the secret number";
}
elseif($guess > $rand)
{
echo "Your Guess is bigger than the secret number";
}
elseif($guess == $rand)
{
echo "you guessed currectly. now try anouthe number!";
}
}
else
{
header("Location: index.php");
exit();
}
?>
I have not tested this code, so i need your feedback. Edit: You've confirmed this worked.
I'd like to provide you the manual about elseif:
http://php.net/manual/en/control-structures.elseif.php
Please consider easier/cleaner coding. Personally I like to use ':' instead of '{}', it's less code and easier to read when you use HTML mixed with PHP like:
<?php
$rand = rand(1, 99);
$guess = $_POST['guess'];
$submit = $_POST['submit'];
if(isset($submit)):
if($guess / 2 % 0):
echo "the number you are guessing is not odd";
elseif($guess < $rand):
echo "Your Guess is Smaller than the secret number";
elseif($guess > $rand):
echo "Your Guess is bigger than the secret number";
elseif($guess == $rand):
echo "you guessed currectly. now try anouthe number!";
else:
header("Location: index.php");
exit();
endif;
?>
And don't forget to check the $_POST data.
Same goes for array, but thats a side note:
$arr = array(1 => 'hi', 2 => 'hello'); // old
$arr = [1 => 'hi', 2 => 'hello']; // new
That's not the correct syntax for an if-else construct in php.
The elseif part needs to have a condition right after it (before the opening brace), while else doesn't expect a condition at all.
if ($guess/2 %0){
echo "the number you are guessing is not odd";
} elseif ($guess<$rand) {
// ....
} else {
echo "you guessed currectly. now try anouthe number!";
}
Of course, before your else you have to be sure that the if and elseifs match all the "wrong" cases.

PHP-How to check if the textbox contains one word or two?

Now I want to check if this text box contains one word or two, for example
if ($_POST['mytext'] == two words){
echo "That is Perfect";
} else{
echo "We don't accept this";
}
and I tried
if ($_POST['mytext'] > 1){
echo "That is Perfect";
} else{
echo "We don't accept this";
}
and it didn't work
that what I mean so how to make it?
Hope to find a way to do that.
Thanks
If you define two words as "some characters followed by one space followed by some characters" then you can do something like:
$mytext = $_POST["mytext"];
$parts = explode(" ", $mytext);
if (count($parts) !== 2) {
throw new Exception("too many or too little!");
}
if (strlen($parts[0]) === 0 || strlen($parts[1]) === 0) {
throw new Exception("not enough characters!");
}
Keep in mind that this allows a string like "# !"
Use str_word_count():
if (str_word_count($_POST['mytext']) > 1){
echo "That is Perfect";
} else{
echo "We don't accept this";
}
you could use the
`substr_count('some text', ' ');
it will return the number of space,.
try this
$text= preg_split(" ",$_POST['mytext']);
if (count($text) > 1){
echo "That is Perfect";
} else{
echo "We don't accept this";
}

Multiple conditions in PHP

I know this is embarrassing easy but I cannot get this to work right now, keep getting syntax errors, I just added in a jquery code that pre-fills in a form filed and when you select the form field it will clear the default value. The result though is if a user submits the form without changing the default value, I need to see if it exist in addition to my normal string sanitations
In this snippet below of PHP I need to run 2 conditions on $fname but below will not work, can someone help please
$fname = 'first name';
if (trim($fname) == '') && ($fname != 'first name') {
$err .= "error";
}else{
$err .= "all good";
}
For karim79
this code below from your example, exactly like this gives me this error
Fatal Error: Can't use function return value in write context on line 5
<?PHP
$fname = '';
if(empty(trim($fname))) {
echo "First name is empty";
}
?>
$fname = 'first name';
if (trim($fname) == '' || $fname != 'first name') {
$err .= "error";
} else {
$err .= "all good";
}
I would prefer to use strcmp:
if (trim($fname) == '' || strcmp($fname,'first name') !== 0) {
$err .= "error";
} else {
$err .= "all good";
}
If the case of the first name is not important, you should consider using strcasecmp instead. Also note you can use empty to test for the empty string:
$fname = '';
$fname = trim($fname);
if(empty($fname)) {
echo "First name is empty";
} else {
echo "Not empty";
}
When using empty, beware the following (from the manual):
Note: empty() only checks variables as
anything else will result in a parse
error. In other words, the following
will not work: empty(trim($name)).
$fname = 'first name';
if (trim($fname) == '' || $fname == 'first name') {
$err .= "error";
}else{
$err .= "all good";
}
PS: I assumed you want to raise an error if the string is either empty or the standard value. If that's wrong let me know.
I would NOT recommend using empty() for anything. It has some tricky return patterns, including telling you that a 0 is empty, and things of that nature. This, unfortunately, is a shortcoming of PHP.
Instead, try this algorithm (The following assumes your form POSTs):
<?php
$err = array();
// this is for sticklers..with E_STRICT on, PHP
// complains about uninitialized indexes
if( isset($_POST['name']) )
{
$name = trim($_POST['name']);
}
else
{
$name = '';
}
if( strlen($name) == 0 )
{
$err[] = "First name is required.";
}
// after validation is complete....
if( count($err) > 0 )
{
echo "There are errors!";
// probably something more elaborate here, like
// outputting an ordered list to display each error
print_r($err);
}
else
{
echo "It's all good!";
}
?>

Categories