如何捕获所有路由并在刀片模板中调用php函数

时间:2019-01-15 19:38:46

标签: php laravel laravel-5 routes

我在Laravel应用中工作,我需要捕获所有类似https://localhost/myapp/someroute/的路由,此路由调用控制器,该控制器返回包含php scritp和该php脚本的视图需要其余的de url(o路由)执行类似

的功能
function test()
{
    return round(microtime(true) * 1000);
}

例如,如果我输入:https://localhost/myapp/someroute/test,则在浏览器中我应该看到该函数的结果,因为我需要脚本中存在array_key_exists('PATH_INFO', $_SERVER)并在php脚本中调用该函数不知道它在Laravel中是否可行。

使用此代码,我试图捕获所有URL:

Route::get('someroute/{function?}', function() {
   return view('directory.phpfilename');
})->where('function', '.*');;

1 个答案:

答案 0 :(得分:1)

尽管此答案对您有用,但我强烈建议您确保用户只能在服务器上调用特定功能。允许用户传递任何php函数名称并从服务器获取响应可能会带来巨大的安全风险。

为此,我添加了$allowedFunctions数组,您可以在其中指定用户可以调用的函数。

或者您可以创建一个类,在其中可以定义用户可以执行的方法,然后检查类中是否存在给定的$function方法。如果是这样,请执行功能。

这是在视图中运行函数的方式

在您的routes/web.php中,添加此

Route::get('/someroute/{function?}', function($function = null) {
  // check that parameter is passed and that function exists
  if ( empty($function) || ! function_exists($function) ) {
    return 'Function not found';
  }

  /*
    here you can list functions that user can call
    - don't allow users to run any function that's not on this list
  */
  $allowedFunctions = [
    'test',
  ];

  if ( ! in_array($function, $allowedFunctions) ) {
    return 'Function not allowed';
  }

  return view('directory.phpfilename', [
    'function' => $function,
  ]);
})->where('function', '.*');

您认为要运行该功能,请使用

{{ $function() }}

{{ call_user_func($function) }}