complete form validation in php - 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.

Related

How to make a 2nd check after first row of validations

I have am trying to re-create a form register validation that I seen a few weeks ago but unable to figure it out.
I want to perform one last check after the first 3 checks then display the message
validation code
public function validateSignup(): bool
{
$this->errors = [];
if (empty($this->name) || (strlen($this->name) < 4)) {
$this->errors['name'] = "Username must be at least 4 characters.";
}
if (empty($this->email) || (filter_var($this->email, FILTER_VALIDATE_EMAIL) === false)) {
$this->errors['email'] = "Email address is required.";
}
if (empty($this->password) || strlen($this->password) < 6) {
$this->errors['password'] = "Password is required.";
}
return empty($this->errors);
}
This works great for the validation requirements but I want to add another step, to check if email or username is taken, I know how to do this traditionally but wanted to make it different without giving information away.
I have a Helper to tell me if an email is in the database called alreadyExists
what I am trying to accomplish is a 2nd check after that
Example
public function validateSignup(): bool
{
$this->errors = [];
if (empty($this->name) || (strlen($this->name) < 4)) {
$this->errors['name'] = "Username must be at least 4 characters.";
}
if (empty($this->email) || (filter_var($this->email, FILTER_VALIDATE_EMAIL) === false)) {
$this->errors['email'] = "Email address is required.";
}
if (empty($this->password) || strlen($this->password) < 6) {
$this->errors['password'] = "Password is required.";
}
return empty($this->errors);
## after it checks validation with no errors check if already exists
if ($this->name) Helpers::alreadyExists("user", "name", $this->name) {
$this->errors['name'] = "Unable to register user with provided data.";
}
return $this->errors;
}
public function validateSignup(): bool {
$this->errors = [];
if (empty($this->name) || (strlen($this->name) < 4)) {
$this->errors['name'] = "Username must be at least 4 characters.";
}
if (empty($this->email) || (filter_var($this->email, FILTER_VALIDATE_EMAIL) === false)) {
$this->errors['email'] = "Email address is required.";
}
if (empty($this->password) || strlen($this->password) < 6) {
$this->errors['password'] = "Password is required.";
}
If(count($this->errors) > 0) {
return empty($this->errors);
}
## after it checks validation with no errors check if already exists
if ($this->name) Helpers::alreadyExists("user", "name", $this->name) {
$this->errors['name'] = "Unable to register user with provided data.";
}
return empty($this->errors);
}

PHP Elseif always returning false, multiple conditions

I'm trying to make an helper php-function that's going to return true/false if the user got right access level. The access level is set when the user logs in. The problem is that the function always return false. The function is located in a "class" php-file that's included(with include_once) on the page I want to use it.
I'm kinda new to php, but the if conditions seems to be right.
I have tested to log in as admin and "economy", but it doesn't return true.
I also have tried to echoing the value that is sent as an parameter and even checking that the access level is right(by echoing the value) before the elseif statement.
const AccessLevelUser = 0;
const AccessLevelAdmin = 1;
const AccessLevelManager = 2;
const AccessLevelEconomy = 3;
public static function hasAccessLevel($requiredAccess) {
//file_put_contents('logg.txt', $logg);
if( !isset($_SESSION['accesslevel']) ) {
header("location:index.php?location=login");
exit;
}elseif ( $requiredAccess == AccessLevelAdmin && $_SESSION['accesslevel'] == AccessLevelAdmin ) {
echo "Admin True";
return true;
}elseif( $requiredAccess == AccessLevelEconomy && ($_SESSION['accesslevel'] == 3 || $_SESSION['accesslevel'] == 1) ) {
echo "Economy True";
return true;
}elseif( $requiredAccess == AccessLevelManager && ($_SESSION['accesslevel'] == 2 || $_SESSION['accesslevel'] == 1) ) {
echo "Manager True";
return true;
}elseif( $requiredAccess == AccessLevelUser && ($_SESSION['accesslevel'] == 0 || $_SESSION['accesslevel'] == 1) ) {
echo "User True";
return true;
}else{
echo "FALSE!";
return false;
}
}

Prestashop remove one checkout step

