PHP conditional statment inside a function - php

I am trying to create function that takes two arguments one for the user input and the other a message for error. I initially have an associative array with the two input fields and the corresponding error.
When the function is submitted without any entry I get two similar output; I thought I would get 'test1' and 'test2'. I am passing different arguments each time but I get the same result. The code is below
$valid = TRUE;
//$errors='';
$errors=array('desc_error'=>'please enter valid description',
'title_error'=>'provide valid title','no_error'=>'',);
function sanitizeText($input,$error){
//$input;
if($input!='')
{
$input= filter_var($input, FILTER_SANITIZE_STRING);
if($input==''){
global $errors;
$errors[$error];
$valid=FALSE;
return $errors[$error];
}
else{
$input;
echo 'test 1';
return $input;
}
}
else if($input=='')
{
if($input==$_POST['desc'])
{
echo 'the description field is required<br/>';
$valid=FALSE;
}
else{
//
}
}
}
if(isset($_POST['submit']))
{
$title=sanitizeText($_POST['title'],'title_error');
$desc=sanitizeText($_POST['desc'],'desc_error');
}
?>
<form method="post" action="">
<p>Book Title:<input type="text" name="title" maxlength="100" value=""/></p>
<p>Desc:<input type="text" name="desc" maxlength="100" value=""/></p>
<p><input type="submit" name="submit" value="Submit"/></p>
</form>

I think you are trying to validate form using php you can also user javascript to validate but to do it using php please refer following links.
http://myphpform.com/required-optional-fields.php
http://coredogs.com/lesson/form-and-php-validation-one-page
http://www.phpf1.com/tutorial/php-form.html?page=3
and
http://www.montanaprogrammer.com/php-web-programming/php-form-validation/

Your code does not make sense logic wise. Firstly, you check if $input is an empty string, or is not, and then within that first check.. you again make the same exact check. Since ifs are evaluated in order, and input is not ever going to be an empty string, the first if will always execute.
Then, your first 'else'; it will only execute if the $input variable is an empty string.. I can sort of see what you're attempting to do, but it won't work as it is right now. In order for it to work, it would have to look something like the below:
function sanitizeText($input,$error) {
global $errors;
global $valid;
$input_val = filter_var($_POST[$input], FILTER_SANITIZE_STRING);
if ($input_val != '') {
$valid = TRUE;
return $input;
}
else if ($input_val == '') {
$valid = FALSE;
echo $errors[$error].'<br />';
}
}
if(isset($_POST['submit']))
{
$title=sanitizeText('title','title_error');
$desc=sanitizeText('desc','desc_error');
}
If the input value is not an empty string, it will return the input value. If it is, it will not return anything and will instead echo the appropriate error.

Related

return message if input is in array

I have a form validation that, so far, returns an error message if either of two defined words/phrase are present in the input area:
add_filter('gform_validation_3', 'custom_validation');
function custom_validation($validation_result){
$form = $validation_result["form"];
foreach($form['fields'] as &$field){
/* Check that the value of the field that was submitted. e.g. the name="input_1" that is generated by Gravity Forms */
if($_POST['input_4'] == "Your First Name" || "SEO"){
// set the form validation to false
$validation_result["is_valid"] = false;
//The field ID can be found by hovering over the field in the backend of WordPress
if($field["id"] == "4"){
$field["failed_validation"] = true;
$field["validation_message"] = "This field needs to be your actual first name.";
}
}
}
//Assign modified $form object back to the validation result
$validation_result["form"] = $form;
return $validation_result;
}
I'm not sure now how to create an array to define the words that are not allowed, so that I can have a much longer list?
First of all, the first "if" is incorrect, I think you meant:
if($_POST['input_4'] == "Your First Name" || $_POST['input_4'] =="SEO")
A good way to achieve what you long is:
$forbidden_words = ["Your First Name", "SEO"];
$is_valid = !in_array($_POST['input_4'], $forbidden_words); //false if the word is in array
After that you may go:
if($is_valid)
//do magic
You can use function in_array()
<?php
$blacklisted = ['some', 'ugly', 'bad', 'words'];
if(in_array('ugly', $blacklisted)){
echo('bad word spotted');
}
demo: https://repl.it/#kallefrombosnia/DarkvioletDeepPolygons

