PHP Function and variables stored in a string in a database - php

I need to store data within a database, when I get the data from the database I need functions and variables in the string to be worked out as such.
Example
$str = "<p>Dear {$this->name},</p>"
I then store this in the database, and when I retrieve the string and run it through
eval("\$detail= \"$detail\";");
then the variable gets populated with the name. This is exactly what I needed and works fine.
The problem is I want to run a function with this variable as the parameter.
example. I would like to ucwords the variable.
I have tried:
$str = "<p>Dear {ucwords($this->name)},</p>" //just echoed {ucword(->name)},
$str = "<p>Dear {ucwords($this->name)},</p>" //Fatal error: Function name must be a string,
Am I going in the right direction?
Is this at all possible?

You don't need to keep PHP code in database. This is a bad practice and also can lead to security vulnerabilities.
Instead store in database string like this:
<p>Dear [name],</p>
And when you retrieve it you can just do:
$stringFromDb = str_replace("[name]", $this->name, $stringFromDb);
or
$stringFromDb = str_replace("[name]", ucwords($this->name), $stringFromDb);
Other common approach is to use sprintf. So you need to store in database string with %s as placeholders for values.
Example:
<p>Dear %s,</p>
and replace with
$stringFromDb = sprintf($stringFromDb, ucwords($this->name));

What you seem to be looking for is a simple templating language.
It's been a long while since I've written PHP (and I suddenly remember why...), but here's something I whipped up.
It should support both objects ($a->name) and arrays ($a["name"]) as input objects.
You can add new filters (name -> function name mapping) in $valid_filters.
$valid_filters = array("title" => "ucfirst", "upper" => "strtoupper");
function _apply_template_helper($match) {
global $_apply_template_data, $valid_filters;
$var = $match[1];
$filter = $valid_filters[trim($match[2], ':')];
$value = is_array($_apply_template_data) ? $_apply_template_data[$var] : $_apply_template_data->$var;
if($filter && !empty($value)) $value = call_user_func($filter, $value);
return !empty($value) ? $value : $match[0];
}
function apply_template($template, $data) {
global $_apply_template_data;
$_apply_template_data = $data;
$result = preg_replace_callback('/\{\{(.+?)(:.+?)?\}\}/', "_apply_template_helper", $template);
$_apply_template_data = null;
return $result;
}
How to use it:
$template = "Hello {{name:title}}, you have been selected to win {{amount}}, {{salutation:upper}}";
echo apply_template($template, array("name"=>"john", "amount" => '$500,000', "salutation" => "congratulations"));
The result:
Hello John, you have been selected to win $500,000, CONGRATULATIONS

I have found the following works,
If i contain the function within the class itself then it can be called using the following code
<p>Dear {\$this->properCase(\$this->rl_account->name)},</p>
But i would like to be able to do this now without having the database have the code as Alex Amiryan mentions earlier.

Related

How to perform string interpolation on string returned from DB PHP Laravel

