技术实现:点击按钮将变量输出(cat LIST.txt)写入textarea,含多按钮需求
Got it, let's fix this up so you can have three buttons that each load different command outputs into your textarea. Your current code runs the shell_exec command when the page loads, but we need to trigger it only when the button is clicked—and support three separate commands. Here's a clean, secure way to do it:
1. Backend PHP Handler (create get_output.php)
First, make a separate PHP file to handle command execution. We'll restrict which commands can be run to avoid security risks (never let users execute arbitrary commands!):
<?php // Define allowed commands to prevent malicious input $allowed_commands = [ 'list' => 'cat LIST.txt', 'another' => 'cat ANOTHER.txt', // For your second button 'third' => 'cat THIRD.txt' // For your third button ]; // Get the command key from the frontend request $command_key = $_GET['cmd'] ?? ''; if (isset($allowed_commands[$command_key])) { // Run the allowed command and format output for the textarea $output = shell_exec($allowed_commands[$command_key]); // Convert newlines to <br> for safe transmission, we'll convert back later echo nl2br($output); } else { echo 'Invalid request: Command not allowed'; } ?>
2. Frontend HTML & JavaScript
Update your main page to include three buttons, each triggering a request for a specific command. We'll use the Fetch API to load the output asynchronously (no page refresh):
<!DOCTYPE html> <html> <body> <br> <textarea placeholder="List Status" name="List" rows="30" cols="100" id="myTextarea"></textarea> <br><br> <!-- Three buttons, each mapped to a command from our allowed list --> <button type="button" onclick="loadOutput('list')">Load LIST.txt</button> <button type="button" onclick="loadOutput('another')">Load ANOTHER.txt</button> <button type="button" onclick="loadOutput('third')">Load THIRD.txt</button> <script> function loadOutput(cmdKey) { const textarea = document.getElementById("myTextarea"); // Fetch the output from our PHP handler fetch(`get_output.php?cmd=${cmdKey}`) .then(response => response.text()) .then(data => { // Convert <br> back to newlines for proper textarea formatting textarea.value = data.replace(/<br>/g, '\n'); }) .catch(error => { textarea.value = `Error loading data: ${error.message}`; }); } </script> </body> </html>
3. Important Notes
- Security First: The
$allowed_commandsarray is critical—never accept raw command input from the frontend. This prevents attackers from running harmful commands on your server. - Newline Handling: We use
nl2br()in PHP to safely send newlines over HTTP, then convert them back to\nin JavaScript so the textarea displays line breaks correctly. - Asynchronous Loading: Using Fetch means the page doesn't refresh when you click a button—your textarea updates instantly with the command output.
内容的提问来源于stack exchange,提问作者Gustavo

