从URL调用PHP函数是一种常见的Web开发需求,它允许通过HTTP请求触发服务器端的PHP函数执行。这种技术通常用于构建API接口、处理表单提交或实现AJAX交互。
// index.php
if (isset($_GET['action'])) {
$action = $_GET['action'];
switch ($action) {
case 'getUser':
getUser();
break;
case 'saveData':
saveData();
break;
default:
echo "未知操作";
}
}
function getUser() {
echo json_encode(['id' => 1, 'name' => '张三']);
}
function saveData() {
// 保存数据逻辑
echo "数据保存成功";
}
调用方式:http://example.com/index.php?action=getUser
// .htaccess (Apache)
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
// index.php
$request = $_GET['url'] ?? '';
$parts = explode('/', $request);
$controller = $parts[0] ?? 'home';
$method = $parts[1] ?? 'index';
$params = array_slice($parts, 2);
if (function_exists($method)) {
call_user_func_array($method, $params);
} else {
http_response_code(404);
echo "方法不存在";
}
调用方式:http://example.com/api/getUser/123
// api.php
$function = $_GET['func'] ?? '';
$allowedFunctions = ['getUser', 'saveData'];
if (in_array($function, $allowedFunctions) && function_exists($function)) {
call_user_func($function);
} else {
http_response_code(403);
echo "不允许的操作";
}
filter_input()
等函数过滤输入原因:函数名拼写错误或函数不存在
解决:检查函数名是否正确,使用function_exists()
验证
原因:直接使用用户输入调用函数 解决:实现白名单机制,只允许调用特定函数
原因:参数格式不正确 解决:使用JSON或表单数据传递复杂参数
通过URL调用PHP函数是一种强大但需要谨慎使用的技术,正确实现可以为Web应用提供灵活的交互能力。
没有搜到相关的文章