Search code examples
phpfunctionwrapper

Can I wrap functions in PHP?


I know this question sounds easy to answer, and I must have missed something somewhere, but after searching, I can't find an answer. I only can find answers about wrapping functions in classes, but I would like to wrap functions themselves, such as fopen.

Why: This may sound strange, but I want to make a site builder in which you write code and it saves it on your account. You should be able to write PHP, but of course you shouldn't delete or open server files, so I want to wrap functions so that I can first check if their fopen, rmdir, or similar functions are safe.


Solution

  • Frame challenge: if you did succeed in this, it would be using a blacklist to achieve security, which is basically impossible to do effectively. For every function you replace with a "safe" version, there will be ten you hadn't thought of that can be used in a malicious way.

    Instead, you should either use a whitelist or a sandbox.

    In a whitelist approach, you don't let the user enter normal PHP at all, but a special set of functionality that you've carefully picked to allow them to do what they need. That could be an actual subset of PHP that you parse with something like nikic/php-parser, a templating language like Twig, or a completely new language you write a simple parser for.

    In a sandbox approach, you allow the user to enter full PHP, but you run it in an isolated environment where they can't affect your real server. Any access to the file system or network would only be accessing virtual resources, and if the process abuses CPU or memory resources, the entire sandbox can be terminated. See for instance how the 3v4l.org site is hosted.