How to transform a php $string into a $string() function call? - php

My current code:
$operation = "alienFunction";
switch($operation){
case "alphaFunction":
alphaFunction();
break;
case "betaFunction":
betaFunction();
break;
case "alienFunction":
alienFunction($kidsPerPlanet, $planet);
break;
Ok, I have a big list of functions. Some functions have parameters and some have not. The $operation is received from a $_POST variable. I want to do something like this:
$operation = "alphafunction";
$operation();
Or
$operation = "alienFunction";
$operation($kidsPerPlanet, $planet);

As already written in the comments you are looking for call_user_func_array(). Just use it like this:
call_user_func_array($functionName, $argumentArray);
But since you don't know which function you call with which parameters, just define an array and then use the code above, e.g.
$arguments = [
"alphaFunction" => [],
"betaFunction" => [],
"alienFunction" => [$kidsPerPlanet, $planet],
];
call_user_func_array($functionName, $arguments[$functionName]);

Excellent.
Thanks, guys. For functions with no parameters, it's working perfectly.
I'm trying this now:
$userInfo = MySQL_FETCH_ARRAY( MySQL_QUERY( ($autoAuth) ) );
CALL_USER_FUNC_ARRAY($operation, $userInfo);
Inside of one of functions, I have this piece of code inserted into HTML:
ECHO "<p>" . VAR_DUMP($userInfo) . "</p>";
And the result gives me "string(2) "25".
I'm new here. So I don't know what to do. For sure, my question is answered. Now I know how to use a string to call a function. Should I close this, select the best answer and create another question? Should I let it open, while my WHOLE problem is solved? Or should I close it and still comment here to get feedback?
Thanks a lot. I'm loving this. I wish that I can contribute as soon as possible too. :)

Related

Best way to do string format in PHP

I have following python code to format the string,
endpoint = '/uri/{id}'
params = {'id': xxxx}
endpoint.format(**params)
which is given me a following result,
'/uri/xxxx'
I need to develop a function in PHP which is doing the same thing, and I found a question related this but still I’m not satisfy with that.
What would be the best way to do this kind of a thing with PHP?
Thanks in advance
Maybe, something like this will satisfy your needs:
function sformat($template, $params) {
return str_replace(
array_map(function($v){return '{'.$v.'}';},array_keys($params)),
$params,
$template
);
}
echo sformat('/uri/{action}/{id}', $params = array(
'id'=>'23',
'action'=>'open'
));

Yii using a variable with an IN condition

I am trying to pull information into a page using my model. The issue is that I need to use an IN condition on my mysql using a variable.
Here is the code I use currently
$list_id = '1,3';
$clients = ListSubscriber::model()->findAll(array('condition'=>'list_id IN (:list_id)','params'=>array(':list_id'=>$list_id)));
I won't necessarily know how many numbers will be stored within $list_id, hence the need for a variable to work with the IN.
The code does execute without errors, but only seems to return the values for the first number of $list_id, so in this case it only finds users where the list_id = 1.
Any help is appreciated. I have found this question Yii addInCondition
However they are using static values, which does not resolve my issue.
When I do use static values, the code executes with results as expected.
You can use addInCondition :
$list_id = '1,3';
$criteria = new CDbCriteria();
$arr_list_id = explode(",",$list_id);
$criteria->addInCondition("list_id ", $arr_list_id );
$clients = ListSubscriber::model()->findAll($criteria);
$list_ids = array(1,3);
$clients = ListSubscriber::model()->findAllByAttributes(array('list_id'=>$list_ids));

Adding an Array multiple times in the DB via Controller

I'm having an issue producing this array multiple times upon how many coupons purchased.
Now it looks like
$coupon_array = array(
'user_id'=>$_POST["user_id"],
'mergent_id'=>$_POST["merchant_id"],
'deals_id'=>$_POST["deal_id"],
'order_id'=>$order_id,
'secret'=>$secret,
'expire_time'=>$time,
'create_time'=>$time,
'status'=>1
);
$this->common_model->insertData('coupon', $coupon_array);
But i have a post value such as:
"quantity"=>$_POST["quantity"]
and i would like to produce this X times. Example:
$quantity x $this->common_model->insertData('coupon', $coupon_array);
Sorry for my english, and i hope i explain this so it's understandable... ;)
Another one! when we insert the coupons they all have the same md5($secret), is it possible to have that also with all the different code...
$secret = md5($secret);
$coupon_array = array(
'user_id'=>$_POST["user_id"],
'mergent_id'=>$_POST["merchant_id"],
'deals_id'=>$_POST["deal_id"],
'order_id'=>$order_id,
'secret'=>$secret,
'expire_time'=>$time,
'create_time'=>$time,
'status'=>1
);
Well, if I understand what you want, you can use for, but that's obvious:
for($i=0; $i<$this->input->post('quantity');$i++) {
$coupon_array['secret'] = md5($coupon_array['secret'].$i);
$this->common_model->insertData('coupon', $coupon_array);
}
Also, never use $_POST["..."] in CodeIgniter, use only $this->input->post('...') as it escapes properly. More info about input class can be found here.
for ($i=0; $i<$quanity; $i++) {
$this->common_model->insertData('coupon', $coupon_array);
}

PHP preg_replace problem

This is a follow-up question to the one I posted here (thanks to mario)
Ok, so I have a preg_replace statement to replace a url string with sometext, insert a value from a query string (using $_GET["size"]) and insert a value from a associative array (using $fruitArray["$1"] back reference.)
Input url string would be:
http://mysite.com/script.php?fruit=apple
Output string should be:
http://mysite.com/small/sometext/green/
The PHP I have is as follows:
$result = preg_replace('|http://www.mysite.com/script.php\?fruit=([a-zA-Z0-9_-]*)|e', ' "http://www.mysite.com/" .$_GET["size"]. "/sometext/" .$fruitArray["$1"]. "/"', $result);
This codes outputs the following string:
http://mysite.com/small/sometext//
The code seems to skip the value in $fruitArray["$1"].
What am I missing?
Thanks!
Well, weird thing.
Your code work's perfectly fine for me (see below code that I used for testing locally).
I did however fix 2 things with your regex:
Don't use | as a delimiter, it has meaning in regex.
Your regular expression is only giving the illusion that it works as you're not escaping the .s. It would actually match http://www#mysite%com/script*php?fruit=apple too.
Test script:
$fruitArray = array('apple' => 'green');
$_GET = array('size' => 'small');
$result = 'http://www.mysite.com/script.php?fruit=apple';
$result = preg_replace('#http://www\.mysite\.com/script\.php\?fruit=([a-zA-Z0-9_-]*)#e', ' "http://www.mysite.com/" .$_GET["size"]. "/sometext/" .$fruitArray["$1"]. "/"', $result);
echo $result;
Output:
Rudis-Mac-Pro:~ rudi$ php tmp.php
http://www.mysite.com/small/sometext/green/
The only thing this leads me to think is that $fruitArray is not setup correctly for you.
By the way, I think this may be more appropriate, as it will give you more flexibility in the future, better syntax highlighting and make more sense than using the e modifier for the evil() function to be internally called by PHP ;-) It's also a lot cleaner to read, IMO.
$result = preg_replace_callback('#http://www\.mysite\.com/script\.php\?fruit=([a-zA-Z0-9_-]*)#', function($matches) {
global $fruitArray;
return 'http://www.mysite.com/' . $_GET['size'] . '/sometext/' . $fruitArray[$matches[1]] . '/';
}, $result);
i write it again, i don't understand good where is the error, the evaluation of preg results is very weird in php
preg_replace(
'|http\://([\w\.-]+?)/script\.php\?fruit=([\w_-]+)|e'
, '"http://www.$1/".$_GET["size"]."/sometext/".$fruitArray["$2"]."/";'
, $result
);
It looks like you have forgotten to escape the ?. It should be /script.php\?, with a \? to escape properly, as in the linked answer you provided.
$fruitArray["\$1"] instead of $fruitArray["$1"]

PHP function name on the fly

I have a rather stupid PHP question :D! I would like to simplify the following statement:
function hello_input() {
return 'Hello World';
}
$helper = 'hello';
$helper = $helper . '_input';
$data = $helperinput();
The specific part I want to simplify is the adding of the _input to the $helper so it calls the right function.
I thought of something like this but it doesn't work:
$data = $helper. 'input'();
or
$data = $helper. 'input' . ();
Any ideas?
Thanks,
Max
Use call_user_func, e.g. $data = call_user_func($helper.'input');.
$helper = 'hello_';
$data = $helper.'input';
call_user_func($data);
That should get you most of the way there. Good luck!
Docs here
Are you expecting to invoke code based on an input? You should never try to do that. That gives people the chance to execute arbitrary code. Even if you can't see quite how, it's still a potential method of attack.
What you probably want is a switch statement (or chained if statements) that match an input and dispatch the correct function.
Get the whole function name into a string first.
$helper = 'hello';
$func = $helper . '_input';
$data = $func();
PHP calls this variable functions. See also variable variables.

Categories