I am trying to check that all query requests from a form is filled and not hindered before proceeding with further actions.
I have a code that works already, but i would like to make it an array in other to shorten my code.
My form queries are a,b,c
Below is my current code:
if ( isset($_GET) && !isset($_GET['a']) || !isset($_GET['b']) || !isset($_GET['c']) )
{ //Reject call
}else{
//Process call
}
I wish to shorten this code with an array, here is my current code but this isn't working.
$supportedrequests = array('a','b','c')
if (isset($_GET) && !isset($_GET[(in_array($supportedrequests))]) ) {
{ //Reject call
}else{
//Process call
}
Any help will be appreciated.
UPDATE
This question is not a duplicate of Using if(!empty) with multiple variables not in an array because it is specifically based on checking isset($_GET) query itself if it exists, and aside that, no answer was fully rendered for the said topic in the stated link.
If you want check request method GET or POST use this: $_SERVER['REQUEST_METHOD'] == 'POST'
For checking multiple parameters you can declare function and check them all.
function allIsset($params)
{
foreach ($params as $param) {
if (!isset($_GET[$param])) return false;
}
return true;
}
Or you can use this method (if you want just less lines of code)
$supportedrequests = array('a','b','c');
if (count(array_intersect(array_keys($_GET), $supportedrequests)) < count($supportedrequests)) {
//reject
}
Related
I'm trying to match a condition where if the user status is 10 and ANY POST variables are not set it triggers an error:
if ($_SESSION['status']=='10' && !isset($_POST['a']) || !isset($_POST['B'])) {}
I can not use && conditions for any !isset as one variable may be set though another might not. I only want the condition to match if one or more variables are not set AND the status==10.
When testing if a $_POST variable !isset, I remove an input element from the page via a browser web tool (e.g. Firebug). When the form is submitted with the variable missing it's still passing validation incorrectly.
I am also seeking a PHP if grouping condition.
If you are looking for absolutely any PHP variables, I'd recommend this:
if (($_SESSION['status'] == 10) && (count($_POST) > 0)) {
You can then get the list of _POST var keys using array_keys($_POST).
If you are looking for a specific:
if (($_SESSION['status'] == 10) && (isset($_POST['A']) || isset($_POST['b']))) {
The order of the brackets is important. You can separate groups of logical statements with brackets.
Is that was what you were looking for?
$status = $_SESSION['status'];
if($status == '10'){
if(!isset($_POST['a']) or !isset($_POST['B'])){
//Triggers error.
}else{
//Another
}
}
Try making it a function:
function checkAllVars($dataVars, $requestVars) {
foreach($dataVars as $varname) {
if(!isset($requestVars[$varname])) {
return false;
}
}
return true;
}
$dataVars = array (
"varName1",
"varName2",
"varName3",
"varName4",
);
$allVarsSet = checkAllVars($dataVars, $_REQUEST);
you might be looking for
if($_SESSION['status']=='10' && (!isset($_POST['a']) || !isset($_POST['B']))){}
^ ^
which means if status = 10 and (if not set 'a' or not set 'B' or they can be both not set) do something
or you might be looking for
if(($_SESSION['status']=='10' && !isset($_POST['a'])) || ($_SESSION['status']=='10' && !isset($_POST['B']))){}
This question already has answers here:
passing POST array to php function
(3 answers)
Closed 9 years ago.
I've been working on a project for a game (so you'll understand that I can't post the actual script), and I'm cleaning up the code and placing code into functions instead of just after the
if ($_POST['name'] { //code }
Is this the correct method of doing what I'm trying? (I tried, but it broke my system)
if ($_POST['action'] == "actionName") actionName($_POST); //calls function if the $_POST is present
function actionName($_POST) { //code }
Thanks in advance for correct answers!
$_POST is globally accessible. So you don't have to pass to your function:
if ($_POST['action'] == 'actionName') actionName();
function actionName() {
//code using $_POST
}
If you want your function to be able to do what it wants with any array (i.e. other than $_POST), then make the function take a parameter, but don't call it $_POST:
if ($_POST['action'] == 'actionName') actionName($_POST);
function actionName(parameters) {
//code using parameters
}
$_POST is a super-global. All PHP code, no matter the scope, automatically has access to this data structure.
Therefore, the following is fine:
if ($_POST['action'] == "actionName") {
actionName();
}
and then
function actionName() {
print_r($_POST);
// code
}
$_POST is already a superglobal variable so you do not need to pass it to a function. If the function needs the content of $_POST then make a copy and pass it to the function.
However, from your example, it seems to me that you need to pass $_POST['action'] to your function instead of $_POST.
Well in your example you need to have quotes around your string variables:
//calls function if the $_POST is present
if ($_POST['action'] == 'actionName') actionName($_POST);
function actionName($_POST) { /*code*/ }
Although $_POST is super-global, yes of course you can do that and is actually a good idea. This way you decouple your code and maybe you can reuse actionName in another part of the application.
However, don't name the parameter of the function $_POST (this is more confusing than helpful).
To avoid a bunch of if statements for every possible action, have a look at call_user_func [docs].
E.g. you could do:
$allowed_actions = array_fill_keys(array('actionName', ...), true);
if(isset($allowed_actions[$_POST['action']])) {
call_user_func($_POST['action'], $_POST);
}
You should move the function before the code that executes it along with what everyone else here is saying about the $_POST array. Try this if you want
function actionName($input) { // code and return }
if (isset($_POST['action'])) {
$action = $_POST['action'];
if ($action == 'actionName') {
$name = actionName($action);
}
}
$_POST is a super global (as other have mentioned), so you don't need to pass it in.
You can pass it in so that you decouple the function code from the environment in which it's running. For example, should you wish to initiate such an action as a result of something else in the code, you can pass in an array with the same key/values that $_POST would have to do so
If you do pass in $_POST to a function, name the function argument something else, hopefully something that indicates what the data represents
Consider that the function may not need all the key/values that $_POST normally contains, and if you might be better off defining a function that takes only the arguments it needs in order to function
If you are talking about dynamically calling a function, you could achieve it this way:
/*
Example Post
$_POST['functionName'] = 'doSomething';
$_POST['value'] = 'woot!';
*/
function doSomething($message) {
echo $message;
}
// Call the function if it exists
if (function_exists($_POST['functionName']) {
call_user_func($_POST['functionName'], $_POST['value']);
}
// The above would output "Woot!"
dispatch_address_postcode
isn't mandatory and it will still run even if it's blank:
if (!is_null($_POST['personal_info_first_name']) &&
!is_null($_POST['personal_info_surname']) &&
!is_null($_POST['personal_info_email']) &&
!is_null($_POST['personal_info_telephone']) &&
!is_null($_POST['dispatch_address_country']) &&
!is_null($_POST['dispatch_address_first_name']) &&
!is_null($_POST['dispatch_address_surname']) &&
!is_null($_POST['dispatch_address_address']) &&
!is_null($_POST['dispatch_address_town']) &&
!is_null($_POST['dispatch_address_postcode']) &&
!is_null($_POST['dispatch_address_county']) &&
( ($_POST['payment_method'] == "Pay by credit card.") ||
(
($_POST['payment_method'] == "Pay by new credit card.") &&
!is_null($_POST['card_number']) &&
!is_null($_POST['expiration_date']) &&
!is_null($_POST['security_code'])
)
)
)
What gives?
"dispatch_address_postcode isn't mandatory and it will still run even if it's blankā¦"
Just look at that sentence again. If the field is not mandatory, it is perfectly okay if the code runs if the field is blank. If a field isn't mandatory, don't test it as mandatory.
The real problem is though, is_null only tests if the variable is null. POSTed values will never be null, if they're empty they will be '' (an empty string). All your !is_null tests will always be true, and you will get a warning if the variable isn't set (something you don't want to happen). The more appropriate test would be !empty.
Even more appropriate tests would include a test if the value appears to be valid (does email look like an email address, does telephone have at least x digits in it?). You should also loop through the fields to make your code more readable, endless nested and chained if conditions are no joy to look at.
$mandatoryFields = array('foo' => 'email', 'bar' => 'telephone');
foreach ($mandatoryFields as $field => $rule) {
if (empty($_POST[$field]) || !validateByRule($_POST[$field], $rule)) {
raiseHell();
}
}
It looks like you're trying to make sure all post variables are submitted. Would you like help with that?
Using !empty() may not be the answer to your specific question, but it would definitely help with what it looks like you're trying to do.
empty() returns TRUE if the $_POST key isn't set, if its an empty array, or even if its an empty string, so using !empty() is a good way to make sure that the user has filled in the information.
Try writing your own is_valid function and use that rather than is_null.
For example (and this is by no means comprehensive):
function is_valid(&$array, $key, $required=false) {
if(!array_key_exists($array))
return false;
$value = trim($array[$key]);
if(empty($value) && $required)
return false;
return true;
}
Use like so:
if(is_valid($_POST, 'personal_info_first_name', true) && ...)
!is_null($_POST['personal_info_first_name']) && !isset($_POST['personal_info_first_name'])
use array_key_exists('card_number', $_POST) && !empty($_POST['card_number'])
Edit: Please consider this before a downvote. I'm leaving this here to serve as a "what not to do". I would delete it because it's bad, but then nobody would learn from my mistakes.
DO NOT DO THIS - read the comments for great info on why this is bad
My answer is going to be wildly different, but I am a wildly different guy...
I JUST found that this will work. Instead of all that isset and things, just assign the variables programmatically! I think I have some refactoring to do... y'know on all my code...
if (!is_array($_POST)){exit "$_POST isn't an array";}
foreach ($_POST as $param => $value){
${$param} = secure($value);
}
//now you have a set of variables that are named exactly as the posted param
//for example, $_POST['personal_info_first_name'] == $personal_info_first_name
if ($payment_method == "Pay by credit card."){
//do stuff that you were gonna do anyways
} else if ($payment_method == "Pay by new credit card.") {
if ($card_number && $expiration_date && $security_code){
//do stuff that you were gonna do anyways
} else {
exit("info missing for credit card transaction");
}
} else {
exit("unknown payment method")
}
function secure($input){
//sanitize user input
}
If you use this code, then it doesn't matter what is null and what isn't within the foreach because anything that's null just won't be made. Then you can use nicer looking code (and probably faster code) to check for anything that is required.
Below is a snippet of PHP that I need to get working, I need to make sure that 3 items are not set already and not === ''
I have the part to make it check if not set but when I try to see if the values are empty as well (I might not even be thinking clearly right now, I might not need to do all this) But I need to make sure that redirect, login_name, and password are all not already set to a value, if they are set to a value I need to make sure that the value is not empty.
Can someone help, when I add in check to see if values are empty, I get errors with my syntax, also not sure if I should have 5-6 checks like this in 1 if/else block like that, please help
I need to check the following:
- $_GET['redirect'] is not set
- $_REQUEST['login_name'] is not set
- $_REQUEST['login_name'] is not != to ''
- $_REQUEST['password'] is not set
- $_REQUEST['password'] is not != to ''
if (!isset($_GET['redirect']) && (!isset($_REQUEST['login_name'])) && (!isset($_REQUEST['password']))){
//do stuff
}
UPDATE
Sorry It is not very clear, I was a bit confused about this. Based on Hobodaves answer, I was able to modify it and get it working how I need it. Below is the code how I need it, it works great like this... So if that can be improved then that is the functionality that I need, I just tested this.
if (!isset($_GET['redirect'])
&& empty($_GET['redirect'])
&& isset($_REQUEST['login_name'])
&& !empty($_REQUEST['login_name'])
&& isset($_REQUEST['password'])
&& !empty($_REQUEST['password'])
) {
echo 'load user';
}
if this was loaded then it will run the login process
login.php?login_name=test&password=testing
If this is loaded then it will NOT run the login process
login.php?login_name=test&password=
if (!isset($_GET['redirect'])
&& !isset($_REQUEST['login_name'])
&& empty($_REQUEST['login_name'])
&& !isset($_REQUEST['password'])
&& empty($_REQUEST['password'])
) {
// do stuff
}
This is exactly what you describe, (not != empty === empty). I think you should edit your question though to explain what you're triyng to do, so we can suggest better alternatives.
Edit:
Your updated question can be simplified as:
if (empty($_GET['redirect'])
&& !empty($_REQUEST['login_name'])
&& !empty($_REQUEST['password'])
} {
// load user
}
A more maintainable solution would be storing each key in an array, and then foreach over it and check if isset or empty. You're not very DRY with your current solution.
The implementation would look someting like:
<?php
$keys = array('login_name', 'password');
foreach($keys as $key)
{
if(!isset($_REQUEST[$key]) || empty($_REQUEST['key'])
// Show error message, kill script etc.
}
// Dot stuff
?>
If a global variable is not set, that is the same as being empty. Thus:
!is_set(($_REQUEST['username'])) is the same as empty($_REQUEST['username'])
So based on your update, you can simplify to:
if (empty($_GET['redirect'])
&& !empty($_REQUEST['login_name'])
&& !empty($_REQUEST['password'])
) {
echo 'load user';
}
please read!
Sorry, the previous answer I gave will not give you what you want. Here is why:
If you use !_REQUEST['password'], it will return true if the password is empty or if it is not set. However if you use if($_REQUEST['password']) it will pass the conditional anytime that global variable is set, even if it is empty.
Therefore I recommend:
$no_redirect = (!$_GET['redirect']);
$login_name = (!$_REQUEST['login_name']) ? false : true;
$password = (!$_REQUEST['login_name']) ? false : true;
if($no_redirect && $login_name && $password) {
echo 'load user';
}
Sorry for the previously bad info.
You could create an array
$array = array(
$_GET['redirect'],
$_GET['redirect'],
$_REQUEST['login_name'],
$_REQUEST['login_name'],
$_REQUEST['password'],
$_REQUEST['password']
);
foreach($array as $stuf)
{
if(!empty($stuff) && $tuff !=0)
//do something
}
I'm doing some validation now in PHP, and I'm running allot of conditional statements, for example:
if ($this->email->isValid($email))
return false;
if ($this->username->isValid($username))
return false;
ect..
Is there a nice way to do this? Or do I just run ten If statements like the ones above?
I can't use switch obviously, but I'm looking for that type of solution..
P.S... I'm using Zend Framework for validation
You could OR them like this:
if(cond1||
cond2||
cond3||
cond4)
{
return false;
}
Doing something like this is called a Guardian clause. It can be improved so clauses that return the same value should be grouped together.
if ($this->email->isValid($email) || $this->username->isValid($username))
{
return false;
}
Or like this, if there are many (btw how I format the if is just so it can read better, any other way should be fine as well)
if (
$this->email->isValid($email) ||
$this->username->isValid($username) ||
$this->somethingelse()
)
{
return false;
}
If this is data from a form, take a look at Zend_Form, as recommended by a poster in your other question
I posted some example code which details adding validators to form elements
Just make sure that you put the most obvious validation at the top, so if its going to fail it will trip before it runs through every statement. Also, I don't like if statements without curly brackets, but then thats just a matter of opinion.
if ($this->email->isValid($email) ||
$this->username->isValid($username))
return false;
It is always good to use some var than multiple returns
In case these are the only return conditions. We dont need to check for all conditions. like check only for true conditions return false by default or vice-versa.
$result = false; //return false by default.
if (cond1 || cond2) { //check only for conditions which result in returning true. :)
$result = true;
}
return $result;
Cheers,
-Ratnesh
I would make them data members of my class. Obviously here you will have to have a form driven class. So here for example the email could be wrapped into a class and initialised with in the constructor of the class that has them as member variables. Now the email wrapper class will do validation for email on initialisation/construction.
IMHO that would look less cluttered and you can wrap up any validation or specific methods to the email-wrapper class.
I know it might be a sledge hammer in some context; so choose wisely!
Maybe something like this:
foreach( $form->getElements as $element => $value )
{
if( !$element->isValid( sanitize($value))){
return false;
}
}
BUT if you are using ZF this is your oneliner answer because you check all the form in one not individual fields:
$form = new My_Zend_Form(); // in the controller action that you send the form to
if ( $form->isValid($_POST)) {
// Success /// do whatever you want with the data
$data = $form->getValues();
} else {
//error
}
Do something like this:
$errlvl = 0;
if($errlvl == 0 && $this->email->isValid($email)){
$errlvl++;
}
if($errlvl == 0 && $this->username->isValid($username)){
$errlvl++;
}
// your validation list keeps going
if($errlvl > 0){
return false;
}
this will
Reduce redundancy because if there's an error in front, the following will not be checked.
you can keep adding on to the list
if you want to know how many errors occurred, you can remove $errlvl == 0 in the statements
Add all objects to an array and the iterate it (I guess you or Zend are using an interface "validator" or something like that each component (username, email, etc) implements the "isValid" method):
$validators = array();
$validators[] = $this->email;
$validators[] = $this->username;
foreach ($validators as $validator)
{
if (!$validator->isValid())
{
return false;
}
}