eval() error check

We all know how dangerous eval() is in terms of security, but still it is the necessary evil sometimes.

I’ve been developing a script last week that required eval() execution. I did pretty granular input validation with regular expressions and known troubleish test cases. Still, some expressions passed to the eval() function were prone to parse errors.

Reading a bit I tried to use the exceptions handling mechanism in PHP 5 (try – catch blocks) to provide a solution, or using a error handler with the set_error_handler function. They work for exceptions and some basic errors, but most of the errors (including the parse erorr) pass.

I don’t mind the system being unable to call a valid function, but I want to protect the frontend. So the best call I found is using this trick.

Create a function with this content:

 

return @eval('return true;' . $code);

Where $code is the code you need to normally call in eval().

This statement returns true if your eval is valid – or false if it is going to break. Without breaking the frontend and the PHP execution.

So calling this before running your eval and testing for true will prevent the ugly errors on the page load.


Mario Peshev is a 5x CEO and operator, founder of DevriX and Growth Shuttle, global value creation advisor, angel investor, and author of “MBA Disrupted.”

His original background in engineering rode the wave of IT entrepreneurship in the last 25 years, from product and service entrepreneurship through acquiring and selling businesses, to investing in global startups like beehiiv, doola, the Stacked Marketer, Alcatraz, SeedBlink.

Peshev spent over 10,000 hours in consulting and training contracts for mid-market and enterprise organizations like VMware, SAP, Software AG, CERN, Saudi Aramco since 2006. His books and guides are referenced in over 50 universities in North America, Europe, and Asia.


Follow Mario on social:

Latest Editions:

Latest Answers: