Instances of objects in a class - php

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;
}
}

Related

Multiple if(strlen) with different value?

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

How do I let an error-message only appear after the $_POSTS are sent?

On a blog I'm coding the admin can edit existing posts.
I want to let an error-message appear when the $_POST['title'] for e.g is empty(There will be displayed:"Your post should have a title"). I also do it if the subheading, content or category are empty.
The errors work just fine if one or some of them is/are empty. As soon I load the page to edit a post every error is displayed from the beginning.
How do I make them only appear when one or some $_POST's are empty after the <input type="submit .../> is clicked (they shouldn't be there when the site has loaded)?
This is the function in the PostsAdminController.php that checks the $_POST's and renders the site:
public function edit()
{
$error = "";
$id = $_GET['id'];
$entry = $this->postsRepository->find($id);
$categoryFId = $this->categoryRepository->getOneCatFromId($entry->c_Id);
$savedSuccess = false;
$abort = false;
if ($this->loginService->check()) {
if (!empty($_POST['title'])) {
$entry->title = $_POST['title'];
} else {
$error .= "Your post should have a title.";
$abort = true;
}
if (!empty($_POST['subheading'])) {
$entry->subheading = $_POST['subheading'];
} else {
$error .= "A good subheading is nothing you should just leave out.";
$abort = true;
}
if (!empty($_POST['content'])) {
$entry->content = $_POST['content'];
} else {
$error .= "Your post should have content, you know, it wouldn't be a 'post' then.";
$abort = true;
}
if (!empty($_POST['category'])) {
$entry->c_Id = $_POST['category'];
}
if ($abort == false){
$this->postsRepository->update($entry);
$savedSuccess = true;
}
} else {
$error = "You have no permission to do this, how the hell did you get here?";
}
$this->render("post/admin/edit", [
'entry' => $entry,
'error' => $error,
'savedSuccess' => $savedSuccess,
'categoryFId' => $categoryFId
]);
}
I really hope someone can help me with this, I don't know what I could to to let them only disappear when the POSTS have already been send..
You have to check if there was a POST action use:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
in your case
...
if ($this->loginService->check()) {
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!empty($_POST['title'])) {
...
}
}
}

Unexpected results when trying to return data from an AJAX call

