求助:实现带自定义输入框的登录Shell下拉选择组件
解决方案
改造后的完整代码
<?php $current_shell = $USER->getLoginShell(); // 预设Shell选项,可根据系统实际路径调整 $preset_shells = [ '/bin/bash' => 'Bash', '/usr/bin/zsh' => 'Zsh' ]; // 判断当前Shell是否属于预设选项 $is_custom_shell = !array_key_exists($current_shell, $preset_shells); ?> <h5>Login Shell</h5> <div class='inline'> <form action='' method='POST'> <input type='hidden' name='form_type' value='loginshell'> <select name="preset_shell" id="preset_shell" onchange="toggleCustomInput()"> <?php foreach ($preset_shells as $path => $label): ?> <option value="<?php echo htmlspecialchars($path); ?>" <?php echo ($current_shell === $path) ? 'selected' : ''; ?>> <?php echo htmlspecialchars($label); ?> </option> <?php endforeach; ?> <option value="custom" <?php echo $is_custom_shell ? 'selected' : ''; ?>>自定义</option> </select> <div id="custom_shell_wrap" style="display: <?php echo $is_custom_shell ? 'inline-block' : 'none'; ?>; margin-left: 8px;"> <input type='text' name='custom_loginshell' placeholder='输入自定义Shell路径' value="<?php echo $is_custom_shell ? htmlspecialchars($current_shell) : ''; ?>" <?php echo $is_custom_shell ? 'required' : ''; ?>> </div> <input type='submit' value='Set Login Shell' style="margin-left: 8px;"> </form> </div> <script> function toggleCustomInput() { const selectEl = document.getElementById('preset_shell'); const customWrap = document.getElementById('custom_shell_wrap'); const customInput = customWrap.querySelector('input'); if (selectEl.value === 'custom') { customWrap.style.display = 'inline-block'; customInput.required = true; } else { customWrap.style.display = 'none'; customInput.required = false; } } </script>
核心功能说明
- 预设选项适配:预设了Bash和Zsh的常见路径,你可以根据服务器实际安装路径修改
$preset_shells数组。 - 初始状态匹配:PHP自动判断当前用户的Shell是否在预设列表中,自动选中对应选项,若为自定义Shell则默认显示输入框并填充当前值。
- 交互逻辑:通过JavaScript实现下拉选择与输入框的联动,选中“自定义”时显示输入框并设置必填,选择预设选项时隐藏输入框并取消必填。
- 后端接收逻辑:提交表单时需要区分取值来源,示例后端处理代码:
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['form_type'] === 'loginshell') { $target_shell = $_POST['preset_shell']; if ($target_shell === 'custom') { $target_shell = $_POST['custom_loginshell']; } // 执行设置登录Shell的逻辑,例如 $USER->setLoginShell($target_shell); }
- 安全防护:使用
htmlspecialchars()转义输出内容,避免XSS攻击风险。
内容的提问来源于stack exchange,提问作者Sean M.
相关产品推荐
相关产品推荐