PHP class, html forum, print $_POST Array on page

i am beginner php programmer, iv been trying to create a small program that takes input from a forum and then after submission i want it to be printed on the screen. simple and easy i thought, iv been trying and suspiciously it seems to work fine for 1 text field, when i added the remaining 2 text fields called [fam][user] my code stops returning the content to the screen. also i started to recieve an error of an unindex array, therefore i had to use isset to counter this problem, and also, why does my code call the destructor although i never implicitly set my destructor. i dont know how to ask these questions because the errors arent consistent.
code doesnt print my [name][fam][user]
code prints [name] when everything about [fam][user] are ommited from the code.
-code sometimes called the destructor
-code doesnt clear html previous input(e.g, when working with the one text field, lets say i input the [name] john, and click submit it
displays submit, then,i refresh the page, and the name john is still
displayed, why doesnt the destructor clear the memory of name from my
submission.
<form class="nameform" action="book.php" method="post">
<input type="text" name="Name" value="1">
<input type="text" name="Fam" value="2">
<input type="text" name="User" value="3">
<input type="button" name="submit" value="Submit">
</form>
private $name; private $familyName; private $userName;
function __construct($names,$familyNames,$userNames)
{
$this->name = $names;
$this->familyName = $familyNames;
$this->userName = $userNames;
}
function getName()
{
return $this->name;
}
function getFamilyName()
{
return $this->familyName;
}
function getUserName()
{
return $this->userName;
}
public function __destruct()
{
echo "destroyed again";
$this->name;
$this->familyName;
$this->userName;
}
}
if(!isset( $_POST["Name"])||!isset($_POST["Fam"])||!isset($_POST["User"]))
{
echo "Please fill in the data";
} else {
$p1 = new Person($_POST["Name"],$_POST["Fam"],$_POST["User"]);
print $p1->getName();
print $p1->getFamilyName();
print $p1->getUserName();
print_r($_POST);
}
// $n = $_POST["Name"];
// $f = $_POST["Fam"];
// $u = $_POST["User"];
// $p1 = new Person($_POST["Name"],$_POST["Fam"],$_POST["User"]);
?>
code doesnt print my [name][fam][user]
You never echo them out of the destuctor
public function __destruct()
{
echo "destroyed again";
$this->name; //<---- does nothing
$this->familyName;
$this->userName;
}
So I am not sure what this is supposed to do. You have them down at the bottom
print $p1->getName();
print $p1->getFamilyName();
print $p1->getUserName();
But the only thing you'll get from the destruct method is
"destroyed again"
And you will only see that if everything in the form is set. Which it always is when the form is submitted, because type text is always submitted with its form.
Which brings me to this, you should be checking empty instead of isset there
if ('POST' === $_SERVER['REQUEST_METHOD']) { //check if POST
if(empty($_POST["Name"])||empty($_POST["Fam"])||empty($_POST["User"])){
echo "Please fill in the data";
} else {
$p1 = new Person($_POST["Name"],$_POST["Fam"],$_POST["User"]);
print $p1->getName();
print $p1->getFamilyName();
print $p1->getUserName();
print_r($_POST);
}
}
Note that anything falsy will be empty, false, [], '', 0, '0', null etc.
I don't know if this solves all of you problems, but these things could produce some of the behaviour you are experiencing.
Another more advance way to check these is like this:
if ('POST' === $_SERVER['REQUEST_METHOD']) { //check if POST
$post = array_filter( $_POST, function($item){
return strlen($item); //any thing of a length of 0 is removed
});
if(count($post) != count($_POST)){
foreach(array_diff_key( $_POST, $post) as $missing=>$empty) {
echo "Please fill in $missing\n";
}
}else{
$p1 = new Person($_POST["Name"],$_POST["Fam"],$_POST["User"]);
print $p1->getName();
print $p1->getFamilyName();
print $p1->getUserName();
print_r($_POST);
}
}
Output
Please fill in Name
Please fill in Fam
You can test it online Here
Cheers!

