You are overcomplicating things by using eval
to achieve this. You can simply define your functions on the server-side and switch to the correct one using a simple switch case. This way you do not have to worry about security-related issues.
jQuery:
function callPhp(func, callback){
$.ajax({
type: 'GET',
url: 'callPhp.php',
data: {action:'register'},
success: function (data) {
data = JSON.parse(data);
callback(data);
}
});
}
PHP:
<?php
$action = $_GET['action'];
switch ($action) {
case "register":
register_user();
break;
case "login":
login();
break;
?>
If you really want to use eval
, which I highly discourage you to use, you can simply implement a sort of whitelist of method names that should be executed on the server side.
<?php
$whiteListMethod = array('register', 'login', 'forgotPassword');
$action = $_GET['action'];
// Is the user supplied function present in my whitelist?
if(in_array($action,$whiteListMethod)){
// You can call this method safely
}else{
// Hack attempt detected
}