Skip to content
Advertisement

Regex letters are not allowed when they should be?

My and my group are trying to create a simple PHP code editor that also executes the code without the use of a library.

We know the risks that come with eval(), but since it’s all running on a local server it shouldn’t be a problem.

The Regex part is definitely the problem since we have no clue how that works and because it’s copied from the internet.

What we are trying to do using Regex is to limit the input to certain words/characters/numbers etc. The problem is that it will fail when trying the input contains words like “Echo”

<textarea id="area" cols="70" rows="30"></textarea>
<button id="submit">Submit</button>

<script>
$('#submit').click(function (e) {
    e.preventDefault();

    var info = $('#area').val();

    $.ajax({
        type: "POST",
        url: 'pages/assignments/response.php',
        data: {
            area: info
        },
        success: function (response) {
            console.log(response);
        }
    });
});
</script>
<?php
    if (!empty($_POST['area'])) {
        runEval($_POST['area']);
    };

    function runEval($data)
    {
        $characters = '[a-zA-Z0-9]*';
        $functions = '';
        $operators = '[w-><$(){}|_+=":;!&*%$]';
        $regexp = '/^((' . $characters . '|' . $functions . 's*((?1)+)|((?1)+))(?:' . $operators . '(?2))?)+/';

        if (preg_match($regexp, $data)) {
            eval('$result = ' . $data . ';');
            echo $result;
        } else {
            return false;
        }
    }
?>

Advertisement

Answer

I think the code you copied was initially used for mathematical or string operations, because it assigns a value to a variable (eval('$result = ' . $data . ';')).

Try removing $result = and the echo statement and see if it works.

From the docs:

The code must not be wrapped in opening and closing PHP tags, i.e. ‘echo “Hi!”;’ must be passed instead of ”. It is still possible to leave and re-enter PHP mode though using the appropriate PHP tags, e.g. ‘echo “In PHP mode!”; ?>In HTML mode!

Apart from that the passed code must be valid PHP. This includes that all statements must be properly terminated using a semicolon. ‘echo “Hi!”‘ for example will cause a parse error, whereas ‘echo “Hi!”;’ will work.

A return statement will immediately terminate the evaluation of the code.

The code will be executed in the scope of the code calling eval(). Thus any variables defined or changed in the eval() call will remain visible after it terminates.

http://php.net/manual/ro/function.eval.php

Btw, note that as said in the docs eval() is very dangerous because it allows to execute any kind of valid php code on the server.

See:

https://security.stackexchange.com/questions/179375/how-eval-in-php-can-be-dangerous-in-web-applications-security

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement