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.


My name is Mario Peshev, a global SME Business Advisor running digital businesses for 20 the past years.

Born in Bulgaria, Europe, I gained diverse management experience through my training work across Europe, North America, and the Arab world. With 10,000+ hours in consulting and training for organizations like SAP, VMware, CERN, I’ve dedicated a huge amount of my time to helping hundreds of SMEs growing in different stages of the business lifecycle.

My martech agency DevriX grew past 50 people and ranks as a top 10 WordPress global agency and Growth Blueprint, my advisory firm, has served 400+ SME founders and executives with monthly ongoing strategy sessions.


Follow me at:

Latest Editions:

Browse by Category

Latest Answers: