I'm coding a worksheet app for a printer company.
I'm getting flood of forms.
For every single input field I have to check if the $_POST variables are set, and if, so echo back the value. (In case of some error, for example after a validation error, the user shouldn't retype the whole form)
Sample code:
if(isset($_POST['time'])&&!empty($_POST['time'])){echo $_POST['time'];}
I had to implement this about a hundred times.
So I tried to figure out some kind of function to make this simple and readable.
Something like this:
function if_post_echo($key, $default = "") {
if(isset($_POST[$key])&&!empty($_POST[$key])){
echo $_POST[$key];
}else{
echo $default;
}
}
But this wont work.
I have tried to pass in the $_POST for the $key variable like this:
if_post_echo($_POST['time'])
function if_request_echo($key, $default = "") {
if(isset($key)&&!empty($key)){
echo $key;
}else{
echo $default;
}
}
And I also tried this:
function if_request_echo($key, $default = null) {
return isset($_REQUEST[$key])&&!empty($_REQUEST[$key]) ? $_REQUEST[$key] : $default;
}
Without any reasonable outcome.
The question:
How can I forge a function that looks for the necessary $_POST variable and returns it or if its unset then returns an empty string.
And is there a way to do this for $_GET and $_REQUEST, too? (Or simply duplicate?)
Your PHP testing function:
<?php
function test_req($key, $default = '') {
if(isset($_REQUEST[$key]) and
!empty($_REQUEST[$key])) {
return $_REQUEST[$key];
} else {
return $default;
}
}
?>
Then in your form HTML:
<input name="my_field" value="<?php echo htmlentities(test_req('my_field')); ?>" />
$_REQUEST (linked) is a PHP super global that contains both POST ($_POST) and GET ($_GET) request parameters.
If you only want to capture POST request parameters then it would be:
<?php
function test_req($key, $default = '') {
if(isset($_POST[$key]) and
!empty($_POST[$key])) {
return $_POST[$key];
} else {
return $default;
}
}
?>
For example.
If you have a large amount of fields, I would propose that you also use an array of defaults:
$defaults = array(
"time" => "default",
"name" => "enter name here",
"text..." => "...",
);
$fields = array_filter($_POST) + $defaults;
$fields will then contain a list of form values with either the POST data or a preset default. No isset, see?
array_filter man page particularly: If no callback is supplied, all entries of input equal to FALSE will be removed. Goes some way to explaining the working behind this solution.
This should work:
function if_post_echo($key, $default = ''){
if(isset($_POST[$key]) AND !empty($_POST[$key]){
echo $_POST[$key];
}
echo $default;
}
If you're having problems I recommend that you try var_dump($_POST) or print_r($_POST) to see if everything has been properly posted.
Just to note, this is redundant:
isset($_POST[$key]) && !empty($_POST[$key])
An unset variable is going to always be "empty", so isset() is implied in your empty() call.
For your logic you can achieve the same result with just:
!empty($_POST[$key])
Your first function works perfectly to me.
Why do you think it doesn't work?
However, a better variant would be
function _post($key, $default = "") {
if(isset($_POST[$key])){
return $_POST[$key];
}else{
return $default;
}
}
To use it :
echo $_post($key); // You could define the message as a second parameter.
function requireArray( $array, $required ) {
foreach( $required as $k=>$v ) {
if ( !isset($array[$k]) || empty($array[$k]) )
return false;
}
return true;
}
#call like this:
requireArray($_POST, array('time', 'username', 'foo'));
If you want to know specifically:
function missingFrom( $array, $required ) {
$r = array();
foreach( $required as $k ) {
if ( !isset($array[$k]) || empty($array[$k]) )
$r[] = $k;
}
return $r;
}
Called like previous function.
Your method seems to work fine here:
function if_post_echo($key, $default = "") {
if(isset($_POST[$key])&&!empty($_POST[$key])){
echo $_POST[$key];
}else{
echo $default;
}
}
I made a simple input with the name test and the form method is POST and using echo if_post_echo('test');.
It posted on the page what was in the text box.
This feature is being added in PHP 7 as the "Null Coalesce Operator" using two question marks:
echo ($_GET['message'] ?? 'default-if-not-set');
https://wiki.php.net/rfc/isset_ternary
Related
i would like to create a php function. Basically, that's what i've :
if(isset($myvariable) AND $myvariable == "something")
{
echo 'You can continue';
}
and that's what i want :
if(IssetCond($myvariable, "something"))
{
echo 'You can continue';
}
I want function that tests if the variable exists, and if it does it tests if the condition is respected. Otherwise it returns false.
I've tried a lot of things, but i still have a problem when $myvariable doesnt exist.
function IssetCond($var, $value){
if(isset($var) AND $var == $value)
{
return true;
}
else
{
return false;
}
}
When $myvariable exists and whether the condition is respected or not, it works.
If you have some minutes to help me i'll be grateful.
Thanks
Thomas
You can pass just the name, not the var, and use variable variable
function IssetCond($var, $value){
return (isset($$var) AND $var == $value);
}
Used like
if(IssetCond('myvariable', "something"))
{
echo 'You can continue';
}
Your idea it good but if you pass a variable to your function you pass the value of that variable to your function. If your variable is not set before you get an error that you try to prevent with your function.
You could pass the reference to the function but that would cause the same problem if you variable is not set before.
I think i found the answer, thanks to #Teko
$a = "3";
function IssetCond($var, $value){
global $$var;
if (isset($$var) && $$var == $value)
{ return true;}
return false;
}
if(IssetCond('d', 4))
{
echo 'first test'; // wont display
}
if(IssetCond("a", 3))
{
echo 'second test'; // will display
}
if(IssetCond("a", 4))
{
echo 'third test'; // wont display
}
Thanks to everyone !
function valueFromGetOrPost($parameter)
{
$shvalue=NULL;
if ($_GET[$parameter])
{
$shvalue=$_GET[$parameter];
}
else if (isset($_POST[$parameter]))
{
$shvalue=$_POST[$parameter];
}
return $shvalue;
}
say by using filter_input
Basically the code check whether a parameter exist either in GET or POST. And then return the value of the parameter.
I think this must be so common it should be there by some built in function already
Use $_REQUEST (documentation).
An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE.
So your code will look like:
function valueFromGetOrPost($parameter)
{
$shvalue=NULL;
if ($_REQUEST[$parameter])
{
$shvalue=$_REQUEST[$parameter];
}
return $shvalue;
}
You could use fast return to simplify it a bit, i.e
function valueFromGetOrPost($parameter){
$shvalue=NULL;
if (isset($_GET[$parameter])){
return $_GET[$parameter];
} else if (isset($_POST[$parameter])){
return $_POST[$parameter];
}
}
Or, you could use a ternary operator, since you're returning NULL anyway if neither are set:
function valueFromGetOrPost($parameter){
$shvalue = (isset($_GET[$parameter]) ? $_GET[$parameter] : $_POST[$parameter]);
return $shvalue;
}
Here is my proposal, using the filter_input() function:
function valueFromGetOrPost($parameter)
{
$value = ($getValue = filter_input(INPUT_GET, $parameter))
? $getValue
: filter_input(INPUT_POST, $parameter);
return ($value) ? $value : NULL;
}
I have the following function to check the array's keys
public function check($arr, $key, $default = NULL) {
return isset($arr[$key]) && !empty($arr[$key]) ? $arr[$key] : $default;
}
$this->check($info, 'location'); //it's working
$this->check($info['birthday'], 'year'); //it's working
$this->check($_POST, 'email'); //it's working
$this->check($_POST, 'password'); //it's working
everything is ok until multidimensional array appears
Notice: Array to string conversion in
change your function code to:
public function check($arr, $key, $default = NULL) {
return isset($arr[$key]) ? $arr[$key] : $default;
}
if you still want to check for empty value (though isset is enough):
public function check($arr, $key, $default = NULL) {
return isset($arr[$key]) && (!empty($arr[$key]) || is_array($arr[$key])) ? $arr[$key] : $default;
}
Not 100% sure what are you looking for but please notice that if you have email[][] field, when you return $arr[$key] you are returning an array. So you have to check if $arr[$key] is an array before returning its value.
public function check($arr, $key, $default = NULL) {
if( isset($arr[$key]) && !empty($arr[$key]) || is_array($arr[$key])) {
if(is_array($arr[$key])) {
//apply here your second level check condition
} else return $arr[$key]; // returns its value (if it's not an array)
} else return $default;
}
Hope it helps
Instead, if you're trying to build a function checking recursively if $key is contained somewhere in a multidimensional array, you have to do otherwise (that's why I wrote I'm not 100% sure what you're looking for)
? $arr[$key]
In the above code you are using $_POST['email'] (which is an array) as a string.
What I'm trying to do is write one function to reuse vs writing out an if statement every time.
If statement:
if (!isset($value)){ echo 'null';}else{ echo $value;}
Function:
function isSetTest($value){
if ( !isset($value)){
$value = NULL;
}
return $value;
}
echo'name'.isSetTest($value);
Function works but I still get the "undefined" error message which is what i'm trying to avoid.
Pass by reference instead, so that no processing of the variable is done until you want it:
function isSetTest(&$value) { // note the &
if (!isset($value)) {
$value = NULL;
}
return $value;
}
You can shorten this a bit:
function isSetTest(&$value) {
return isset($value) ? $value : null;
}
I have a function that does something similar, except you can provide an optional default value in the case that the variable is not set:
function isset_or(&$value, $default = null) {
return isset($value) ? $value : $default;
}
The problem in your code is, that you still pass an undefined variable to your function, so that's why you still get your undefined error.
One way to solve this now, is that you pass your variable name as a string and then use variable variables, to check if it exists, e.g.
function isSetTest($value){
global $$value;
if ( !isset($$value)){
$$value = NULL;
}
return $$value;
}
echo'name'.isSetTest("value");
Demo
I find in my PHP pages I end up with lines and lines of code that look like this:
$my_id = isset($_REQUEST['my_id']) ? $_REQUEST['my_id'] : '';
$another_var = isset($_REQUEST['another_var']) ? $_REQUEST['another_var'] : 42;
...
Is there a better, more concise, or more readable way to check this array and assign them to a local variable if they exist or apply a default if they don't?
EDIT: I don't want to use register_globals() - I'd still have the isset problem anyway.
How about wrapping it in a function?
<?php
function getPost($name, $default = null) {
return isset($_POST[$name]) ? $_POST[$name] : $default;
}
a better method might be to create a singleton/static class to abstract away the details of checking the request data.
Something like:
class Request {
private $defaults = array();
private static $_instance = false;
function getInstance () {
if (!self::$_instance) {
$c = __CLASS__;
self::$_instance = new $c;
}
return self::$_instance;
}
function setDefaults($defaults) {
$this->defaults = $defaults;
}
public function __get($field) {
if (isset($_REQUEST[$field]) && !empty($_REQUEST[$field])) {
return $_REQUEST['field'];
} elseif (isset($this->defaults[$field])) {
return $this->defaults[$field];
} else {
return ''; # define a default value here.
}
}
}
you can then do:
# get an instance of the request
$request = Request::getInstance();
# pass in defaults.
$request->setDefaults(array('name'=>'Please Specify'));
# access properties
echo $request->name;
echo $request->email;
I think this makes your individual scripts loads cleaner and abstracts away the validation etc. Plus loads of scope with this design to extend it/add alternate behaviours, add more complicated default handling etc etc.
First, use $_POST for POSTed variables. $_REQUEST is a mashup of many different incoming variables, not just $_POST and could cause problems.
One solution for your question would be to create a function that handles the isset() logic.
function ForceIncomingValue($Key, $Default) {
if (!isset($_POST[$Key]))
return $Default;
else return $_POST[$Key];
}
first of all, NEVER use the $_REQUEST variable, it'll lead to bugs and other problems during development
function getPOST($key) {
if(isset($_POST[$key])) {
return $_POST[$key];
}
}
note that this code leaves the variable empty when $_POST[$key] was not set
you could also adapt that code to enable you to instead provide you with a (sensible) default when the value could not be loaded.
function getPOST($key, $default = NULL) {
if(isset($_POST[$key])) {
return $_POST[$key];
} else {
return $default;
}
}
Is the set of variables you're expecting known at the time of the script's writing, or do you want to do this for an arbitrary set of values? If the former is true, you could do something like this:
# This array would hold the names of all the variables you're expecting
# and a default value for that variable name
$variableNames = array (...);
foreach ($variableNames as $key => $default) {
if (isset ($_REQUEST[$key])) $$key = $_REQUEST[$key];
else $$key = $default;
}
Basically, this takes advantage of PHP's ability to evaluate variables to create other variables (hence the double-dollar for $$key--this means create a new variable whose name is the value of $key).
I haven't yet come up with a good solution to the latter situation.
PHP's null coalescing operator!
$username = $_GET['user'] ?? 'nobody';
For a lot of variables, with a requirement check, anyone is free to use my expect function.