How can I call a function specified in a GET param? - php

I have a simple link like so: Accept
The idea is that this will run a function called wp_accept_function and pass in the id of 10 how do I do this? Thanks
Here is the code I have so far, but I feel I'm going wrong and need to pass the number into the function and then be able to use it within the function. Thanks
if ( isset ( $_GET ['wp_accept_function'] ) )
{
function wp_accept_favor ( $id )
{
// JAZZ
}
}

I think you want this:
First you need to define the function.
function wp_accept_favor($id) {
// do something
}
Then, you have to check if the parameter is set and call the function.
if (isset($_GET['wp_accept_function'])) {
// call the function passing the id casted to an integer
wp_accept_favor((int)$_GET['wp_accept_function']);
}
The cast to (int) is for avoid passing a non-integer type for wp_accept_favor() function, but you can handle it as you want.

If you are trying to build something generic...
// Add a white list of functions here which can be called via GET.
$safeFunctions = array('wp_accept_function');
foreach($_GET as $function => $argument) {
if (in_array($function, $safeFunctions)
AND function_exists($function)) {
$function($argument);
}
}
However, make sure you have a whitelist of safe functions, otherwise your app will no doubt have security issues.

Related

Extracting a parameter from a URL in WordPress

I am trying to pass a parameter to a WordPress site using a URL - for instance:
www.fioriapts.com/?ppc=1 will be the URL.
I am intending to write a function in the functions.php file but the mechanics of how to extract a parameter in WordPress is beyond me. How can it be done?
I am finding a lot of examples on how to add a parameter to a URL using the function add_query_arg() but have found nothing on how to extract a parameter.
Why not just use the WordPress get_query_var() function? WordPress Code Reference
// Test if the query exists at the URL
if ( get_query_var('ppc') ) {
// If so echo the value
echo get_query_var('ppc');
}
Since get_query_var can only access query parameters available to WP_Query, in order to access a custom query var like 'ppc', you will also need to register this query variable within your plugin or functions.php by adding an action during initialization:
add_action('init','add_get_val');
function add_get_val() {
global $wp;
$wp->add_query_var('ppc');
}
Or by adding a hook to the query_vars filter:
function add_query_vars_filter( $vars ){
$vars[] = "ppc";
return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );
When passing parameters through the URL you're able to retrieve the values as GET parameters.
Use this:
$variable = $_GET['param_name'];
//Or as you have it
$ppc = $_GET['ppc'];
It is safer to check for the variable first though:
if (isset($_GET['ppc'])) {
$ppc = $_GET['ppc'];
} else {
//Handle the case where there is no parameter
}
Here's a bit of reading on GET/POST params you should look at: http://php.net/manual/en/reserved.variables.get.php
EDIT: I see this answer still gets a lot of traffic years after making it. Please read comments attached to this answer, especially input from #emc who details a WordPress function which accomplishes this goal securely.
You can try this function
/**
* Gets the request parameter.
*
* #param string $key The query parameter
* #param string $default The default value to return if not found
*
* #return string The request parameter.
*/
function get_request_parameter( $key, $default = '' ) {
// If not request set
if ( ! isset( $_REQUEST[ $key ] ) || empty( $_REQUEST[ $key ] ) ) {
return $default;
}
// Set so process it
return strip_tags( (string) wp_unslash( $_REQUEST[ $key ] ) );
}
Here is what is happening in the function
Here three things are happening.
First we check if the request key is present or not. If not, then just return a default value.
If it is set, then we first remove slashes by doing wp_unslash. Read here why it is better than stripslashes_deep.
Then we sanitize the value by doing a simple strip_tags. If you expect rich text from parameter, then run it through wp_kses or similar functions.
All of this information plus more info on the thinking behind the function can be found on this link https://www.intechgrity.com/correct-way-get-url-parameter-values-wordpress/
In the call back function, use the $request parameter
$parameters = $request->get_params();
echo $parameters['ppc'];

php-function, passing value to specific argument?

