You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP/HTML薪资计算网站:隐藏未选额外项及Cookie存储计算历史功能开发需求咨询

Hey there! Let's fix up your salary calculator with the two features you need. I've revised your code and added explanations for each change below:

Key Changes Made

1. Optimized Display Logic for Empty Extras

We'll now only show the "Extras" section if the user has selected at least one extra task. This is done by wrapping the Extras HTML in a conditional check for a non-empty $extra array.

2. Improved Cookie Storage Functionality

  • Save only when checked: The cookie is now only updated if the user ticks the "save this details" checkbox.
  • 1-week validity: Adjusted the cookie expiration from 30 days to 7 days (86400 * 7 seconds).
  • Preserve existing history: Fixed the initial cookie setup so it doesn't overwrite existing history every time the page loads—now it only sets the default empty array if the cookie doesn't exist yet.
  • Cleaner history rendering: Ensured the stored extra details display correctly when viewing past calculations.

Revised Full Code

<html>
<body>
<?php
$none = 0;
$cookie_name = 'historyDetails';
$message = '';
date_default_timezone_set('Asia/Bahrain');

// Initialize cookie only if it doesn't exist yet
if (!isset($_COOKIE[$cookie_name])) {
    $cookie_value = '[]';
    setcookie($cookie_name, $cookie_value, time() + (86400 * 7), "/"); // 7 days validity
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (isset($_POST['calculate_salary'])) {
        // Get all form values
        $details = $_POST;
        $basic = 0;
        $extra_tags = '';
        
        // Set basic salary (default to 0 if empty)
        if (isset($details['basic']) && !empty($details['basic'])) {
            $basic = $details['basic'];
        }
        
        $extra = [];
        // Collect selected extra tasks
        if (isset($details['extra'])) {
            foreach ($details['extra'] as $value) {
                $temp = explode("#", $value);
                $extra[(integer)$temp[0]] = $temp[1];
                $extra_tags .= '<li>' . $temp[1] . '</li>';
            }
        }
        
        // Calculate marital status allowance
        $BD = 0;
        switch($details['ms']) {
            case 'single':
                $BD = 50;
                break;
            case 'married':
                $BD = 100;
                break;
        }
        
        // Calculate total salary
        $total = $basic + array_sum(array_keys($extra)) + $BD;
        
        // Save to cookie ONLY if "save this details" is checked
        if (isset($_POST['save'])) {
            $cookie_values = (array)json_decode($_COOKIE[$cookie_name]);
            $history_value = [
                'basic' => $basic,
                'extra' => $extra, // Store full extra array (amount => description)
                'ms_allowance' => $BD,
                'total' => $total,
                'date' => date("Y-m-d"),
                'time' => date("h:i:sa")
            ];
            array_push($cookie_values, $history_value);
            setcookie($cookie_name, json_encode($cookie_values), time() + (86400 * 7), "/"); // 7 days
        }
        
        // Generate display HTML
        $message = '<br/><br/><br/><ul>';
        $message .= '<li>Salary Details: Total Salary is BD ' . (string)$total . '</li>';
        
        // Only show Extras section if there are selected extras
        if (!empty($extra)) {
            $message .= '<li>Extras:</li><ol>' . $extra_tags . '</ol>';
        }
        
        $message .= '</ul>';
    } elseif (isset($_POST['view_history'])) {
        $histories = (array)json_decode($_COOKIE[$cookie_name]);
        $history_data = '';
        
        foreach ($histories as $history) {
            $history = (array)$history;
            $extra_value = '';
            
            // Render extra items from stored data
            foreach ((array)$history['extra'] as $amount => $description) {
                $extra_value .= '<li>' . $description . ' (BD ' . $amount . ')</li>';
            }
            
            $history_data .= '<li>Date: ' . (string)$history['date'] . ' Time: ' . (string)$history['time'] . '<br/>';
            $history_data .= '<ul>';
            $history_data .= '<li>Salary Details: Total Salary is BD <b>' . (string)$history['total'] . '</b></li>';
            
            // Only show Extras in history if there were any
            if (!empty($history['extra'])) {
                $history_data .= '<li>Extras:</li><ol>' . $extra_value . '</ol>';
            }
            
            $history_data .= '</ul></li><br/>';
        }
        
        $message = '<br/><h3>History details of your old salary calculations</h3><br/><br/><ol>' . $history_data . '</ol>';
    }
?>
<form method='post' action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
    Basic Salary <input type='number' name='basic' /><br />
    Marital Status: <br />
    <input type='radio' name='ms' value='single' checked /> Single <br />
    <input type='radio' name='ms' value='married' /> Married <br />
    Extra: <br />
    <input type='checkbox' name="extra[]" value="200#Work on Weekend" /> Work on Weekend - BD 200<br />
    <input type='checkbox' name="extra[]" value="100#Work Night Shift" /> Work Night Shift - BD 100<br />
    <input type='checkbox' name="extra[]" value="400#Work Abroad" /> Work Abroad - BD 400<br />
    <br /><br />
    <input type='checkbox' name="save" value="1" /> save this details<br />
    <br />
    <input type='submit' name='calculate_salary' value='Calculate Salary' />
    <input type='submit' name='view_history' value='View History' />
</form>
<?php echo($message); ?>
</body>
</html>

Quick Notes on the Changes

  • For the display logic: We added if (!empty($extra)) checks both when showing the current calculation and the history, so the Extras section stays hidden when nothing is selected.
  • For the cookie: We moved the initial cookie setup inside a check for !isset($_COOKIE[$cookie_name]) to avoid overwriting existing history. Also, the cookie is only updated when $_POST['save'] is present (i.e., the checkbox is ticked), and we set the expiration to 7 days.
  • In the history rendering, we now display both the extra task description and its amount for clarity.

内容的提问来源于stack exchange,提问作者fatema alzaki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 22:47:39