Php Filter array - php

I need a simple example of php filter array. This function is new for me so please I can't understand complex program of it.
I want to store filtered data to the database from a simple form where these conditions can exist.
i.e:
NAME in capital words.
proper email/Password syntax.
proper address and mobile number (1234-1234567)
registration no: 2012-2015-AUP-1234
if any one mistakes an alert or message is displayed.

array_filter :
The official documentation for PHP is full of very understandable examples for each function. These examples are given by the documentation or the community, and follows each function description.
PHP Documentation
Form validation :
A little code example for the script called by your POST form. Of course a lot of changes to this can be made to display the errors the way you like, and perhaps tune more precise checks on each data.
<?php
if (isset($_POST['name']) && !ctype_upper($_POST['name'])) {
$errors[] = 'name should be uppercase';
}
if (isset($_POST['email']) && !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = 'email is invalid';
}
if (isset($_POST['password']) && strlen($_POST['password']) >= 6 && strlen($_POST['password']) <= 16)) {
$errors[] = 'password should be between 6 and 16 characters length';
}
if (isset($errors)) {
// do not validate form
echo '<ul><li>' . join('</li><li>', $errors) . '</li></ul>';
// ... include the html code of your form here
}
else {
// ... call things that must work on validated forms only here
}

Related

How to go to new page on form submit only if form passes error checks?

I have an HTML form with PHP error checks. The form has several different types of fields (one for name, email, phone number, a checkbox, a drop down, etc.) and I have a PHP function written for each that runs when you hit the submit button, and checks that the form is filled in correctly and fully. If a field is left empty, or is filled in incorrectly, an error message appears. However, after I got that running, I tried to add a redirect, so that after the form is completed and submit is pressed, it brings the user to a confirmation page, if the errorchecks are passed. I wrote it like this:
if(isset($_POST['submit']) ){
header("Location:confirmed.php");}
It does what it's supposed to--bring the user to a new page--but it doesn't take into consideration any errorchecks. So, when submit is pressed, rather than run through the error checks, it immediately goes to the new page. I tried adding a variable named "errorcount" so each function so that the number of errors that occur when the form is submit will be either counted, or removed from the count, and then considered when changing the page...
if(isset($_POST['submit']) ){
if ($errorcount == 0){
header("Location:confirmed.php");}}
This didn't work either. I realized that $errorcount wasn't actually being updated at all; for what reason, I'm not sure. I set it up so each function returns $errorcount, and then called each function in the snippet of code above before running the second if statement, but it still does nothing.
I feel like I'm approaching this the wrong way, but I'm not really sure how else to do this. Please tell me if there's an easier way to achieve this, or maybe you have an idea what I'm doing wrong in the first place.
EDIT:
I am passing the variable $errorcount as global in each function, like so:
function validateName ($name, $submit){
global $errorcount;
if( empty( $submit )) {
return '';}
if (empty ($name)){
return "You didn't enter your name!";
$errorcount = $errorcount+1;
}
if (!preg_match("/^[a-zA-Z \-]*$/",$name, $matches)){
return "Please enter a valid name";
$errorcount = $errorcount+1;
}
else{
$errorcount = $errorcount-1;
}
return $errorcount;
}
However, $errorcount still does not actually change with the if loop I posted above. If I take that out (the section of code that causes the page to change) then the functions work as intended; once you click submit, the page refreshes, and error messages appear where the user did not fill out the form properly. But once all the form areas are filled out properly, clicking submit does... nothing.
EDIT 2:
I got it working. It's honestly not very efficient but it does what I need it to do. Thanks to all who helped!
You don't really need to count the errors, and you don't need to use global. Just write your validator functions so they return an error message if there is an error, or nothing if there is no error. Like this, for example:
function validateName($name) {
if (!$name) {
return 'name is required';
}
if (!preg_match("/^[a-zA-Z \-]*$/", $name)) {
return "Please enter a valid name";
}
}
Then when you run your validators, add any error messages you get to an array.
if ($error = validateName($_POST['name'] ?? '')) {
$errors['name'] = $error;
}
After you run all the validators, if the error array is empty, then there were no errors so you can redirect. And if it's not empty, then you have an array of errors keyed by field name, so you can display any errors next to the problematic fields, which your users will prefer rather than getting one error at a time in some generic location.
if (empty($errors)) {
// redirect
} else {
// stay here and show the errors
}
You're needlessly complicating things. Defining functions are only useful if you plan on re-using that code elsewhere. Try this instead:
if ( isset($_POST['submit']) )
{
if ( empty($name) )
{
echo "You didn't enter a name!";
sleep 3;
// redirect or re-load the form
}
elseif ( !preg_match("/^[a-zA-Z \-]*$/", $name, $matches) )
{
echo "Enter a valid name!";
sleep 3;
// redirect or re-load the form
}
header("Location:confirmed.php");
}

Redirection with $_SERVER["PHP_SELF"] and using header()

