基于按钮的PHP计算器HTML代码技术咨询
Alright, let's start by formatting your provided code snippet correctly using Markdown, then dive into key technical insights to get this calculator working smoothly.
Formatted Original Code Snippet
<div style="padding-left:40px"> <h2>PHP Calculator</h2> <form method="post" action=""> Enter value: <input type="text" name="value"> <br><br> <div style="padding-left: 105px"> <input type="submit" value="9" name="button"> <input type="submit" value="8" name="button"> <input type="submit" value="7" name="button"> <input type="submit" value="+" name="button"> <br> <input type="submit" value="6" name="button"> <!-- Truncated original code --> </div> </form> </div>
Key Technical Fixes & Enhancements
- Capturing Button Inputs: Since every button is a submit element, clicking any will post the form to the same page (empty
action). To build the calculator's input logic, you need to append the clicked button's value to the display field. Here's a quick PHP snippet to handle this:
Update your input field to pre-fill the current value (and avoid XSS risks):<?php $display = ''; if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Retain existing value and append the clicked button $display = isset($_POST['value']) ? $_POST['value'] : ''; if (isset($_POST['button'])) { $display .= $_POST['button']; } } ?><input type="text" name="value" value="<?php echo htmlspecialchars($display); ?>"> - Critical Security Note: Always use
htmlspecialchars()when echoing user input back to the page—this prevents cross-site scripting (XSS) attacks, which are a common vulnerability in PHP forms. - Clean Up Inline Styles: Instead of hardcoding padding directly in HTML, use CSS classes to keep your markup organized:
.calculator-wrapper { padding-left: 40px; } .button-group { padding-left: 105px; } - Complete the Button Set: You'll want to add the remaining digits (0-5), operators (
-,*,/), an equals button, and a clear button—all with the samename="button"attribute so PHP can capture them consistently.
Common Pitfalls to Watch For
- Calculation Logic: Right now, there's no way to compute the result. For an equals button, you can use
eval()(but be careful!) or a custom expression parser. Never useeval()on unfiltered input—sanitize the expression first to only allow numbers and valid operators. - State Persistence: Without retaining the display value, the input will reset if the page refreshes. The PHP snippet above fixes this by keeping the current value in the input field.
内容的提问来源于stack exchange,提问作者Amit Paple
相关产品推荐
相关产品推荐