Can pass a value to specific argument in function ?
function fun1($a,$b)
{
echo $b;
}
#fun1(123);
Functions can be defined so that they do not require all parameters. For example:
function foo($a, $b = 2) {
echo $a + $b;
}
foo(1); //gives 3
Read about default function values here
However, you cannot pass in later parameters without specifying earlier ones. Some simple programming-function-parameters-basics... when you do foo($b) the function has no idea that the variable was named b... It just gets the data; usually a primitive type (in this case an int) or a reference.
You haven't specified how you're using these variables, so you may want to give a dummy value like "-1" to $a (and handle it in your function) (foo(-1, 123)), or rewrite your function so that $a is the second parameter with the default value. (function foo($b, $a = NULL))
That's why you must pass the variables in order; the function assumes you're using it right, and it lines up the values passed with the function definition. function foo($a, $b) means "I'm assuming I should associate your first value with a and your second value with b)".
With your original example function foo($a, $b):
No context, so I would just say do this function foo($b, $a = some_default_value). However, I'm assuming you're using $a and $b equally so you could check to see if it was some default-invalid-value and act on it. However, if your function performs different tasks depending on the (number of) parameters passed, you probably want to separate your function.
If you insist on not switching the order, you could call foo(-1, 123) with a dummy value and check it. Again though, same problem as above
Edit: You've given another example foo($a, $b, $c) and you said you want to do foo($b) to update the middle value. See the explanation in the first paragraph about how a function knows what parameter is what.
If you mean you want to pass an arbitrary set of variables to a function and it knows which ones it got? Again I don't think this is the best practice (you'll need to give us more detail about how you're using this) but you could pass an associative array:
function foo($arr) {
if (isset($arr['a'])) {
echo $a;
}
if (isset($arr['b'])) {
echo $b;
}
if (isset($arr['c'])) {
echo $c;
}
}
foo(array('b' => 123));
I feel horrible after writing this function :P
<?php
function FUN1($a, $b)
{
echo "HI";
echo $b;
} //$_a= 123; //error_reporting (E_ALL ^ E_NOTICE ^ E_WARNING); //$b=23; echo #FUN1(123);//it gives HI123
?>
I formatted your function. Firstly, when I tried that call it doesn't give me "HI123". Secondly, # is bad practice and really slows down the code. Thirdly, you don't echo FUN1 since it doesn't return anything; your function prints the stuff itself.
You (your student) are/is going in the wrong direction. As I said in my comment, functions already have a beautiful way of sorting out the parameters. Instead of trying to do something funky and work around that, just change your approach.
The example above has no real use and I'm sure in actual code you should just write different functions when you're setting different variables. like setA($a) setB($b) setC($c) setAll($a, $b, $c) and use them accordingly. Arrays are useful for easy variable length functions, but if you're checking each tag to do something, then something's wrong.
If you only want to pass one argument, you could make a wrapper function like this:
function PassOne($arg)
{
fun1(NULL,$arg);
}
function fun1($a,$b)
{
echo $b;
}
Forgive any inaccuracies. It's been a while since I coded in PHP.
If you want to ensure the order of arguments, you can pass a single array as an argument.
$args = array(
'name' => 'Robert',
'ID' => 12345,
'isAdmin' => true
);
example($args);
function example($args)
{
echo $args['name']; // prints Robert
echo $args['ID']; // prints 12345
echo $args['isAdmin']; // prints true
}
Using this approach, you can also hard-code default values into the function, replacing them only when they're provided in the argument array. Example:
$args = array(
'name' => 'Robert',
'ID' => 12345
// Note that I didn't specify whether Robert was admin or not
);
example($args);
function example($args)
{
$defaultArgs = array(
'name' => '',
'ID' => -1,
'isAdmin' => false // provides a default value to incomplete requests
);
// Create a new, mutable array that's a copy of the default arguments
$mixArgs = $defaultArgs;
// replace the default arguments with what was provided
foreach($args as $k => $v) {
$mixArgs[$k] = $v;
}
/*
Now that we have put all the arguments we received into $mixArgs,
$mixArgs is mix of supplied values and default values. We can use
this fact to our advantage:
*/
echo $mixArgs['name']; // prints Robert
// if ID is still set to the default value, the user never passed an ID
if ($mixArgs['ID'] == -1) {
die('Critical error! No ID supplied!'); // use your imagination
} else {
echo mixArgs['ID']; // prints 12345
}
echo mixArgs['isAdmin']; // prints false
// ... etc. etc.
}
2018's PHP syntax and defaults
function example($args=[], $dftArgs=['name'=>'', 'ID' => -1, 'isAdmin'=>false])
{
if (is_string($args))
$args = json_decode($args,true); // for microservice interoperability
$args = array_merge($dftArgs,$args);
// ... use $args
}
// PS: $dftArgs as argument is not usual, is only a generalization
No.
But by convention you can skip arguments to built in functions by passing NULL in that position:
fun1(NULL, 123);
Obviously this is doesn't make sense for everything - for example this makes no sense:
$result = strpos(NULL, 'a string');
For user defined functions, it's up to you to handle the arguments in whatever way you see fit - but you might find func_get_arg()/func_get_args() useful for functions that use an indeterminate number of arguments.
Also, don't forget you can make arguments optional by defining default values:
function fun ($arg = 1) {
echo $arg;
}
fun(2); // 2
fun(); // 1
Note that default values can only be defined on the right-most arguments. You cannot give an argument a default value if an argument to its right does not have one. So this is illegal:
function fun ($arg1 = 1, $arg2) {
// Do stuff heere
}

