-
Notifications
You must be signed in to change notification settings - Fork 0
/
calculator.php
73 lines (68 loc) · 2.56 KB
/
calculator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php
function calculate($expression) {
// Remove any whitespace from the expression
$expression = str_replace(' ', '', $expression);
// Handle basic math operations
try {
// Evaluate the expression
$result = eval('return ' . $expression . ';');
if ($result === false) {
throw new Exception('Invalid Expression');
}
return $result;
} catch (Exception $e) {
return 'Error';
}
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$display = isset($_POST['display']) ? $_POST['display'] : '';
if (isset($_POST['button'])) {
$button = $_POST['button'];
// If 'C' is pressed, clear the display
if ($button == 'C') {
$display = '';
}
// If '=' is pressed, calculate the result
elseif ($button == '=') {
$display = calculate($display);
} else {
// Append the pressed button to the display
$display .= $button;
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Calculator</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="calculator">
<form action="calculator.php" method="post">
<input type="text" name="display" id="display" value="<?php echo htmlspecialchars($display); ?>" readonly>
<div class="buttons">
<input type="submit" name="button" value="1">
<input type="submit" name="button" value="2">
<input type="submit" name="button" value="3">
<input type="submit" name="button" value="+">
<input type="submit" name="button" value="4">
<input type="submit" name="button" value="5">
<input type="submit" name="button" value="6">
<input type="submit" name="button" value="-">
<input type="submit" name="button" value="7">
<input type="submit" name="button" value="8">
<input type="submit" name="button" value="9">
<input type="submit" name="button" value="*">
<input type="submit" name="button" value="0">
<input type="submit" name="button" value="C">
<input type="submit" name="button" value="=">
<input type="submit" name="button" value="/">
</div>
</form>
</div>
</body>
</html>