PHP - Echo an array value from a class - php

I have the following PHP code
<?php
class SimpleEmailServiceMessage
{
public function properNames($formValue) {
$formValue = strtolower($formValue); //Make all letters small case
$formValue = ucwords($formValue); //Make all first letters capital
$formValue = str_replace('','',$formValue); //Remove extra spaces
if(is_numeric($username)) {
$error[] = 'The name is invalid';
}
return $error;
return $formValue;
}
}
$username = 'john doe';
$m = new SimpleEmailServiceMessage();
echo $m->properNames($username);
foreach($error as $result) {
echo $result . '<br>';
}
?>
I am managing to output $username, but I am not managing to output $error[] if it is a number. $error[] in my case is an array as different classes will have an error.
The current code is telling me Array Warning: Invalid argument supplied for foreach() in /web/com/140895582016925/main.php on line 22 which is for foreach($error as $result) {

The error message say it all: your $error is NOT an array.
Take a look at the is_numeric() validation part of your code.
You have an error there.
is_numeric() needs an argument.
In your case i think you need to:
if ( is_numeric($formValue ) )
{
// execute if condition
}

try this
<?php
class SimpleEmailServiceMessage
{
public $error;
public function properNames($formValue) {
$formValue = strtolower($formValue); //Make all letters small case
$formValue = ucwords($formValue); //Make all first letters capital
$formValue = str_replace('','',$formValue); //Remove extra spaces
if(is_numeric($formValue)) {
$this->error[] = 'The name is invalid';
}
return $formValue;
}
}
$username = 'john doe';
$m = new SimpleEmailServiceMessage();
echo $m->properNames($username);
if(isset($m->error))
{
foreach($m->error as $result) {
echo $result . '<br>';
}
}
?>
Demo

Try to use assignment:
$error = $m->properNames($username);
instead of echoing:
echo $m->properNames($username);

Related

Why does preg_match function validate all fields with a specific field argument?

I have a form in which I am using a preg_match function to validate fields. I have a generalized function for the matching. The function validateForm() is being called earlier on in the script with the appropriate values.
When the function is NOT passed any values, all the fields show the error message despite having correctly matching information. Generalized function with no arguments:
function validateForm() {
if(preg_match()) {
return true;
}
else {
return false;
}
} // end function validateForm
When I pass just ONE specific regex/field pair argument, all the fields begin to validate and show the error message when appropriate (so basically the code works as it should despite having a field-specific argument in the function). For example, when I pass this single regex/field argument into preg_match, all the fields begin to validate each field correctly, regardless of the fact that I am only checking for the 'City' field in this case. Example of passing a field-specific argument, in which all the code 'works':
function validateForm($cityRegex, $city) {
if(preg_match($cityRegex, $city)) {
return true;
}
else {
return false;
}
} // end function validateForm
Can someone explain to me why, when passed a specific argument for a specific field, the function will work for all individual preg_match arguments in the code? The script is running as I would want it to, I just do not understand why the specific argument is what makes it validate all fields.
Here is all of the PHP code, if needed:
<?php
$first = '';
$last = '';
$phone = '';
$city = '';
$state = '';
$error_message = '';
$firstLastRegex = '/^[a-zA-Z]{2,15}$/';
$lastRegex = '/^[a-zA-Z]{2,15}$/';
$phoneRegex = '/^(\(\d{3}\))(\d{3}\-)(\d{4})$/';
$cityRegex = '/^[a-zA-Z]{3,20}$/';
$stateRegex = '/^[a-zA-Z]{2}$/';
$validate_first = '';
$validate_last = '';
$validate_phone = '';
$validate_city = '';
$validate_state = '';
$phone_string = '';
if(isset($_POST['submit'])) {
$first = $_POST['firstName'];
$last = $_POST['lastName'];
$phone = $_POST['phoneNumber'];
$city = $_POST['userCity'];
$state = $_POST['userState'];
$show_form = false;
$phone_string = str_replace(array('-', '(', ')'), '', $phone);
$validate_first = validateForm($firstLastRegex, $first);
$validate_last = validateForm($lastRegex, $last);
$validate_phone = validateForm($phoneRegex, $phone);
$validate_city = validateForm($cityRegex, $city);
$validate_state = validateForm($stateRegex, $state);
if($validate_first == false) {
$show_form = true;
$error_message .= "Please enter your FIRST name between 2 and 15 letters.<br>";
}
if($validate_last == false) {
$show_form = true;
$error_message .= "Please enter your LAST name between 2 and 15 letters.<br>";
}
if($validate_phone == false) {
$show_form = true;
$error_message .= "Please enter your phone number in (###)###-### format.<br>";
}
if($validate_city == false) {
$show_form = true;
$error_message .= "Please enter your city name between 3 and 20 letters.<br>";
}
if($validate_state == false) {
$show_form = true;
$error_message .= "Please enter your state's abbreviation (Example: CA).<br>";
}
} // end if isset();
else {
$show_form = true;
$error_message = "";
} // end else
// REGEX FUNCTION
function validateForm() {
if(preg_match()) {
return true;
}
else {
return false;
}
} // end function validateForm
?>
You still need to have arguments for you function. The code below will make your validate function work.
function validateForm($regEx, $field) {
if(preg_match($regEx, $field)) {
return true;
}
else {
return false;
}
} // end function validateForm
I also see other potential issues with not checking if post variables are set before using them, and you are setting $show_form = true for all your if/else cases. I'm sure you can figure everything else out with some debug statements.

comparing code in Associative Arrays to hard coded values

I have a text file with the following values which would be used as a username and password
root=>user
roots=>password
blabla=>moonbeam
help=>me
Code for a function validateUser in a file validateUser.php
function validateUser($username, $password)
{
$filename = 'userCreds.txt';
$file = fopen($filename, "r");
if($file==false)
{
echo"Error opening file";
exit();
}
$i=0;
static $Credentials = array();
foreach (file($filename) as $line)
{
list($key,$value) = explode("=>",$line,2) + array(NULL,NULL);
if($value !== NULL)
{
$Credentials[$key] = $value;
}
}
print_r($Credentials);
echo "<br>";
//static $Credentials = array("root"=>"user","rtam"=>"password","q"=>"continuum");
if(array_key_exists($username, $Credentials))
{
echo "$Credentials[$username] <br>";
echo "$password <br>";
if($Credentials[$username] == $password)
{
return TRUE;
}
else
{
echo $Credentials[$username]," is not equal to ",$password,"<br>";
return FALSE;
}
}
else return FALSE;
}
Code for the main file:
<?php
include_once "validateUser.php";
$username = "root";
$password = "user";
if(validateUser($username,$password))
{
echo "<h2>Welcome! <br></h2>";
}
else
{
echo "Try again <br>";
}
?>
The values for $username and password are hardcoded from the beginning for testing purposes.
The problem I have, is when I get to comparing the username and password from the text file and comparing the two, they don't match.
Even when I print out the two values i.e. $password and $Credentials[$username], I get equal values on screen but the if statement doesn't recognize it using if($Credentials[$username] == $password).
What am I doing wrong?
please try to trim the values in your validateuser function - wouldn't be the first time a \n or \t or simple space caught me out.
if($value !== NULL)
{
$Credentials[trim($key)] = trim($value);
}
If that's not the case then maybe you can use regex to strip our any non alphanumeric chars from username and password.
eg
$key = preg_replace('/[^(\x20-\x7F)]*/','', $key);
$value = preg_replace('/[^(\x20-\x7F)]*/','', $value);

Header Redirect after form Validation in PHP

I am trying this code as part of form processing:
<?php
if(isset($_POST['senderEmail']))
{
try
{
require '_php/_security/validation.php'; //SEE BELOW
$rules = array(
'senderEmail' => 'validEmail',
'emailTextbox' => 'validTextbox',
);
$validation = new Validation();
if ($validation->validate($_POST, $rules) == TRUE) {
require("_php/database/dbProcessing.php"); //Form Proccessing for database inclusion
}
else {
foreach($validation->emailErrors as $error){
$emailErrors[] = $error;
$_SESSION['$emailErrors'] = $emailErrors;
header('Location:indexmobile.php#emailErrors');
die('ABORT!');
}
}
}
catch (PDOException $e)
{
$error = 'Error adding elements to database: ' . $e->getMessage();
echo "Error: " . $error;
exit();
}
exit();
}
?>
The validation.php where I do my validation has this:
<?php
class Validation {
public $errors = array();
public function validate($data, $rules) {
$valid = TRUE;
foreach ($rules as $fieldname => $rule) {
$callbacks = explode('|', $rule);
foreach ($callbacks as $callback) {
$value = isset($data[$fieldname]) ? $data[$fieldname] : NULL;
if ($this->$callback($value, $fieldname) == FALSE) $valid = FALSE;
}
}
return $valid;
}
public function validEmail($value, $fieldname) {
$valid = !empty($value);
if ($valid == FALSE) {
$this->emailErrors[] = "The $fieldname is required";
return $valid;
} else {
$valid = filter_var($value, FILTER_VALIDATE_EMAIL);
if ($valid == FALSE) $this->emailErrors[] = "The $fieldname needs to be a valid email";
return $valid;
}
}
public function validTextbox($value, $fieldname) {
$valid = !empty($value);
if ($valid == FALSE) {
$this->emailErrors[] = "The $fieldname is required";
return $valid;
} else {
$whitelist = '/^[a-zA-Z0-9 ,\.\+\\n;:!_\-#]+$/';
$textarea = strip_tags($value);
$textarea = mysql_real_escape_string($textarea);
$valid = preg_match($whitelist, $textarea);
if ($valid == FALSE) $this->errors[] = "The $fieldname contains invalid characters";
return $valid;
}
}
}
Upon using this, Im have issues with the redirect (I think). It seems further that Im having errors in validation. My questions are thus:
Am I doing the header redirect correctly? I've read that " header() must be called before any actual output is sent,.." So is this the reason why this redirect is incorrect? how to make a redirect if i need to show/send something to the redirected page?
function validTextbox always ends up an error that the field is empty. Why so?
Is my entire process of form validation a good way of validating form fields (which i learned from watching an online tutorial)? What is a better way?
Is there something wrong with error reporting in this case?
Thank you for those who replies. I am new to PHP and trying my best to learn the language.
1 - There are several ways to pass on a message to the page you are redirecting to. One is through $_GET like this
$message="Some message for the next page.";
$message=urlencode($message);
header("Location:page.php?message=".$message);
then on page.php
if(!empty($_GET['message']))
{
$_GET['message'];
}
similarly you can also use the session (less secure)
$_SESSION['message']='some other message';
then on page.php
if (!empty($_SESSION['message']))
{
echo $_SESSION['message'];
unset($_SESSION['message']);
}
2 - I would have to see what you are passing to your validate function. You should do a var_dump of $_POST and add that to your question.
3 - It depends on your criteria. If you are just checking for emptiness its overkill. I don't know what text you need / consider valid, but a regex is a reasonable way of enforcing validation.
4 - See #2.

Return true or false with preg match instead of echoing out a sentence

I am using the following to check to see if the data from a form contains certain words, the problem is though, when it checks I get "a match was found" or "a match was not found" over and over again a million times. How can I just assign a true or false value for the whole sentence that is posted ?. I want to then add something like....if true dump this post, if false process it and put it in the database.
<?php
$message = $_POST['message'];
echo $message;
$targets = array('viagra', 'prescription', 'drugs', 'zyban', 'zithromax', 'voltaren', 'cilias', 'FDA');
foreach($targets as $t)
{
if (preg_match("/\b" . $t . "\b/i", $message)) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
}
?>
function containsSpam($message) {
$targets = array('viagra', 'prescription', 'drugs', 'zyban', 'zithromax', 'voltaren', 'cilias', 'FDA');
foreach($targets as $t)
{
if (preg_match("/\b" . $t . "\b/i", $message)) {
//A match was found.
return true;
}
}
return false;
}
If i get it right you need to set a stop value like this
<?php
function containsSpam($message) {
$targets = array('viagra', 'prescription', 'drugs', 'zyban', 'zithromax', 'voltaren', 'cilias', 'FDA');
$stop = false;
foreach($targets as $t)
{
if (preg_match("/\b" . $t . "\b/i", $message)) {
//A match was found.
$stop = true;
break;
}
}
//And you can then do something like this
if ($check) {
//Insert it
} else {
//Dump it
}
}
?>

PHP foreach invalid argument supplied

I'm trying display error messages on a form but only one is displayed (the last one always). I tried using a foreach loop but I keep getting the invalid argument error. The following displays errors one by one. Code is inside a class...
public $errorContainer = '';
// ------------------------------------------------------------
// ERROR MESSAGE PROCESSING
// ------------------------------------------------------------
private function responseMessage($respBool, $respMessage) {
$return['error'] = $respBool;
$return['msg'] = $respMessage;
if (isset($_POST['plAjax']) && $_POST['plAjax'] == true) {
echo json_encode($return);
} else {
$this->errorContainer = $respMessage;
}
}
The following always gives me the invalid for each argument error.
private function responseMessage($respBool, $respMessage) {
$return['error'] = $respBool;
$return['msg'] = $respMessage;
if (isset($_POST['plAjax']) && $_POST['plAjax'] == true) {
echo json_encode($return);
} else {
foreach ($respMessage as $value) {
$this->errorContainer = $value;
}
}
}
Thank you!
replace your foreach() with this:
private function responseMessage($respBool, $respMessage) {
// ...code...
foreach ((array) $respMessage as $value) {
$this->errorContainer .= $value;
}
// ...code---
}
Using type casting (array) above will make it works for both array and string type.
Edit:
Use this solution (type casting) only in your last effort. But your real problem is you're not passing an array to the function. See this code:
// incorrect
$msg = 'This is a message';
$this->responseMessage($some_bool, $msg);
// correct
$msg = array('This is a message');
$this->responseMessage($some_bool, $msg);
// correct
$msg = array('This is a message', 'And another message');
$this->responseMessage($some_bool, $msg);
If you pass the argument correctly like above, you don't need to cast $respMessage to array.

Categories