首页 > 解决方案 > 从另一个 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."?>

标签: php

解决方案


是的,可以动态执行函数,但要确保它有很多验证让用户只调用有效函数。

$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));

推荐阅读