Is it possible to use php's func_get_args() to catch 'post(ed)' data from an Ajax function call? (Currently using json to post data).
Hypothetical Ajax call posting data:
.
url: '.../.../...?action=function'
data: { someString: someString }
.
.
php:
function() {
$arg_list = func_get_args();
foreach( $arg_list as ....) {
.
.
}
}
i'm currently using isset( $_POST['someString'] ) but I was wondering if i can achieve the same using func_get_args().
Currently, func_get_args isn't catching anything from the ajax call. The 'post' line is directly below this chunk of code and is verifying that ajax has correctly sent the function the correct data. However, func_get_args isn't actually displaying anything on a var_dump. What am i not doing?
Many Thanks
Unfortunately not. func_get_args() looks for function arguments in php stack, while $_POST and $_GET look for http request header parameters.
But if you just want to iterate through $_POST parameters without knowing their names, try this:
foreach( $_POST as $pars ) {
if( is_array( $pars ) ) {
foreach( $pars as $par ) {
echo $par;
}
}
else { echo $pars;
}
}
You should try something like that :
function myAjaxFunction() {
$args = $_POST;
if (sizeof($args) > 0)
{
foreach ($arg_list as $arg) {
//
}
}
}
Related
I have several interchangeable functions with different numbers of arguments, for example:
function doSomething1($arg1) {
…
}
function doSomething2($arg1, $arg2) {
…
}
I would like to pass a certain number of these functions, complete with arguments, to another handling function, such as:
function doTwoThings($thing1, $thing2) {
$thing1();
$thing2();
}
Obviously this syntax is not correct but I think it gets my point across. The handling function would be called something like this:
doTwoThings(‘doSomething1(‘abc’)’, ‘doSomething2(‘abc’, ‘123’));
So the question is, how is this actually done?
From my research it sounds like I may be able to "wrap" the "doSomething" function calls in an anonymous function, complete with arguments and pass those "wrapped" functions to the "doTwoThings" function, and since the anonymous function doesn't technically have arguments they could be called in the fashion shown above in the second code snippet. The PHP documentation has me confused and none of the examples I'm finding put everything together. Any help would be greatly appreciated!
you could make use of call_user_func_array() which takes a callback (eg a function or class method to run) and the arguments as an array.
http://php.net/manual/en/function.call-user-func-array.php
The func_get_args() means you can feed this funciton and arbitary number of arguments.
http://php.net/manual/en/function.func-get-args.php
domanythings(
array( 'thingonename', array('thing','one','arguments') ),
array( 'thingtwoname', array('thing','two','arguments') )
);
funciton domanythings()
{
$results = array();
foreach( func_get_args() as $thing )
{
// $thing[0] = 'thingonename';
// $thing[1] = array('thing','one','arguments')
if( is_array( $thing ) === true and isset( $thing[0] ) and is_callable( $thing[0] ) )
{
if( isset( $thing[1] ) and is_array( $thing[1] ) )
{
$results[] = call_user_func_array( $thing[0], $thing[1] );
}
else
{
$results[] = call_user_func( $thing[0] );
}
}
else
{
throw new Exception( 'Invalid thing' );
}
}
return $results;
}
This would be the same as doing
thingonename('thing','one','arguments');
thingtwoname('thing','two','arguments');
On my WordPress page I have created a shortcode function which gets a parameters from the URL of the post. So, I have created this simple function and added the following code to the theme's file function.php:
function getParam($param) {
if ($param !== null && $param !== '') {
echo $param;
} else {
echo "Success";
}
}
add_shortcode('myFunc', 'getParam');
And I know I have to add this shortcode to posts and pages using (in my case) [myFunc param=''].
Usually, I would get the value of the parameter from the URL using <?php $_GET['param'] ?>, but in this case I don't know how to send this PHP code to the shortcode function.
For example, I doubt I can write [myFunc param=$_GET['param']].
A shortcode like this:
[myFunc funcparam="param"]
Is not needed here, unless the called parameter is changing with the posts.
Let's say you have this URL:
http://example.com?param=thisparam
To get the value of 'param' by using the shortcode described above, your function in functions.php should look something like this:
function sc_getParam() {
// Get parameter(s) from the shortcode
extract( shortcode_atts( array(
"funcparam" => 'funcparam',
), $atts ) );
// Check whether the parameter is not empty AND if there is
// something in the $_GET[]
if ( $funcparam != '' && isset( $_GET[ $funcparam ] ) ) {
// Sanitizing - this is for protection!
$thisparam = sanitize_text_field( $_GET[ $funcparam ] );
// Returning the value from the $_GET[], sanitized!
return $thisparam;
}
else {
// Something is not OK with the shortcode function, so it
// returns false
return false;
}
}
add_shortcode( 'myFunc', 'sc_getParam' );
Look up these references:
WordPress Shortcodes: A Complete Guide - tutorial on creating shortcodes
Validating Sanitizing and Escaping User Data - sanitizing
If you need get the parameters you can:
function getParam($arg) {
if (isset($arg) &&
array_key_exists('param', $arg ) &&
$arg['param'] != '')
{
return $_GET[$arg['param']]; // OR get_query_var($arg['param']);
}
else
return "Success";
}
add_shortcode('name', 'getParam');
Do it this way:
function getParam($data)
{
$var = $_GET[$data['param']];
if ($var !== null && $var !== '')
{
echo "True: " . $var;
}
else echo "False: " . $var;
}
And call it by: [myFunc param=whatever]
You shouldn't call a function in the shortcode.
For better understanding, I changed your code just a little bit, but beware this is not secure and clean.
Im working on a register function that will register users into the database.
I want a checker in that function that checks if any of the arguments are empty. I've simplified the problem, so this is not the retail look.
<?php
create_user($_POST["username"], $_POST["epost"]);
function create_user($username, $epost){
// Pull all the arguments in create_user and check if they are empty
// Instead of doing this:
if(empty($username) || empty($epost)){
}
}
Reason for making this is so i can simply add another argument to the function and it checks automatically that it isnt empty.
Shorted question:
How do I check if all the arguments in a function isnt empty?
function create_user($username, $epost){
foreach(func_get_args() as $arg)
{
//.. check the arg
}
}
You can use array_filter and array_map functions also.
For example create a function like below
<?php
function isEmpty( $items, $length ) {
$items = array_map( "trim", $items );
$items = array_filter( $items );
return ( count( $items ) !== (int)$length );
}
?>
the above function accepts two parameters.
$items = array of arguments,
$length = the number of arguments the function accepts.
you can use it like below
<?php
create_user( $_POST["username"], $_POST["epost"] );
function create_user( $username, $epost ) {
if ( isEmpty( func_get_args(), 2 ) ) {
// some arguments are empty
}
}
?>
I want to apply addslashes() to all the post elements got through
$this->input->post('my_var');
How can I do that ? Is there any feature like filters under wordpress for this ?
I think you want something global. My idea is to edit the global post function in the codeigniter to use addslashes on everything. You can find that function in:
/yourfolder/system/core/Input.php
You can escape it by setting it global.
function post($index = NULL, $xss_clean = FALSE)
{
// Check if a field has been provided
if ($index === NULL AND ! empty($_POST))
{
$post = array();
// Loop through the full _POST array and return it
foreach (array_keys($_POST) as $key)
{
$post[$key] = addslashes($this->_fetch_from_array($_POST, $key, $xss_clean));
}
return $post;
}
return addslashes($this->_fetch_from_array($_POST, $index, $xss_clean));
}
Although I don't really find it as good solution to modify the global functions this should do the trick in your case.
Edit: I see that input->post already does that and you would not need to add that function additionally.
//first function
function insertdigit(){
$userdigit=5;
$flag = $this->usermodel->userdigitmodel($userdigit);
$value = array(
'result' => $flag
);
echo json_encode($value);
if ($flag == true) {
return $userdigit;
} else {
}
}
//second function
function usedigit(){
$data['userdigit']=$this->insertdigit();
}
but i get {"result":true} goes back to the function? how to access a member variable in a different member function
Try to remove echo json_encode($value); in your code.
If you need to access a parameter in several functions on your controller, you have to create it outside your function so it will be available for all your controller functions.
So, in your case it should be something like this:
class Test extends Controller
{
private $userdigit; //here you can set a default value if necessary: private $userdigit = 5
function insertdigit(){
$this->userdigit=5;
$flag = $this->usermodel->userdigitmodel($this->userdigit);
$value = array(
'result' => $flag
);
echo json_encode($value);
if ($flag == true) {
return $this->userdigit;
} else {
}
}
//second function
function usedigit(){
$data['userdigit']=$this->userdigit;
}
}
This way your userdigit variable is available for all your functions. With $this you are telling PHP that you are trying to access something inside the class.
This link contain more and useful information: http://www.php.net/manual/en/language.oop5.properties.php
Is that what you really need?
A possible solution:
function insertdigit()
{
$userDigit = 5;
$flag = $this->usermodel->userdigitmodel($userDigit);
$value = array
(
'result' => $flag
);
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
echo json_encode($value);
}
if ($flag == true)
{
return $userdigit;
}
else
{
}
}
//second function
function usedigit()
{
$data['userdigit'] = $this->insertdigit();
}
The above code, in insertdigit detects if there is an Ajax request and if so, it will echo out the json_encoded data. If you call it in an normal request, i.e. via usedigit it won't echo the json_encoded data (unless you are calling usedigit via an Ajax request).
Your question doesn't really explain what you are doing, so it's hard to explain a better solution, however, if you are trying to access a "variable" in more than one place, you should really separate your code so you have a single entry point for that variable.
Is your variable dynamic, or is it static?