is it possible to do this , im trying to validate a form then, it will redirect using header() if TRUE.. but it seems not to be working? or my method is completely wrong ?
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = $_POST["clientEmail"];
if ($email != $sentEmailClients) {
echo 'Please enter a valid email';
} else {
$newURL = "http://www.myurl.com";
header('Location: ' . $newURL);
}
}
Give us more details about what actually happens when you run your code. You're likely facing one of the following problems:
You're using header() after you've already sent output to the browser. Headers must be sent before any other output. Check out the docs. If you change that line with die('redirecting') and that text shows up, then this is your problem.
Request method is not POST. Add die($_SERVER['REQUEST_METHOD']). If something other than POST is printed, then this is your problem.
$_POST['clientEmail'] is not set, or is not equal to $email
$email is not what you expect (where does it come from?)
$sentEmailClients is not what you expect (where does it come from?)
Basically, "why doesn't it work?" is not a good question because it doesn't give us much info with which to help you. Be more specific about what is happening.
Show enough of your code that we understand the origin of the variables you use.
Hi It seems that Your outermost if condition is not working thats why your header function is not working i just tried this and it woks fine. That means either your first if condition is false or either second if condition becomes true every time just try to echo your values before checking them.
<?php
if (1) {
$email = $_POST["clientEmail"];
if (0) {
echo 'Please enter a valid email';
} else {
$newURL = "http://www.google.com";
header('Location: ' . $newURL);
}
}
check this print_r($_SERVER["REQUEST_METHOD"]); is POST or not and
$email != $sentEmailClients true or false

How to echo variables in the middle of messages provided from translation array?

So I'm making a CMS from scratch, a CMS that will support multiple languages.
I have separate .php translation file for each supported language. I require_once the right translation file according to the user setting. If they choose to view site in English then they get require_once 'lang/english.php';, etc. This is the content of english.php:
<?php
function text($phrase){
static $text = array(
'WELCOME' => 'Welcome to the CrappyCMS!',
'NEW_MEMBER' => 'This user is new. What a scrub.',
'ERROR_EMPTY_FIELDS' => 'Please fill in all of the required fields.'
);
return $text[$phrase];
}
For example, I basically use echo text('WELCOME'); in my home page to display the welcome message in right language.
Now I have some old code from my earlier CMS that has this kind of error recording in the user registration page:
if (user_exists($_POST['username']) === true){
$errors[] = 'Sorry, the username \'' . $_POST['username'] . '\' is already taken.';
}
if (preg_match("/\\s/", $_POST['username']) == true){
$errors[] = 'Username must not contain any spaces.';
}
if (email_exists($_POST['email']) === true){
$errors[] = 'Sorry, the email \'' . $_POST['email'] . '\' is already in use.';
}
(I know it's probably vulnerable code but I'll fix it later, don't mind security)
I want to edit it to return array keys to refer to translation array's values, such as this:
if (user_exists($_POST['username']) === true){
$errors[] = 'ERROR_USERNAME_TAKEN';
}
Then I will have an array entry in my translation file for 'ERROR_USERNAME_TAKEN' through which I will display the error(s).
Now finally to the question, I'm not sure how I can display things like user-entered username in the middle of the message and do it in elegant and simple way. As you can see my old CMS shows $_POST['username'] in the middle of the error message. I'm not sure how I can implement this in efficient way to my new CMS.
I would show you my solution but sadly I don't have one in mind, things that come into my mind currently are kinda absurd, inefficient and very dirty.
Any input is welcome.
http://php.net/manual/en/function.sprintf.php provides the functionality for this.
$welcome = 'Welcome to the %s!';
$cms = 'CrappyCMS';
echo sprintf($welcome, $cms);
// echoes: Welcome to the CrappyCMS!
Else you could write your own preg_replace function.

PHP Printing Conditions Unxepectedly

Hi Guys i am having a very peculiar problem i have written a small code so that it is possible to sign up to the website i am creating with a few restrictions to each field however from what i see the code seems ok but each time i try to use the php code with html code the browser is always printing part of the code like this:
"11){ echo 'Username needs at least 6 and maximum 11 characters'; } else if (strpos($Username, '#') != 0) { echo ' Username cant be your email'; } ?>"
<?php
$Username = 'aasd';
if (strlen($Username) < 6 || strlen($Username) > 11){
echo 'Username needs at least 6 and maximum 11 characters';
}
else if (strpos($Username, '#') != 0) {
echo ' Username cant be your email';
}
?>
From what i can see the code is correct but i can't seem to find the reason as to why this is happening am i missing something in the PHP code? do i have some condition or operator that is not set in the right way?
Thank you first hand to all those who reply

How to validate reCAPTCHA

I want to write a JavaScript and php validation for reCAPTCHA In my php I have the function below but I doesn't work. It doesn't, return an errror message if I enter the wrong reCAPTCHA code:
function invalid($inputname,$error_message)
{
$this->js.='if (!invalid(formname.'.$inputname.',"'.$error_message.'")) return false;';
if ( isset($_POST[$inputname]) && strlen($_POST[$inputname]) - strlen(str_replace(' ','',$_POST[$inputname])) > $limit && $_POST[$inputname] != "")
{
$this -> error_message .= $error_message.'<br>';
}
}
I don't want to just echo the message I want to echo the message on top of the form like I did with my other validate using:
Can someone show me how to do it correctly in php and javascript?
Thanks
Please read the reCAPTCHA documentation. It clearly outlines the correct use of the recaptcha_check_answer() function (part of the reCAPTCHA PHP library) to validate solutions.
This
strlen($_POST[$inputname]) - strlen(str_replace(' ','',$_POST[$inputname])) > $limit
will be false, assuming $limit is something like 6. Should be just
strlen(str_replace(' ','',$_POST[$inputname])) > $limit
Let's say the captcha is "bananas". strlen("bananas") - strlen("bananas") == 0.
Added The JavaScript doesn't return false at any point, so it will return undefined if the captcha is correct, which may affect your code elsewhere (particularly if you are using === ).

Categories