PHP save array value if match to Session

I have an Input submit form and i want if an user enters an number thats match with my array value, the Card Brand saves to PHP Session on next site.
<?php
$submitbutton= $_POST['btnLogin'];
$number= $_POST['Kreditkartennummer'];
function validatecard($number)
{
global $type;
$cardtype = array(
"visa" => "/^4[0-9]{12}(?:[0-9]{3})?$/",
"mastercard" => "/^5[1-5][0-9]{14}$/",
"amex" => "/^3[47][0-9]{13}$/",
"discover" => "/^6(?:011|5[0-9]{2})[0-9]{12}$/",
);
if (preg_match($cardtype['visa'],$number))
{
$type= "visa";
return 'visa';
}
else if (preg_match($cardtype['mastercard'],$number))
{
$type= "mastercard";
return 'mastercard';
}
else if (preg_match($cardtype['amex'],$number))
{
$type= "amex";
return 'amex';
}
else if (preg_match($cardtype['discover'],$number))
{
$type= "discover";
return 'discover';
}
else
{
return false;
}
}
validatecard($number);
?>
The Question now, works it with my Code? or needs an "If Submit"?
The other question how can i echo the return and save it to my php Session?
To save something to your session variable all you have to do is declare it so.
$_SESSION['card_type'] = $_POST['card_type'];
for example let's say this is your form. This is only an example.
<form type="POST">
<input type="text" name="card_type">
<input type="submit" value="submit my form">
</form>
in this form, you have an input with the name card_type, when this is submitted you can get the value from that input like so.
if(isset($_POST['card_type'])) {
$_SESSION['card_type'] = $_POST['card_type']; //you are taking the post and making a session variable.
}
I know this only explains the last part of your questions, I just did not understand the first part.
edit..I also wanted to point out that you do not just want to accept the user input without some type of validation. Put you validation code after you check if there has been a post.

the best approach to giving an error message when validating