I am trying to figure out how to make this work. I am currently storing a string with a dynamic variable in it in a DB. The string is stored like this, and it is associated with a thank you message:
"Thank you for visiting $location->name"
When I retrieve it, I am doing this:
$thankyou = Thankyou::where('action', $request->get('action');
My hope was that I would be able to then dynamically get and set the location variable
$location = Location::where('id', $request->get('id'))->first()
And then return $thankyou->message (which has the value of the string above) and have it work as intended.
In full, my code looks like this
$thankyou = Thankyou::where('action', $request->get('action');
// $thankyou->message yields "Thank you for visiting $location->name"
$location = Location::where('id', $request->get('id'))->first();
return $thankyou->message;
But, instead of correctly parsing the $location variable, this code simply returns the string stored in the DB. How can I make this work?
Usually placeholders are used. For example:
$variables = [
'LOCATION_NAME' => 'New York',
'OTHER_VAR' => 'Test'
];
$string = 'Thank you for visiting {LOCATION_NAME}. {OTHER_VAR}';
foreach($variables as $key => $var){
$string = \Str::replaceFirst('{'.$key.'}', $var, $string);
}
return $string;
I would suggest to use an accessor insted, as the whole approach is not completely right. Let's save your message is saved like: "Thank you for visiting %location_name%"
public function getUpdatedMessageAttribute()
{
$location = Location::where('id', request()->get('id'))->first();
return str_replace('%location_name%', $location->name, $this->message);
}
You can develop the way you receive your parameters to make it more dynamic.

How can I sanitise the explode() function to extract only the marker I require?

I have some php code that extracts a web address. The object I have extracted is of the form:
WEBSITE?flage=2&fgast=48&frat=1&sort=D&fsrc=2&wid=bf&page=1&id=16123012&source=searchresults
Now in PHP I have called this object $linkHREF
I want to extract the id element only and put it into an array (I'm bootstrapping this process to get multiple id's)
So the command is:
$detailPagePathArray = explode("id=",$linkHREF); #Array
Now the problem is the output of this includes what comes after the id tag, so the output looks like:
echo $detailPagePathArray[0] = WEBSITE?flage=2&fgast=48&frat=1&sort=D&fsrc=2&w
echo $detailPagePathArray[1] = bf&page=1&
echo $detailPagePathArray[2] = 16123012&source=searchresults
Now the problem is obvious, where it'd firstly picking up the "id" in the "wid" marker and cutting it there, however the secondary problem is it's also picking up all the material after the actual "id". I'm just interested in picking up "16123012".
Can you please explain how I can modify my explode command to point it to the particular marker I'm interested in?
Thanks.
Use the built-in functions provided for the purpose.
For example:
<?php
$url = 'http://www.example.com?flage=2&fgast=48&frat=1&sort=D&fsrc=2&wid=bf&page=1&id=16123012&source=searchresults';
$qs = parse_url($url);
parse_str($qs['query'], $vars);
$id = $vars['id'];
echo $id; // 16123012
?>
References:
parse_url()
parse_str()
if you are sure that you are getting &id=123456 only once in your object, then below
$linkHREF = "WEBSITE?flage=2&fgast=48&frat=1&sort=D&fsrc=2&wid=bf&page=1&id=16123012&source=searchresults";
$str = current(explode('&',end(explode('&id', $linkHREF,2))));
echo "id" .$str; //output id = 16123012

Can I add variable name within a string?

I am creating an OpenCart extension where the admin can change his email templates using the user interface in the admin panel.
I would like the user to have the option to add variables to his custom email templates. For example he could put in:
Hello $order['customer_firstname'], your order has been processed.
At this point $order would be undefined, the user is simply telling defining the message that is to be sent. This would be stored to the database and called when the email is to be sent.
The problem is, how do I get "$order['customer_firstname']" to become a litteral string, and then be converted to a variable when necessary?
Thanks
Peter
If I understand your question correctly, you could do something like this:
The customer has a textarea or similar to input the template
Dear %NAME%, blah blah %SOMETHING%
Then you could have
$values = array('%SOMETHING%' => $order['something'], '%NAME%' => $order['name']);
$str = str_replace(array_keys($values), array_values($values), $str);
the user will be using around 40 variables. Is there a way I can set it to do that for each "%VARIABLE%"?
Yes, you can do so for each variable easily with the help of a callback function.
This allows you, to process each match with a function of your choice, returning the desired replacement.
$processed = preg_replace_callback("/%(\S+)%/", function($matches) {
$name = $matches[1]; // between the % signs
$replacement = get_replacement_if_valid($name);
return $replacement;
},
$text_to_replace_in
);
From here, you can do anything you like, dot notation, for example:
function get_replacement_if_valid($name) {
list($var, $key) = explode(".", $name);
if ($var === "order") {
$order = init_oder(); // symbolic
if(array_key_exists($key, $order)) {
return $order[$key];
}
}
return "<invalid key: $name>";
}
This simplistic implementation allows you, to process replacements such as %order.name% substituting them with $order['name'].
You could define your own simple template engine:
function template($text, $context) {
$tags = preg_match_all('~%([a-zA-Z0-9]+)\.([a-zA-Z0-9]+)%~', $text, $matches);
for($i = 0; $i < count($matches[0]); $i++) {
$subject = $matches[0][$i];
$ctx = $matches[1][$i];
$key = $matches[3][$i];
$value = $context[$ctx][$key];
$text = str_replace($subject, $value, $text);
}
return $text;
}
This allows you to transform a string like this:
$text = 'Hello %order.name%. You have %order.percent%% discount. Pay a total ammount of %payment.ammount% using %payment.type%.';
$templated = template($text, array(
'order' => array(
'name' => 'Alex',
'percent' => 20
),
'payment' => array(
'type' => 'VISA',
'ammount' => '$299.9'
)
));
echo $templated;
Into this:
Hello Alex. You have 20% discount. Pay a total ammount of $299.9 using VISA.
This allows you to have any number of variables defined.
If you want to keep the PHP-syntax, then a regex would be appropriate to filter them:
$text = preg_replace(
"/ [$] (\w+) \[ '? (\w+) \'? \] /exi",
"$$1['$2']", # basically a constrained eval
$text
);
Note that it needs to be executed in the same scope as $order is defined. Else (and preferrably) use preg_replace_callback instead for maximum flexibility.
You could also allow another syntax this way. For example {order[customer]} or %order.customer% is more common and possibly easier to use than the PHP syntax.
You can store it as Hello $order['customer_firstname'] and while accessing make sure you have double-quotes "" to convert the variable to its corresponding value.
echo "Hello $order['customer_firstname']";
Edit: As per the comments, a variation to Prash's answer,
str_replace('%CUSTOMERNAME%', $order['customer_name'], $str);
What you're looking for is:
eval("echo \"" . $input . "\";");
but please, PLEASE don't do that, because that lets the user run any code he wants.
A much better way would be a custom template-ish system, where you provide a list of available values for the user to drop in the code using something like %user_firstname%. Then, you can use str_replace and friends to swap those tags out with the actual values, but you can still scan for any sort of malicious code.
This is why Markdown and similar are popular; they give the user control over presentation of his content while still making it easy to scan for HTML/JS/PHP/SQL injection/anything else they might try to sneak in, because whitelisting is easier than blacklisting.
Perhaps you can have a template like this:
$tpl = "Hello {$order['customer_firstname']}, your order has been processed.".
If $order and that specific key is not null, you can use echo $tpl directly and show the content of 'customer_firstname' key in the text. The key are the curly braces here.

Replacing delimiters with PHP variables

I'm writing a mail class that pulls content stored in a database and loads it into a template before sending it as a HTML e-mail. However, because each e-mail contains PHP variables and dynamic content, I've decided to use delimiters. So instead of the content looking like:
Hello $username, welcome to the site.
It'll look like:
Hello {{username}}, welcome to the site.
So far I'm using these methods:
function load($name,$content)
{
// preps the template for HTML
}
function content($template_id)
{
$template = $this->db->get_where('email_templates',array('id'=>$template_id));
return $template->content;
}
function new_email($email,$name,$user_type)
{
$msg = $this->load($name,$this->content(1));
$this->send($email,'Thanks for your application',$msg,1);
}
The trouble I'm having is how to convert a {{variable}} into a $variable so that it will parse - I don't want it to just be loaded as $username in the e-mail template. Is it just a case of using regular expressions and escaping the string so that it'll parse? Something like:
$content = str_replace("{{","'.$",$template->content);
$content = str_replace("}}",".'",$template->content);
Or is this flawed? Does anybody know what's the best thing to do?
I would not create my own templating system, because there are existing ones out there.
The most popular is probably Smarty, but there is an another one which has the same format as you created, that is mustache.
Update:
The problem with your code is that you're replacing the {{ to a .$ and store that in $content variable, then replacing }} to . and overwrite this replaced $content variable.
A possible working solution could be:
if (preg_match_all("/{{(.*?)}}/", $template, $m)) {
foreach ($m[1] as $i => $varname) {
$template = str_replace($m[0][$i], sprintf('$%s', $varname), $template);
}
}
But then you would also need to eval your code somehow.
So after converting {{variable}} to $variable in your email template, you will use eval to get it replaced by the actual contents of that variable?
Why not just replace {{variable}} with the contents of $variable straight away?
Perhaps have a function that takes the template text and an array of placeholder => "text to replace it with". Then it's as simple as making up the placeholders' exact strings by adding {{ and }} around that array's key and doing str_replace.
foreach ($replacements as $placeholder => $value) {
$placeholder = "{{" . $placeholder . "}}" ;
$text = str_replace($placeholder, $value, $text) ;
}
Couple this with (class) constants for the placeholders and you have a very solid and typo-repelant templating system. It will not be as elegant or easy to use as a full blown templating solution, and it might require extra work from whoever writes code that uses it, but they will not make mistakes during development due to mis-named variables.
If you are going to do it yourself it is probably best to just be explicit with str_replace. If you try to convert the curly bracers to $ you'll then need to eval() which is a potential security hole.
This would be my approach with str_replace - this becomes difficult to maintain as you add more variables but it really doesn't get much simpler either.
$content = str_replace(
array('{{username}}','{{var2}}'),
array($username,$var2),
$template->content
);
use preg_replace_callback , see : http://codepad.org/EvzwTqzJ
<?php
$myTemplateStr = "Hello {{username}} , this is {{subject}} ,and other string {{example}}";
$tagRegex = "|{{(.*?)}}|is";
$result = preg_replace_callback($tagRegex,"myReplaceFunc",$myTemplateStr);
echo $result ;
/* output :
Hello $username , this is $subject ,and other string {{example}}
*/
function myReplaceFunc($matches)
{
$validTags = array('username','subject','name');
$theFull = $matches[0];
$theTag = $matches[1];
if(in_array($theTag,$validTags) == true)
return '$'.$theTag;
return $theFull ;
}
?>
$template = "Hello {{username}} , this is {{subject}} ,and other the answer is on page {{example}}";
$replacements = array(
'username' => 'Jeffrey',
'subject' => 'your final notice',
'page' => 43
);
function bind_to_template($replacements, $template) {
return preg_replace_callback('/{{(.+?)}}/',
function($matches) use ($replacements) {
return $replacements[$matches[1]];
}, $template);
}
echo bind_to_template($replacements, $template);
Credit to https://www.labnol.org/code/19266-php-templates

PHP Dynamic Regexp replacement

I would like to know if there is a way to bind PHP function inside a regexp.
Example:
$path_str = '/basket.php?nocache={rand(0,10000)}';
$pattern = ? // something i have no idea
$replacement = ? // something i have no idea
$path = preg_replace($pattern, $replacement, $path_str);
Then :
echo "'$path'";
would produce something like
'/basket.php?nocache=123'
A expression not limited to the 'rand' function would be even more appreciated.
Thanks
You could do the following. Strip out the stuff in between the {} and then run an eval on it and set it to a variable. Then use the new variable. Ex:
$str = "/basket.php?nocache={rand(0,10000)}";
$thing = "rand(0,10000)";
eval("\$test = $thing;");
echo $test;
$thing would be what's in the {} which a simple substr can give you. $test the becomes the value of executing $thing. When you echo test, you get a random number.
Don't, whatever you do, store PHP logic in a string. You'll end up having to use eval(), and if your server doesn't shoot you for it, your colleagues will.
Anywhoo, down to business.
Your case is rather simple, where you need to append a value to the end of a string. Something like this would be sufficient
$stored = '/basket.php?nocache=';
$path = $stored . rand(0,10000);
If, however, you need to place a value somewhere in the middle of a string, or possibly in a variable location, you could have a look at sprintf()
$stored = '/basket.php?nocache=%d&foo=bar';
$path = sprintf($stored, rand(0,10000));
I would not try to store functions in a database. Rather store some kind of field that represents the type of function to use for each particular case.
Then inside your crontab you can do something like:
switch ($function)
{
case 'rand':
$path_str = '/basket.php?nocache='. rand(0,10000);
}
e.t.c

Categories