-4
\$\begingroup\$

I want to be able to call php functions from Javascript.

I thought of doing something like this, for any function I want to call :

jQuery

function callPhp(func, callback){
    $.ajax({
    type: 'GET',
    url: 'callPhp.php',
    data: {func:func},
    success: function (data) {
        data = JSON.parse(data);
        callback(data);
    }
});
}

Php (callPhp.php)

<?php
    require("functions.php");
    session_start();
    echo JSON.encode("data" => eval($_GET['func']));
?>

I just wrote this code, it is untested.

Using this, I can call functions from jQuery using callPhp().

Does this have security risks?

\$\endgroup\$
3
  • 3
    \$\begingroup\$ Please read How to Ask. Your question (especially the title) needs to state the purpose or goal of the code being reviewed. Also give us more context about the application that this code is a part of, so that we can give you better advice about how to write it. \$\endgroup\$ Commented Apr 2, 2017 at 19:05
  • 1
    \$\begingroup\$ It's like opening every door and every window in your house wide open and then asking "is it safe from thieves"? \$\endgroup\$ Commented Apr 3, 2017 at 7:56
  • 1
    \$\begingroup\$ This truly is broken code, as there is no way it works. JSON.encode() in PHP? \$\endgroup\$ Commented Apr 3, 2017 at 14:24

1 Answer 1

4
\$\begingroup\$

First of all your code has errors:

echo JSON.encode("data" => eval($_GET['func']));

There's no JSON.encode in PHP. The correct function is json_encode. You also have to pass a valid value, like an array:

echo json_encode(["data" => eval($_GET['func'])]);

That being said. Don't use eval unless there's absolutely no other way, because:

Caution: The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.


However, your code has a major security flaw. You pass everything from a $_GET parameter to eval(). You don't verify that string at all. I can call your script like:

callPhp.php?func=return system("ls -a");

… and I will get a list of all files in the directory. And this is just an example, because now anybody can run any code on your server. I can get your database content, download files, run scripts, send emails etc.


To be sure, let me put it this way:
Don't use that code.


If your goal is to run a function based on a selection in the client, send over a string, test it, and call the requested function yourself:

$func = $_GET['func'];

if ('list-something' == $func) {
    $data = listSomething();
}

This is just a simple example, to get you away from eval.

\$\endgroup\$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.