Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php eval function and performance

Tags:

php

Im creating a web app where I want all of the responses to the user stored in a language file for easy editing. So Im using eval() to manage dynamic messages lik so:

$msg = 'Hello $user, your favorite color is $color';

$colors =  array("red","green","blue","yellow");
$users =  array("bob","craig","ted","dirty sanchez");

foreach($users as $key => $user){

 $color = $colors[$key];
 eval("\$newmsg = \"$msg\";");
 echo $newmsg;


}

Im wondering if this is the best approach or if there is a better way?

like image 643
websiteguru Avatar asked Dec 17 '22 22:12

websiteguru


1 Answers

Never use that damn eval if not necessary! Your code won't work, you should use sprintf for your purpose.

$messageFormat = 'Hello %s, your favorite color is %s';

$colors =  array("red","green","blue","yellow");
$users =  array("bob","craig","ted","dirty sanchez");
foreach($users as $key => $user){
   $color = $colors[$key];
   $actualMessage = sprintf($messageFormat, $user, $color);
   echo htmlentities($actualMessage);
}

Assuming you're using this for comments or other user-supplied text, I've added htmlentities() to prevent XSS.

like image 153
Lekensteyn Avatar answered Jan 02 '23 22:01

Lekensteyn