I'm new to prestashop and I'm having major trouble removing the address(I want to have only Summary=Shrnutí, Login/Guest Checkout=Přihlásit se, Delivery=Doručení and Payment=Platba here https://www.enakupak.cz/objednavka?step=1) step,. I am using prestashop 1.6.1.5
I know I have to modify order-carrier.tpl file and have followed several posts here and there but couldn't get it done right.
Does any of you have any actual idea on how to do this ?
I think that it will be change in this part of OrderController.php but dont know how to concretly change it
switch ((int)$this->step) {
case OrderController::STEP_SUMMARY_EMPTY_CART:
$this->context->smarty->assign('empty', 1);
$this->setTemplate(_PS_THEME_DIR_.'shopping-cart.tpl');
break;
case OrderController::STEP_DELIVERY:
if (Tools::isSubmit('processAddress')) {
$this->processAddress();
}
$this->autoStep();
$this->_assignCarrier();
$this->setTemplate(_PS_THEME_DIR_.'order-carrier.tpl');
break;
case OrderController::STEP_PAYMENT:
// Check that the conditions (so active) were accepted by the customer
$cgv = Tools::getValue('cgv') || $this->context->cookie->check_cgv;
if ($is_advanced_payment_api === false && Configuration::get('PS_CONDITIONS')
&& (!Validate::isBool($cgv) || $cgv == false)) {
Tools::redirect('index.php?controller=order&step=2');
}
if ($is_advanced_payment_api === false) {
Context::getContext()->cookie->check_cgv = true;
}
// Check the delivery option is set
if ($this->context->cart->isVirtualCart() === false) {
if (!Tools::getValue('delivery_option') && !Tools::getValue('id_carrier') && !$this->context->cart->delivery_option && !$this->context->cart->id_carrier) {
Tools::redirect('index.php?controller=order&step=2');
} elseif (!Tools::getValue('id_carrier') && !$this->context->cart->id_carrier) {
$deliveries_options = Tools::getValue('delivery_option');
if (!$deliveries_options) {
$deliveries_options = $this->context->cart->delivery_option;
}
foreach ($deliveries_options as $delivery_option) {
if (empty($delivery_option)) {
Tools::redirect('index.php?controller=order&step=2');
}
}
}
}
$this->autoStep();
// Bypass payment step if total is 0
if (($id_order = $this->_checkFreeOrder()) && $id_order) {
if ($this->context->customer->is_guest) {
$order = new Order((int)$id_order);
$email = $this->context->customer->email;
$this->context->customer->mylogout(); // If guest we clear the cookie for security reason
Tools::redirect('index.php?controller=guest-tracking&id_order='.urlencode($order->reference).'&email='.urlencode($email));
} else {
Tools::redirect('index.php?controller=history');
}
}
$this->_assignPayment();
if ($is_advanced_payment_api === true) {
$this->_assignAddress();
}
// assign some informations to display cart
$this->_assignSummaryInformations();
$this->setTemplate(_PS_THEME_DIR_.'order-payment.tpl');
break;
default:
$this->_assignSummaryInformations();
$this->setTemplate(_PS_THEME_DIR_.'shopping-cart.tpl');
break;
}
What if you cann this code after first case - break:
case OrderController::STEP_SUMMARY_EMPTY_CART:
$this->context->smarty->assign('empty', 1);
$this->setTemplate(_PS_THEME_DIR_.'shopping-cart.tpl');
break;
After this case add this case:
case OrderController::STEP_ADDRESSES:
$this->_assignAddress();
$this->processAddressFormat();
if (Tools::getValue('multi-shipping') == 1) {
$this->_assignSummaryInformations();
$this->context->smarty->assign('product_list', $this->context->cart->getProducts());
$this->setTemplate(_PS_THEME_DIR_.'order-address-multishipping.tpl');
} else {
$this->autoStep();
$this->_assignCarrier();
$this->setTemplate(_PS_THEME_DIR_.'order-carrier.tpl');
}
break;
Check, is it work.

Multiple conditional statement

What's the best way to write this in PHP, so I know which condition fails and is easy to maintain? Without resorting to multiple if else statements...
if ((!$titleBlockPresent || !$leadBlock || ($allDoubleBlockCount !=2 || $allDoubleBlockCount!=1) ||$countFirstSmallShowBlocks !=2 ||$countSecondSmallShowBlocks !=2 ) && !$contentNotAvailableMessage)
{
$this->fail("Block missing in the horizontal list of blocks on the non live carousel");
}
try this
$shouldFail = FALSE;
switch(TRUE){
case !titleBlockPresent:
echo "No title block present<br/>";
$shouldFail = TRUE;
case !$leadBlock:
echo "No lead block<br/>";
// the rest of the code
}
If you move that check into the function, it'll be clear for you and anyone else looking at your code, and very easy to maintain, for example:
function tester($var1, $var2, $var3)
{
if (!$var1)
{
$this->fail("error1");
return FALSE;
}
if (!$var2)
{
$this->fail("error2");
return FALSE;
}
if (!$var3)
{
$this->fail("error3");
return FALSE;
}
return TRUE;
}
You could also add a comment to each if that needs further clarification.
I just come up with this, but noticed that it is very similar to GeoPhoenix's answer, just the other way around, may be worth checking this out, as well:
$bFail = false;
if(!$bFail && $contentNotAvailableMessage) $bFail = true;
if(!$bFail && !$titleBlockPresent ) $bFail = true;
if(!$bFail && !$leadBlock ) $bFail = true;
if(!$bFail && $allDoubleBlockCount != 2) $bFail = true;
if(!$bFail && $allDoubleBlockCount != 1) $bFail = true;
if(!$bFail && $countFirstSmallShowBlocks != 2) $bFail = true;
if(!$bFail && $countSecondSmallShowBlocks != 2) $bFail = true;
if($bFail) $this->fail("Block missing in the horizontal list of blocks on the non live carousel");

make an ifnot statement and if statement in one line

I'm trying to make an if statement with 2 conditions. One that checks if one variable is NOT present & does NOT matches the word "good2go" and the other that checks to make sure "body" variable is present. I'm trying to trip the error message here. Here is what I have and what I've tried, and none of it seems to work.
if (stripos($_POST['check'], 'good2go') == FALSE && $_POST['body']) {
$error = true; }
if (!$_POST['check'] == 'good2go' && $_POST['body']) {
$error = true; }
if (!stripos($_POST['check'], 'good2go') && $_POST['body']) {
$error = true; }
if ((!stripos($_POST['check'], 'good2go')) && $_POST['body']) {
$error = true; }
How do I get this to work?
here's the entire code of contact_us.php this has the validation code and the email code.
$error = false;
if (isset($_GET['action']) && ($_GET['action'] == 'send')) {
// Winnie the pooh check
//$t = tep_db_prepare_input($_POST['verify']);
if (!isset($_POST['check']) && !$_POST['check']=='good2go' && isset($_POST['body'])) {
$error = true;
} else { // Winnie the pooh Check
$name = tep_db_prepare_input($_POST['name']);
$email_address = tep_db_prepare_input($_POST['email']);
//IP recorder start
$ipaddress = $_SERVER["REMOTE_ADDR"];
$ip = "\n\nIP: " . $ipaddress;
$content = "\n\nName: ".$name."\n\nComments: ".$_POST['enquiry'];
$product = tep_db_prepare_input($_POST['product']);
if ($product) {
$product_text = "\n\nProduct Interest: ".$product; }
$content_ip = $content . $product_text. $ip;
$enquiry = tep_db_prepare_input($content_ip);
//IP recorder end
}
// BOF: Remove blank emails
// if (tep_validate_email($email_address)) {
// tep_mail(STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, EMAIL_SUBJECT, $enquiry, $name, $email_address);
// tep_redirect(tep_href_link(FILENAME_CONTACT_US, 'action=success'));
// } else {
// $error = true;
// $messageStack->add('contact', ENTRY_EMAIL_ADDRESS_CHECK_ERROR);
if (! tep_validate_email($email_address)) {
$error = true;
$messageStack->add('contact', ENTRY_EMAIL_ADDRESS_CHECK_ERROR);
}
if ($enquiry == '') {
$error = true;
$messageStack->add('contact', ENTRY_EMAIL_CONTENT_CHECK_ERROR);
}
if ($error == false) {
tep_mail(STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, EMAIL_SUBJECT, $enquiry, $name, $email_address);
tep_redirect(tep_href_link(FILENAME_CONTACT_US, 'action=success'));
// EOF: Remove blank emails
}
}
Solution to your updated problem:
if (!isset($_POST['check']) || !$_POST['check']=='good2go' || !isset($_POST['body'])) {
$error = true;
}
The reason for the pipes vs ampersands is that you want to throw an error if ANY of the fields has issue. Also, you want to check if body is NOT set vs IS set. Glad this worked out for you!
and the other that checks to make sure "body" variable is not present.
if(stripos($_POST['check'], "good2go") !== false && !isset($_POST['body'])){
//code here
}
According to PHP docs regarding the stripos function:
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
So you need to change the first line to:
// Doing stripos checks you MUST use === (not ==)
if (stripos($_POST['check'], 'good2go') !== FALSE && $_POST['body']) {
$error = true; }
And to check if there is no $_POST['body'] you can change the above to:
if (stripos($_POST['check'], 'good2go') !== FALSE && (!isset($_POST['body'])) {
-- Update --
According to your comment, you need $_POST['check'] to equal 'good2go', then you shouldn't be using stripos as it will check for the existence of good2go regardless if it's exactly equal, or part of a string; 'wow this hamburger is good2go'.
So I would change the conditional to:
if (((isset($_POST['body'])) && (strlen($_POST['body']) > 0)) && ((!isset($_POST['check'])) || ($_POST['check'] !== 'good2go'))) {
// Post body has a value and Post check DOES NOT equal good2go, someone is hax0rin!
}
You may want to read up on Cross-site request forgery as it seems right inline with what you are working on.
One that checks if one variable is present & matches the word "good2go"
isset($_POST['check']) AND $_POST['check'] == 'good2go'
and the other that checks to make sure "body" variable is not present.
!isset($_POST['body'])
so, just put them together
if (isset($_POST['check']) AND $_POST['check'] == 'good2go' AND !isset($_POST['body'])) {
$error = true;
}
try this:
if(!empty($_POST['check']) && $_POST['check']=='good2go' && empty($_POST['body'])) { $error=true; }
Consider using empty instead of isset if your $_POST['body'] can be present with an empty value.
No need for all those unneeded functions. What you are trying to achieve is:
if (isset($_POST['check']) && $_POST['check']=='good2go' && !isset($_POST['body']) {
// your code
}
However, As per the title of the question: Use a ternary statement. Syntax is as such
$var = <condition> ? <true> : <false>;

Categories