function simplify argument list

When calling a function is there a way to simplify the argument list? Instead of using $blank.
$subscribe=1;
$database->information($blank,$blank,$blank,$blank,$blank,$blank,$subscribe,$blank,$blank,$blank,$blank,$blank);
function information ($search,$id,$blank,$category,$recent,$comment,$subscribe,$pages,$pending,$profile,$deleted,$reported) {
//code
}
You could pass in an array with the specified keys, and merge it with an array of default values
So instead of
function foo($arg1 = 3, $arg2 = 5, $arg3 = 7) { }
You'd have
function foo($args) {
$defaults = array(
'arg1' => '',
'arg2' => null,
'arg3' => 7
);
// merge passed in array with defaults
$args = array_merge($defaults, $args);
// set variables within local scope
foreach($args as $key => $arg) {
// this is to make sure that only intended arguments are passed
if(isset($defaults[$key])) ${$key} = $arg;
}
// rest of your code
}
Then call it as
foo(array('arg3' => 2));
Yes, pass an array instead, or refactor. A long arguments list is usually a bad smell.
function information(array $params) {....
information(array('search'=>'.....
Twelve arguments are generally too many for one function. It's likely that your code could be simplified (including the argument lists getting shorter) by refactoring function information which looks likely to be a monster.
Stopgap measures you can use in the meantime are
adding default argument values
making the function accept all its arguments as an array
Both of the above will require you to visit all call sites for the function for review and modification.
Adding default arguments is IMHO the poor choice here, as by looking at the example call it seems that you would need to make all arguments default, which in turn means that the compiler will never warn you if you call the function wrongly by mistake.
Converting to an array is more work, but it forces you to rewrite the calls in a way that's not as amenable to accidental errors. The function signature would change to
function information(array $params)
or possibly
function information(array $params = array())
if you want all parameters to be optional. You can supply defaults for the parameters with
function information(array $params) {
$defaults = array('foo' => 'bar', /* ... */);
$params += $defaults; // adds missing values that have defaults to $params;
// does not overwrite existing values
To avoid having to rewrite the function body, you can then use export to pull out these values from the array into the local scope:
export($params); // creates local vars
echo $foo; // will print "bar" unless you have given another value
See all of this in action.
You can make it so the function wil automatically fill the variable with a given value like an empty string:
function information ($subscribe, $search="", $id="", $blank="", $category="", $recent="", $comment="", $pages="", $pending="", $profile="", $deleted="", $reported="") {
//code
}
Yes, there are several ways:
Accept an associative array as a single argument, and pass what you need to that. Throw exceptions if a critical argument is missing.
Place critical arguments at the head of the function definition, and optional ones at the end. Give them a default value so that you don't have to declare them.
Recosinder your function. 12 arguments is much too many for one function. Consider using a class/object, or dividing the work between different functions.
Several ways:
function test($input = "some default value") {
return $input; // returns "some default value"
}
function test($input) {
return $input;
}
test(NULL); // returns NULL
function test() {
foreach(func_get_args() as $arg) {
echo $arg;
}
}
test("one", "two", "three"); // echos: onetwothree

PHP - Inherit function default value

I have a function that look like this:
function test($arg1 = 'my_value', $arg2 = 'second')
{
}
When I call it I only want to set the second value to something different, like this:
test(inherit, 'changed value');
I found out that it is possible to add this line to my function (when my "inherit" is changed to null):
$arg1 = ( is_null( $arg1 ) ? 'my_value' : $arg1 );
Is there a better way, a nicer way to solve it?
Depending on the nature and number of your parameters it may be reasonable to use named parameters (at least emulated):
function xyz($args) {
$args += array(
'x' => 'default',
'q' => 'default 2',
// ...
);
// ...
}
xyz(array('q' => 'hehe, not default'));
The way you have solved it is actually pretty usable.
The other way is to pass the same value as the default value every time on the function call.
If that is structural, then you have to reconsider the function.
Make two different functions:
// Full function
function testex($arg1 = 'my_value', $arg2 = 'second')
{
}
// Shorthand when just argument 2 is needed
function test2($arg2 = 'second')
{
return testex('my_value', $arg2);
}
That way, you don't have to pass null to the first parameter when you don't need to.
You will have to flip them, you can't leave the first value to be blank,
Set the first value and let the second one be the default value;
UPDATE:
If you want to have dynamic length to your argument consider using the func_get_args();
function something() {
$args = func_get_args();
....
}
then you can test your arguments for different value or datatype to make them do whatever yuo please

PHP Optional Parameters - specify parameter value by name?

I know it is possible to use optional arguments as follows:
function doSomething($do, $something = "something") {
}
doSomething("do");
doSomething("do", "nothing");
But suppose you have the following situation:
function doSomething($do, $something = "something", $or = "or", $nothing = "nothing") {
}
doSomething("do", $or=>"and", $nothing=>"something");
So in the above line it would default $something to "something", even though I am setting values for everything else. I know this is possible in .net - I use it all the time. But I need to do this in PHP if possible.
Can anyone tell me if this is possible? I am altering the Omnistar Affiliate program which I have integrated into Interspire Shopping Cart - so I want to keep a function working as normal for any places where I dont change the call to the function, but in one place (which I am extending) I want to specify additional parameters. I dont want to create another function unless I absolutely have to.
No, in PHP that is not possible as of writing. Use array arguments:
function doSomething($arguments = array()) {
// set defaults
$arguments = array_merge(array(
"argument" => "default value",
), $arguments);
var_dump($arguments);
}
Example usage:
doSomething(); // with all defaults, or:
doSomething(array("argument" => "other value"));
When changing an existing method:
//function doSomething($bar, $baz) {
function doSomething($bar, $baz, $arguments = array()) {
// $bar and $baz remain in place, old code works
}
Have a look at func_get_args: http://au2.php.net/manual/en/function.func-get-args.php
Named arguments are not currently available in PHP (5.3).
To get around this, you commonly see a function receiving an argument array() and then using extract() to use the supplied arguments in local variables or array_merge() to default them.
Your original example would look something like:
$args = array('do' => 'do', 'or' => 'not', 'nothing' => 'something');
doSomething($args);
PHP has no named parameters. You'll have to decide on one workaround.
Most commonly an array parameter is used. But another clever method is using URL parameters, if you only need literal values:
function with_options($any) {
parse_str($any); // or extract() for array params
}
with_options("param=123&and=and&or=or");
Combine this approach with default parameters as it suits your particular use case.

Categories