Multiple if(strlen) with different value? - php

So I am trying to have two if(strlen) but the top one is the only one that displays even if it's the call sign error? Updated to have the full list of code.
final public function register()
{
global $core, $template, $_CONFIG;
if(isset($_POST['register']))
{
unset($template->form->error);
$template->form->setData();
$name = $template->form->reg_name;
if($this->validName($name))
{
if(!$this->nameTaken($name))
{
if(!$this->emailTaken($template->form->reg_email))
{
if(strlen($template->form->reg_password) >= 8)
{
if(strlen($template->form->reg_callsign) > 2)
{
if(!$this->callTaken($template->form->reg_callsign))
{
if($this->isBanned($_SEVER['REMOTE_ADDR']) == false)
{
if($template->form->reg_email == $template->form->reg_rep_email)
{
if($this->validEmail($template->form->reg_email))
{
$this->addUser($name, $core->hashed($template->form->reg_password), $template->form->reg_email, $template->form->reg_callsign, 1, $core->hashed);
$this->turnOn($name);
header('Location: ' . $_CONFIG['game']['url'] . '/application');
exit;
}
else
{
$template->form->error = 'Oops, email seems to be invalid.';
return;
}
}
else
{
$template->form->error = 'Email & repeated email doesn\'t match.';
return;
}
}
else
{
$template->form->error = 'Sorry, it appears you are banned.<br />';
$template->form->error .= 'Reason: ' . $this->getReason($_SERVER['REMOTE_ADDR']);
return;
}
}
else
{
$template->form->error = 'That call sign is already taken!';
return;
}
}
else
{
$template->form->error = 'Your call sign must be 3 digits.';
return;
}
}
else
{
$template->form->error = 'Make sure your password has 8 characters or more.';
return;
}
}
else
{
$template->form->error = 'Oops, this email is already registered.';
return;
}
}
else
{
$template->form->error = 'Oops, this name:<b>' . $name . '</b> is taken.';
return;
}
}
else
{
$template->form->error = 'Oops, this name is invalid.';
return;
}
}
}
What I would like to happen is where if(strlen($template->form->reg_password) >= 8) (error message) would only show up if the password is shorter than 8 and the if(strlen($template->form->reg_callsign) > 2) (error message) to show up if they are only putting 1-2 numbers and not 3

Related

PHP bug while validating user name