I am a new programmer and am attempting to do some validation for a basic registration form. I have built a basic registration form that sends the user back to the same page when submitted. I have also created a user class and have created some basic validation functions. However, the functions have the error messages built into them. I obviously put the functions on the top of the registration form so when there is an error the errors are posted on the registration form. However, I have no control on how the error messages look and would like to know if there is a lot better way to somehow echo the error messages from outside the class so I can use some type of css or something else for better control of how they look. I hope that makes sense. Also when there is an error the user is sent back to an empty registration form. I was trying to figure out how to keep the valid information in the text boxes and just make them redo the invalid information. Here is a basic example of a validation I have done. I know its basic but I am very new to programming
function validate_password($password)
{
$valid = TRUE;
if ($password == '')
{
echo "<p> Please enter a value for the password </p>";
$valid = FALSE;
}
elseif($_POST['pwd'] !== $_POST['pwd2'])
{
echo "The passwords do not match please try again";
$valid = FALSE;
}
return $valid;
}
Don't echo them right away, instead store them for later use. You mentioned this is inside a class, so you can use a class property to hold error messages.
class YourClass
{
public $error;
function validate_password($password)
{
$valid = TRUE;
if ($password == '')
{
// Set the error message
$this->error = "Please enter a value for the password";
$valid = FALSE;
}
// etc...
}
}
Later, when you need to, you can output it in the HTML:
if (!empty($yourclass->error)) {
echo "<p class='errmsg'>{$yourclass->error}</p>\n";
}
You then just need a CSS class errmsg and you can style it how you like:
.errmsg {
color: #FF0000;
font-size: 36px;
}
Now if you have that working, you can expand it further to make the $error class property into an array and push multiple messages onto it:
// In the class, initialize it as an array
$this->error = array();
// Use the [] notation to append messages to the array.
$this->error[] = "Another error message..."
$this->error[] = "And yet another error message..."
In your presentation code, use a loop to output the messages:
// Output a big stack of error messages...
foreach ($yourclass->error as $err) {
echo "<p class='errmsg'>$err</p>\n";
}
What I normally do with classes and their errors is have a variable specifically for the errors.
So something like:
class User
{
private $_ValidationErrors = array();
function validate_password($password)
{
$this->_ValidationErrors = array();
$valid = TRUE;
if ($password == '')
{
$this->_ValidationErrors[] = "Please enter a value for the password";
$valid = FALSE;
}
elseif($_POST['pwd'] !== $_POST['pwd2'])
{
$this->_ValidationErrors[] = "The passwords do not match please try again";
$valid = FALSE;
}
return $valid;
}
function ValidationErrors ()
{
if (count($this->_ValidationErrors) == 0)
return FALSE;
return $this->_ValidationErrors;
}
}
Then to use:
$user = new User();
if (!$user->validate_password('somepass'))
echo implode('<BR>',$user->ValidationErrors ());
EDIT: To display errors by the user something like:
<?php
if (isset($_POST["submit"]))
{
$user = new User();
$passwordErrors = (!$user->validate_password($_POST["pass1"]))?$user->ValidationErrors():array();
}
?>
<form action="<?php echo $_SERVER["php_self"]; ?>" method="post">
<input type="text" name="pass1" value="<?php echo htmlspecialchars($_POST["pass1"]); ?>" /><BR/>
<?php
echo ((isset($passwordErrors) && count($passwordErrors) == 0)?"":implode("<BR/>", $passwordErrors));
?>
<input type="submit" name="submit" value="Register" />
</form>

Using $_POST += array() for default values

I'm finishing up a small contact form and had a question about providing default values for $_POST. The reason I'm asking about default values is because within my form I have fields like this:
<input type="text" name="fullname" value="<?php echo $_POST['fullname']; ?>" />
Clearly I would like to retain the submitted value if I do not permit the data to clear. This raises errors when the page is first loaded, since there is no value for $_POST['fullname'].
To my question: is there anything I should be concerend about providing default values to the $_POST array like I'm doing in the next code-sample:
$_POST += array(
'fullname' = '',
);
If $_POST['fullname'] already exists, it will be retained - if it doesn't, it will be created within the array. This way, upon loading the form, blank values will be presented in the input fields.
Don't worry, all
I sanitize my data
Thank you for the help
Even if you are doing so, put that data in your container, do not modify superglobals. Create class that'll contain your data - then you'll have the interface do sanitize, manipulate and get it te proper way. Import data from $_POST and then validate, if all necessary values are in.
As for code:
<?php
class PostData
{
private $data;
public function __construct(array $data)
{
$this->data = is_array($data)
? $data
: array();
}
public function set($key, $value)
{
$this->data[$key] = $value;
}
public function get($key, $default, $escaping)
{
if(isset($this->data[$key]))
{
switch($escaping)
{
case 'htmlspecialchars':
{
return htmlspecialchars($this->data[$key]);
break;
}
case 'mysql_real_escape_string':
{
return mysql_real_escape_string($this->data[$key]);
break;
}
// and so on, your invention goes here
default:
{
return $this->data[$key];
}
}
}
else
{
return $default;
}
}
}
$postData = new PostData($_POST);
Create function:
function displayValue($field) {
if(isset($_POST[$field])) {
echo 'value="' . htmlentities($_POST[$field]) . '"';
}
}
And then use like:
<input type="text" name="fullname" <?php displayValue('fullname'); ?> />
You can also do it like this:
<?php echo empty($_POST['fullname']) ? null : $_POST['fullname']; ?>

Categories