Running Lua Scripts in PHP

I was looking for a way to run untrusted user code in a PHP application, and I found different PHP extensions that could potentially support this. Initially, I explored php-lua, but soon realized that it is currently unmaintained and only a community fork provides support for PHP 8.

I did not realize, at first, that LuaSandbox is a different project entirely. Upon a second review of my options, I discovered that LuaSandbox is still actively maintained (by Tim Starling/Legoktm /Timo Tijhof) and is compatible with PHP 8.

I plan to use LuaSandbox for two primary purposes:

  1. Calculating field values dynamically.
  2. Allowing users to define conditional actions by exposing certain application functions to Lua.

Executing Lua Scripts in PHP with LuaSandbox

Here’s how you can use LuaSandbox to execute user-provided Lua scripts in PHP:

Prerequisites

LuaSandbox must be installed and enabled in the PHP environment. It's available as a PECL extension

pecl install luasandbox

The extension must be loaded in php.ini:

extension=luasandbox.so

Lua Execution Example

$lua = new LuaSandbox();

$lua->setMemoryLimit( 50 * 1024 * 1024 );
$lua->setCPULimit( 10 );

$lua->registerLibrary( 'php', [
    'output' => function ( $string ) {
        echo "$string\n";
    },
    'error' => function () {
        throw new LuaSandboxRuntimeError( "Something is wrong" );
    }
] );
$luaCode = <<<EOF
php.output( "Hello, world" );
EOF;

$lua->loadString( $luaCode )->call();