I'm building a website using PHP and I need to validate whether the name entered by the user is correct or not. Since JavaScript is client-side, I cannot completely rely on that, so here's my server-side function to validate the name of the user:
function validate_name($name) {
$name = trim($name); // only for the purpose of debugging <---- edited comment
echo $name;
if (strlen($name) <= 1) {
return "small";
} else if (has_numbers($name)) {
return "numbers";
} else {
return true;
}
}
After this, I check the input and display result accordingly:
function final_check() {
if (validate_name($_POST["first_name"]) == "small") {
echo "<span class='error'>Your first name cannot be empty</span>";
return false;
} else if (validate_name($_POST["first_name"]) == "numbers") {
echo "<span class='error'>Numbers are not allowed in your first name</span>";
return false;
}
return true;
}
When I enter nothing in the first_name field, I get the empty error message; when I enter numbers, I get the numbers error message. However, when I do enter a valid name, it gives me the name empty error message.
Here's the post data:
Array
(
[email] => ewf#gmail.com
[first_name] => qwe
[last_name] => wqe
[password] => qwe
[re_password] => qwe
[gender] => Male
)
Output:
Your first name cannot be empty
Any idea what I am doing wrong? I have been stumped for the past hour trying to fix this and I haven't been able to find a solution.
Array
(
[email] => ewf#gmail.com
[first_name] => qwe
[last_name] => wqe
[password] => qwe
[re_password] => qwe
[gender] => Male
)
// First_name length = 3
function validate_name($name) {
$name = trim($name);
echo $name;
if (strlen($name) <= 1) {
return "small";
} else if (has_numbers($name)) {
return "numbers";
} else {
return true; // satisfy this case return true
}
}
and here it's becoming like
function final_check() {
if (validate_name($_POST["first_name"]) == "small") { // if(1 == 'small')
echo "<span class='error'>Your first name cannot be empty</span>";
return false;
} else if (validate_name($_POST["first_name"]) == "numbers") {
echo "<span class='error'>Numbers are not allowed in your first name</span>";
return false;
}
return true;
}
if(1 == 'small') its a string comparison with Boolean which always going to return true.
Please check this page in the manual to understand the problem.
Your logic is correct, however, as other questions pointed out, string with boolean comparison will return true.
To fix this, you should use === instead of == and all should be fine
What I suggest here is to modify your validate_name function, so that it will have only one return type, since it can currently return either a string or a boolean, which is not a good practice.
For instance you can do something like :
function validate_name($name) {
$name = trim($name);
echo $name;
if (strlen($name) <= 1) {
return "small";
} else if (has_numbers($name)) {
return "numbers";
} else {
return "ok"; // or return ""; or whatever string you want.
}
}
Moreover to optimize your code and improve readability, you can change your final_check function so that there will be only one call to validate_name using a intermediate variabe.
function final_check() {
$valid = validate_name($_POST["first_name"]);
if ($valid == "small") {
echo "<span class='error'>Your first name cannot be empty</span>";
return false;
} else if ($valid == "numbers") {
echo "<span class='error'>Numbers are not allowed in your first name</span>";
return false;
}
return true;
}
try with
if (validate_name($_POST["first_name"]) == "small" && !validate_name($_POST["first_name"])) {
echo "<span class='error'>Your first name cannot be empty</span>";
return false;
} else if (validate_name($_POST["first_name"]) == "numbers" && validate_name($_POST["first_name"])) {
echo "<span class='error'>Numbers are not allowed in your first name</span>";
return false;
}
true == 'small' will also return true
or try with === will strictly match the values
if (validate_name($_POST["first_name"]) === "small") {
echo "<span class='error'>Your first name cannot be empty</span>";
return false;
} else if (validate_name($_POST["first_name"]) === "numbers"=) {
echo "<span class='error'>Numbers are not allowed in your first name</span>";
return false;
}
I think you have to change only final_check() function
function final_check() {
if(validate_name($_POST["first_name"])){
return true;
}else{
if (validate_name($_POST["first_name"]) == "small") {
echo "<span class='error'>Your first name cannot be empty</span>";
return false;
} else if (validate_name($_POST["first_name"]) == "numbers") {
echo "<span class='error'>Numbers are not allowed in your first name</span>";
return false;
}
}
}

PHP class method call not displaying all errors