I have the following script that sends an image, directory name, and possible alternative filename to an action url in a php file.
$(document).ready(function() {
$(".layout-save").click(function(e) {
e.preventDefault();
var form = $(".image_define");
var params = form.serializeArray();
var formData = new FormData();
formData.append('default_image', $('#default_image')[0].files[0]);
$(params).each(function (index, element) {
formData.append(element.name, element.value);
});
$.ajax({
url: form.attr('action'),
method: "post",
data: formData,
contentType: false,
processData: false
})
.done(function(data) {
var obj = JSON.parse(data);
$('.tooltip-imageHandler-<?php echo $products_filter; ?>').tooltipster('close');
var elem = $('.image-<?php echo $products_filter; ?>');
elem.fadeOut('slow', function() {
elem.html(obj.asHtml).fadeIn('slow', function() {
elem.delay(1200).fadeOut('slow', function() {
elem.html(obj.products_image).fadeIn('slow');
});
});
});
})
.fail(function(){
alert('Ajax Submit for New Image Save Failed ...');
});
});
});
What I was trying to achieve was to send back a success message that I can display in the class image-xxx, where xxx is a product id, thus giving unique class names when there are multiple instances on the page.
File upload is working ok, and the tooltip closes correctly. I added the following line of code inside my "save" case, just after the final sql query that updates the database:
echo json_encode(array("products_image"=>$data['defaultFileName'], "asHtml" => '<div class="alert alert-info update-notice update-'.$products_filter.'"><strong>Product image updated</strong></div>'));
I was expecting to be able to use this to display the success message, and then update the div with the newly uploaded image.
However, when testing I am getting the following in the console
"VM3150:2 Uncaught SyntaxError: Unexpected token < in JSON at position 162"
and if I console.log(data) I am seeing the parsed php for the page rather than just "products_image" and "asHtml".
Can anyone offer some pointers as to what I've done wrong here?
Note: Whilst I know I could take the data that was submitted via the form, I really need the information after it has been processed because it makes decisions on the file path and image naming etc depending on if it is a first, or additional image before it writes to the database.
Added the php from the file where if ($action == 'save') is located. The json_encode is approx 12 lines before the end, right after the original (pre ajax modification)success message would be displayed.
if ($action == 'save') {
// -----
// Log the input values on entry, if debug is enabled.
//
$ih_admin->debugLog(
'ih_manager/save, on entry.' . PHP_EOL .
'$_GET:' . PHP_EOL . var_export($_GET, true) . PHP_EOL .
'$_POST:' . PHP_EOL . var_export($_POST, true) . PHP_EOL .
'$_FILES:' . PHP_EOL . var_export($_FILES, true)
);
// -----
// Set some processing flags, based on the type of upload being performed.
//
$editing = (isset($_GET['imgEdit']) && $_GET['imgEdit'] == '1');
$new_image = (isset($_GET['newImg']) && $_GET['newImg'] == '1');
$main_image = (!isset($_GET['imgSuffix']) || $_GET['imgSuffix'] == '');
$keep_name = (isset($_POST['imgNaming']) && $_POST['imgNaming'] == 'keep_name');
$data = array();
$data_ok = true;
// -----
// Determine the extension required for any uploaded images.
//
// 1) A new main-image (and any medium/large) use the extension from the (required) default image suppied.
// 2) A new additional image's files use the extension from the pre-existing main-image.
// 3) Editing an image uses the pre-existing file extension.
//
if ($new_image) {
if ($_FILES['default_image']['name'] == '') {
$messageStack->add(TEXT_MSG_NO_DEFAULT, 'error');
$data_ok = false;
} else {
$data['imgExtension'] = '.' . pathinfo($_FILES['default_image']['name'], PATHINFO_EXTENSION);
}
} else {
$data['imgExtension'] = $_GET['imgExtension'];
}
// -----
// If the file-upload is in support of a new main image or the main image is being edited ...
//
if ($new_image || ($editing && $main_image && !$keep_name && $_FILES['default_image']['name'] != '')) {
// New Image Name and Base Dir
if (isset($_POST['imgBase']) && $_POST['imgBase'] != '') {
$data['imgBase'] = $_POST['imgBase'];
} else {
// Extract the name from the default file
if ($_FILES['default_image']['name'] != '') {
$data['imgBase'] = pathinfo($_FILES['default_image']['name'], PATHINFO_FILENAME);
} else {
$messageStack->add(TEXT_MSG_AUTO_BASE_ERROR, 'error');
$data_ok = false;
}
}
// catch nasty characters
if (strpos($data['imgBase'], '+') !== false) {
$data['imgBase'] = str_replace('+', '-', $data['imgBase']);
$messageStack->add(TEXT_MSG_AUTO_REPLACE . $data['imgBase'], 'warning');
}
if (isset($_POST['imgNewBaseDir']) && $_POST['imgNewBaseDir'] != '') {
$data['imgBaseDir'] = $_POST['imgNewBaseDir'];
} elseif (isset($_POST['imgBaseDir'])) {
$data['imgBaseDir'] = $_POST['imgBaseDir'];
} else {
$data['imgBaseDir'] = $_GET['imgBaseDir'];
}
$data['imgSuffix'] = '';
// -----
// Otherwise, if we're editing an additional product image ...
//
} elseif ($editing) {
$data['imgBaseDir'] = $_GET['imgBaseDir'];
$data['imgBase'] = $_GET['imgBase'];
$data['imgSuffix'] = $_GET['imgSuffix'];
// -----
// Otherwise, we're adding an additional product image ...
//
} else {
// An additional image is being added
$data['imgBaseDir'] = $_GET['imgBaseDir'];
$data['imgBase'] = $_GET['imgBase'];
// Image Suffix (if set)
if ($_POST['imgSuffix'] != '') {
$data['imgSuffix'] = '_' . $_POST['imgSuffix'];
} else {
// -----
// Get additional images' list; the class function takes care of sorting the files
//
$matching_files = array();
$ih_admin->findAdditionalImages($matching_files, $data['imgBaseDir'], $data['imgExtension'], $data['imgBase']);
// -----
// If no additional images exist, use the _01 suffix.
//
$file_count = count($matching_files);
if ($file_count == 1) {
$data['imgSuffix'] = '_01';
} else {
// -----
// Otherwise, find the first unused suffix in the range _01 to _99. Note that the first
// (ignored) element of the find-array "should be" the main image's name!
//
for ($suffix = 1, $found = false; $suffix < 99; $suffix++) {
$suffix_string = sprintf('_%02u', $suffix);
if (!in_array($data['imgBase'] . $suffix_string . $data['imgExtension'], $matching_files)) {
$found = true;
$data['imgSuffix'] = $suffix_string;
break;
}
}
if (!$found) {
$messageStack->add('Could not find an unused additional-image suffix in the range _01 to _99.', 'error');
$data_ok = false;
}
}
}
}
// determine the filenames
if ($data_ok) {
// add slash to base dir
if ($data['imgBaseDir'] != '') {
if (substr($data['imgBaseDir'], -1) != '/' && substr($data['imgBaseDir'], -1) != '\\') {
$data['imgBaseDir'] .= '/';
}
}
$data['defaultFileName'] = $data['imgBaseDir'] . $data['imgBase'] . $data['imgSuffix'] . $data['imgExtension'];
// Check if the file already exists
if ($editing && file_exists(DIR_FS_CATALOG . DIR_WS_IMAGES . $data['defaultFileName'])) {
$messageStack->add(TEXT_MSG_FILE_EXISTS, 'error' );
$data_ok = false;
}
}
// -----
// If no previous errors and we're either (a) creating a new main-image or (b) editing the main-image and a new name
// is requested ...
//
if ($data_ok && $new_image || ($editing && $main_image && !$keep_name && $_FILES['default_image']['name'] != '')) {
// -----
// ... first, check to see that the image's name is going to fit into the database field.
//
if (strlen($data['defaultFileName']) > zen_field_length(TABLE_PRODUCTS, 'products_image')) {
$messageStack->add(sprintf(TEXT_MSG_NAME_TOO_LONG_ERROR, $data['defaultFileName'], zen_field_length(TABLE_PRODUCTS, 'products_image')), 'error');
$data_ok = false;
} else {
// update the database
$sql =
"UPDATE " . TABLE_PRODUCTS . "
SET products_image = '" . $data['defaultFileName'] . "'
WHERE products_id = " . (int)$products_filter . "
LIMIT 1";
if (!$db->Execute($sql)) {
$messageStack->add(TEXT_MSG_INVALID_SQL, "error");
$data_ok = false;
}
}
}
if ($data_ok) {
// check for destination directory and create, if they don't exist!
// Then move uploaded file to its new destination
// default image
if ($_FILES['default_image']['name'] != '') {
io_makeFileDir(DIR_FS_CATALOG_IMAGES . $data['defaultFileName']);
$source_name = $_FILES['default_image']['tmp_name'];
$destination_name = DIR_FS_CATALOG_IMAGES . $data['defaultFileName'];
if (!move_uploaded_file($source_name, $destination_name)) {
$messageStack->add(TEXT_MSG_NOUPLOAD_DEFAULT, "error" );
$data_ok = false;
}
} elseif ($_FILES['default_image']['name'] == '' && !$editing) {
// Nigel Hack for special idiots
io_makeFileDir(DIR_FS_CATALOG_IMAGES.$data['defaultFileName']);
$source_name = $_FILES['default_image']['tmp_name'];
$destination_name = DIR_FS_CATALOG_IMAGES . $data['defaultFileName'];
if (!move_uploaded_file($source_name, $destination_name) ) {
$messageStack->add( 'you must select a default image', "error" );
$data_ok = false;
$_FILES['medium_image']['name'] = $_FILES['large_image']['name'] = '';
}
} // End special idiots hack
// medium image
if ($_FILES['medium_image']['name'] != '') {
$data['mediumImgExtension'] = substr( $_FILES['medium_image']['name'], strrpos($_FILES['medium_image']['name'], '.'));
$data['mediumFileName'] ='medium/' . $data['imgBaseDir'] . $data['imgBase'] . $data['imgSuffix'] . IMAGE_SUFFIX_MEDIUM . $data['mediumImgExtension'];
io_makeFileDir(DIR_FS_CATALOG_IMAGES.$data['mediumFileName']);
$source_name = $_FILES['medium_image']['tmp_name'];
$destination_name = DIR_FS_CATALOG_IMAGES . $data['mediumFileName'];
if (!move_uploaded_file($source_name, $destination_name)) {
$messageStack->add( TEXT_MSG_NOUPLOAD_MEDIUM, "error" );
$data_ok = false;
}
}
// large image
if ($_FILES['large_image']['name'] != '') {
$data['largeImgExtension'] = substr( $_FILES['large_image']['name'], strrpos($_FILES['large_image']['name'], '.'));
$data['largeFileName'] = 'large/' . $data['imgBaseDir'] . $data['imgBase'] . $data['imgSuffix'] . IMAGE_SUFFIX_LARGE . $data['largeImgExtension'];
io_makeFileDir(DIR_FS_CATALOG_IMAGES.$data['largeFileName']);
$source_name = $_FILES['large_image']['tmp_name'];
$destination_name = DIR_FS_CATALOG_IMAGES . $data['largeFileName'];
if (!move_uploaded_file($source_name, $destination_name)) {
$messageStack->add( TEXT_MSG_NOUPLOAD_LARGE, "error" );
$data_ok = false;
}
}
}
if (!$data_ok) {
if ($editing) {
$action = "layout_edit";
} else {
$action = "layout_new";
}
} else {
// Data has been saved
// show the new image information
$messageStack->add(TEXT_MSG_IMAGE_SAVED, 'success');
echo json_encode(array("products_image"=>$data['defaultFileName'], "asHtml" => '<div class="alert alert-info update-notice update-'.$products_filter.'"><strong>Product image updated</strong></div>'));
// we might need to clear the cache if filenames are kept
if ($editing) {
$error = bmz_clear_cache();
if (!$error) {
$messageStack->add(IH_CACHE_CLEARED, 'success');
}
}
$_GET['imgName'] = $data['imgBase'] . $data['imgSuffix'];
$action = "layout_info";
}
}
One point I would make is that when looking at console log in dev tools, it is highlighting the first character of the file the form resides in, which IS NOT the file that the json_encode is in. Code structure has the form in file A, which is actioned in file B. File B contains the json_encode response I want to send, but the error is showing the html content of file A, as well as the son data. A snippet of it is here.
{"products_image":"Teal-Shirt-min_01.jpg","asHtml":"<div class=\"alert alert-info update-notice update-310\"><strong>Product image updated<\/strong><\/div>"}
<div class="container-fluid">
<div id="ih-head">
<h1>Image Handler<sup>5</sup></h1>
</div>
<div id="defaultContent">
<div class="row">
<div class="col-md-6 col-sm-12 no-padding">
<div class="ih-heading pull-left">Product</div>
<div class="ih-info pull-left"> #310 — Teal T-Shrt</div>
</div>
<div class="col-md-6 col-sm-12 no-padding">
<div class="ih-heading pull-left">Image Directory</div>
<div class="ih-info pull-left"> images/</div>
</div>
</div>
<hr>
Given you are getting back the contents of the current page, my guess is that your ajax request is NOT setup right.
"url" should be set to the url of the script that you want to process the data and return the response. If "url" is not set it defaults to the "CURRENT URL".
So I am thinking you want something like below for your URL...
.ajax({
url: "/myapp/myJsonResponseScript.php",
....
Pass your action value in a data option for the ajax call.

complete form validation in php

I have this php code associated with a database and I need here to make a complete email and name validation
based on this code how can I do that because my code has some issues here
1)name key doesn't have (//) or any symbols to be a correct name
2)email key is valid email because what we did here just make ensure that there is # symbol and if I type the email hhhh#hhh.com or even without( .com ) it will be valid also ?!!
if(array_key_exists("submit",$_POST)){
$link = mysqli_connect("localhost","root","123456789","users");
if(mysqli_connect_error()){
die("There is a problem in connecting to database");
}
if(!$_POST['name']){
$error .="<p>Your Full name is required</p><br>";
}
if(!$_POST['email']){
$error .="<p>Your email address is required</p><br>";
}
if(!$_POST['password']){
$error .="<p>Your password is required</p><br>";
}
if($error !=""){
$error = "<p>There were errors in your form</p><br>".$error;
}
}
You can use this function for the validation:
function filtervariable($string,$type,$method) {
//function for sanitizing variables using PHPs built-in filter methods
$validEmail = false;
if ($method == 'sanitize') {
$filtermethod = 'FILTER_SANITIZE_';
} elseif ($method == 'validate') {
$filtermethod = 'FILTER_VALIDATE_';
} else {
return;
}
switch ($type) {
case 'email':
case 'string':
case 'number_int':
case 'int':
case 'special_chars':
case 'url':
$filtertype = $filtermethod.strtoupper($type);
break;
}
if ($filtertype == 'FILTER_VALIDATE_EMAIL' && !empty($string)) {
list($local,$domain) = explode('#',$string);
$localLength = strlen($local);
$domainLength = strlen($domain);
$checkLocal = explode('.',$domain);
if (($localLength > 0 && $localLength < 65) && ($domainLength > 3 && $domainLength < 256) && (checkdnsrr($domain,'MX') || checkdnsrr($domain,'A') || ($checkLocal[1] == 'loc' || $checkLocal[1] == 'dev' || $checkLocal[1] == 'srv'))) { // check for "loc, dev, srv" added to cater for specific problems with local setups
$validEmail = true;
} else {
$validEmail = false;
}
}
if (($filtertype == 'FILTER_VALIDATE_EMAIL' && $validEmail) || $filtertype != 'FILTER_VALIDATE_EMAIL') {
return filter_var($string, constant($filtertype));
} else {
return false;
}
}
And use it like this:
$email = filtervariable($registeremail,'email','validate');
It will return "true" on success and "false" on failure.

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)) {

Categories