php - 从另一个 php 文件的文本框中的 php 文件执行函数
问题描述
我是否可以通过在另一个 php 文件的输入 texbox 中键入函数的名称来执行 php 文件中的函数。
function bamiiChuckNorris() {
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
$geocodeUrl = "http://api.icndb.com/jokes/random";
$response = file_get_contents($geocodeUrl, false, stream_context_create($arrContextOptions));
$a =json_decode($response, true);
return $a['value']['joke'];
}function bamiiTellTime($data) {
if(strpos($data, 'in')) {
return "Sorry i can't tell you the time somewhere else right now";
} else {
return 'The time is:' . date("h:i");
}
}?>
这是我的文件
<?php include answers.php
This is the input text box
<input name="input" type="text" class="tb5" placeholder="Chat with me! Press Ask to send."?>
解决方案
是的,可以动态执行函数,但要确保它有很多验证让用户只调用有效函数。
$functionName = $_POST['input'];
if (function_exists($functionName)) {
// Dynamic call using variable value as function name.
$response = {$functionName}();
} else {
throw new Exception(404, "Function '{$functionName}' not found");
}
如果检查对象方法,请使用method_exists($class, $functionName)
要从输入中执行代码,get_number(1)
有几个选项:
1) 使用eval($input)
-不安全
2) 使用正则表达式解析用户输入
$uInput = $_POST['input'];
$matches = [];
preg_match('/(\w+)\((\w+)\)/', $uInput, $matches);
$functionName = $matches[1];
$params = $matches[2];
{$functionName}(...explode(', ', $params));
推荐阅读
- android - 为什么在这些源代码中没有调用 onMeasure
- linux - 如何使用 yocto 配方在目标板上设置环境变量?
- c# - 如何在不减慢到 0.3 FPS 的情况下移动 500 个刚体立方体?
- reactjs - rc-tree 只显示文件夹而不是文件
- python-3.x - 将零插入numpy数组的最快方法
- ssl - 使用 Google Ingress 和托管证书进行 SSL 重定向
- c - 什么代码负责在 Numpy 中添加两个矩阵?
- windows - 如何将数据传递给我的 WFP 标注驱动程序?
- python - 在 PyCharm 上使用 Kivy 库时如何解决以下错误?
- node.js - 是否可以在不使用承诺的情况下将许多插入 MongoDB?