<?php
class Validator {
public $errors = array(
'password' => '',
'email' => '');
const PASSWORD_MINCHARS = 8;
public function checkEmail($email) {
if ($this->checkEmpty($email)) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->errors['email'] = "Please provide a valid email";
return FALSE;
} else {
return TRUE;
}
} else {
$this->errors['email'] = "Please provide a value for the email";
return FALSE;
}
}
public function checkPassword($string) {
if ($this->checkEmpty($string)) {
if (strlen($string) < self::PASSWORD_MINCHARS) {
$this->errors['password'] = "The password should be atleast ".self::PASSWORD_MINCHARS." characters long.";
return FALSE;
} else {
return TRUE;
}
} else {
$this->errors['password'] = "Please provide a value for the password";
return FALSE;
}
}
private function checkEmpty($string) {
if (!empty($string)) {
return TRUE;
}
return FALSE;
}
public function displayErrors() {
$output = '';
foreach ($this->errors as $error) {
if (!empty($error)) {
$output .= '<p>'.$error.'</p>';
}
}
return $output;
}
}
?>
<?php
require 'Validator.php';
$validator = new Validator();
$email = '';
$password = '';
if ($validator->checkPassword($password) && $validator->checkEmail($email)) {
echo 'You have entered a valid password and email.';
} else {
echo $validator->displayErrors();
}
?>
The above code comes from two separate files. The one that comes begins with class Validator comes from Validator.php while the one that begins with the require function comes from index.php. So am just wondering why the method call that is $validator->displayErrors() in index.php only displays one error at a time instead of displaying them all at once.
There is only one error displayed because of your condition:
if ($validator->checkPassword($password) && $validator->checkEmail($email))
It executes your checkPassword method first, it returns false and so the second condition (which should execute the second validation method) is never checked.
You can avoid this by executing the validation methods first:
$validPassword = $validator->checkPassword($password);
$validEmail = $validator->checkEmail($email);
if ($validPassword && $validEmail) {
echo 'You have entered a valid password and email.';
} else {
echo $validator->displayErrors();
}
Replace
if ($validator->checkPassword($password) && $validator->checkEmail($email))
with
if ($validator->checkPassword($password) || $validator->checkEmail($email)) {

Instances of objects in a class

I have a form building a processing class that I have developed to handle any and all form processing on a page.
I am running into a problem when I have mulitple forms on a page I am building each form with an instance of the class:
$form2 = new newForm('submitform2', 'post.contact.php', '100%');
$form2->setHandler('#canWe');
$form2->html('<div class="half">');
$form2->addText('name', 'Name:');
$form2->html('</div>');
$form2->html('<div class="halfNoMarg">');
$form2->addEmail('email_address', 'E-Mail Address:');
$form2->html('</div>');
$form2->html('<div class="half">');
$form2->addUrl('website', 'Website URL:');
$form2->html('</div>');
$form2->html('<div class="halfNoMarg">');
$form2->addText('phone', 'Phone Number:');
$form2->html('</div>');
$form2->addTextArea('about_business', 'Tell Us About Your Business:');
$form2->addSubmitButton('Find Out Now!');
$form2->getPost();
$form2->outputForm();
AND
$form = new newForm('submitform', 'post.contact.php', '100%');
$form->addText('name', 'Name:');
$form->addEmail('email_address', 'E-Mail Address:');
$form->addUrl('website', 'Website URL:');
$form->addText('phone', 'Phone Number:');
$form->addTextArea('about_business', 'Tell Us About Your Business:');
$form->addSubmitButton('Find Out Now!');
$form->getPost();
$form->outputForm();
When the class processes the form and spits out the errors for the missing fields etc. each of the forms displays the errors and not just the form object that is being processed.
Basically the output is affecting each instance of the class and not just the one being processed.
I can include the class file if anyone needs it to help out (its 650 lines so didn't want to include in the post).
Thanks in advance for any help provided.
~M
EDIT ADDING IN THE POST FUNCTION
//get the post data and return a cleaned array of information if the post passes the pre check
public function getPost()
{
//if post tests all passed then lets create the array of elements and load the processing file.
if ($this->checkPost() === true) {
$cleanedPost = $this->cleanPost;
//get the post processing file
if (file_exists($this->processFile)) {
require_once($this->processFile);
//$this->postMessage($this->successMessage, 'confirm');
} else {
$this->postMessage('Processing File Not Found:<em>' . $this->processFile . '</em>', 'error');
}
return $this->cleanPost;
} else {
return false;
}
}
//output the form to the screen
public function outputForm()
{
//echo spl_object_hash($this);
if($this->handler !== null){
$this->handler = 'action="'.$this->handler.'"';
}
$return = '<form id="' . $this->formName . '" method="' . $this->method . '"'. $this->handler .' enctype="multipart/form-data" style="width:' . $this->width . '" >';
if(!empty($this->message)){
$return .= '<div class="errorMessage">' . $this->message . '</div>';
}
$return .= $this->output;
$return .= '</form>';
echo $return;
}
more post handling code
//check post before we handle it
public function checkPost()
{
//go through the entire post and process information as needed
if (!empty($_POST)) {
foreach ($this->postCheck AS $postVar => $item) {
if (is_array($item)) {
//addItemTo cleanPost
if(isset($_POST[$postVar])){
$this->addToCleanedPost($postVar, $_POST[$postVar]);
}else{
$this->cleanPost[$postVar] = null;
}
switch ($item['type']) {
//validate emails
case 'email':
//check valid email
if (isset($this->cleanPost[$postVar]) && !$this->validEmail($this->cleanPost[$postVar])) {
$this->postMessage('Email Address is invalid');
}
break;
//validate and verify password
case 'password':
if ($item['verify'] === true) {
//validate password against other
if (!$this->verifyPassword($this->cleanPost['password'], $this->cleanPost['password2'])) {
$this->postMessage('Passwords do not match');
}
} else {
if (empty($this->cleanPost[$postVar]) && $item['req'] === 1) {
$this->postMessage($postVar . ': Please enter a password');
}
}
break;
//validate checkboxes
case 'checkbox':
if ($item['req'] === 1 && $this->validateCheckBox($postVar) === 0) {
$this->postMessage($postVar . ' must be checked');
} else {
$this->cleanPost[$postVar] = $this->validateCheckBox($postVar);
}
break;
//handle url
case 'url':
//first we need to handle making the url format properly
if(isset($this->cleanPost[$postVar])){
$url = $this->validUrl($this->cleanPost[$postVar]);
//now we do the final checking of the url and make sure it is a valid url before we move forwards
if ($item['req'] === 1 && $url === null) {
$this->postMessage($postVar . ' must be a valid URL');
}else{
$this->cleanPost[$postVar] = $url;
}
}
break;
//handle text and text areas
case 'text':
case 'textarea':
if (isset($_POST[$postVar])) {
//check for a bypass on the min required characters
if (isset($item['bypass']) && $item['bypass'] === true || $this->minBypass === true) {
$bypassMinCheck = true;
} else {
$bypassMinCheck = false;
}
//process the item
if ($item['req'] === 1 && $bypassMinCheck === false && strlen($this->cleanPost[$postVar]) < 2) {
$this->postMessage($postVar . ' is too short');
} else {
if (!empty($this->cleanPost[$postVar]) && $bypassMinCheck === false) {
if (strlen($_POST[$postVar]) < 2) {
$this->postMessage($postVar . ' is too short');
}
}
}
}
break;
//handle other inputs
default:
if (empty($_POST[$postVar]) && $item['req'] === 1) {
$this->postMessage($postVar . ' cannot be left empty');
}
break;
}
}
}
} else {
return false;
}
//return the success or failure of the prepost test
if (empty($this->message)) {
return true;
} else {
return false;
}
}

PHP if statement errmsg

I have this if statment
if(!empty($URL) && ($safe===true)){
//lots of code
}
Is it possible to show different error messages depending on what condition failed?
For example if $URL is empty echo "URL empty";
and if $safe===false echo "GTFO";
Just add this to your code
else if(empty($URL)
{
echo "url empty";
}
else if($safe===false)
echo "Get Out"; // be polite ;)
if (empty($url))
{
echo "URL empty";
}
elseif ($safe === false)
{
echo "GTFO";
}
else
{
//lots of code
}
} else {
if($safe === false){
die("GTFO");
}
if (empty($url)){
echo "URL Empty.";
}
}
Yes; you could make use of an else if statement.
if (!empty($URL) && ($safe===true)) {
//lots of code
} else if (empty($URL)) {
// report that url is empty
} else if ($safe === false) {
// report that safe is false
}
Alternatively, you could just use an else statement to report that the if condition was false.
I propose the following solution. It will allow you to show multiple errors and set each condition only once (instead of having so many conditions and anti-conditions as other solutions proposed).
$errors = array();
if(empty($URL) {
$errors[] = 'URL empty';
}
if($safe !== true) {
$errors[] = 'GTFO';
}
if(empty($errors)) {
//lots of code
} else {
echo '<ul>';
foreach($errors as $error_message) {
echo '<li>' . $error_message . '</li>';
}
echo '</ul>';
}

Email validation, Am I doing the right thing?

I am writing some PHP code where I end it with a email validation checking. Can someone review it and confirm if it's a good solution?
<?php
function isTrue($var) {
return (isset($var)) ? TRUE : FALSE;
}
function len($str) {
$i;
for($i=0; isTrue($str[$i]); $i++) {
/* count me */
}
return $i;
}
function parsMe($str) {
$at; $dot; $isvalid=0; $isnotvalid=0;
for ( $at=0; isTrue($str[$at]); $at++) {
if ( $str[$at] == "#" ) {
for ( $dot=$at+1; isTrue($str[$dot]); $dot++ ) {
if ( $str[$dot] == "." ) $isvalid += 1;
if ( $str[$dot] =="#" || $str[len($str)-1] == "#" || $str[len($str)-1] == "." ) {
die("Error email entered");
}
}
}
if ( $str[$at] != "#" ) {
$isnotvalid+=1;
}
}
/* exit cond */
if ( $isnotvalid == len($str) ) die("Error mail usage");
else if ( $isvalid == 0 ) die("Error mail");
else echo "Mail is OK ";
}
$eml = "dotdot#com.";
parsMe($eml);
?>
parsMe() should produce error.
There are built in functions for checking validity of emails:
<?php
$email ='dotdot#com';
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
echo "E-mail is not valid";
}else{
echo "E-mail is valid";
}
?>

Categories