On Tue, Feb 15, 2011 at 5:02 PM, Brian Waters <brianmwat...@gmail.com>wrote:

> On Mon, Feb 14, 2011 at 11:49 PM, Paul M Foster <pa...@quillandmouse.com>
> wrote:
> > Advice: don't use eval() this way. It's slow and dangerous.
> Could you elaborate, or provide a link?

Hi Brian,

Here's a dated but still relevant reference:

terms of performance, you could toss together some tests to see the
performance hit (using microtime() and a for loop could get you some nice
quick data.) It's a pretty big hit, and to my knowledge, opcode caches don't
cache eval() code, either.

In terms of security, the issue is using user input. If your evaluated code
includes any user input, you'll have to safely guard against a vast array of
potential injections. Not so hard when the user input is limited to numbers
like an age field, just regex it to show it's only numbers.  However,
complex user input becomes very difficult. In the case of your example
template class, evaling a template file that you don't control and that by
it's very nature is contains complex data, would lead to significant
security issues.

I have never chosen to use eval, as PHP comes with many, many powerful
options for solving problems. However, it's nice to know it's there if I
wanted to use it :)

In the case of your template class, you have several options:

   - Use placeholders other than PHP and merely perform string replaces
   (e.g., "{title}", "{text}", etc.).  This is a bit slower, but limits PHP in
   - Change the sequence of your calls. You could create the template
   object, set the variables, then include the appropriate template file. See
   answer 2 by meouw in the link below:


Anyways, just 2 quick ideas.

Happy PHP coding,


Nephtali:  A simple, flexible, fast, and security-focused PHP framework

Reply via email to