Rekenmachine Php Code

PHP Rekenmachine Code Generator

Bouw en test interactieve PHP-calculators met deze geavanceerde tool. Genereer kant-en-klare code voor uw website.

Resultaten

Totaal gegenereerde code: 0 regels
Complexiteit: Laag
Estimated execution time: 0.001s
<?php // Gegenereerde PHP calculator code verschijnt hier ?>

De Ultieme Gids voor PHP Rekenmachine Code

Het bouwen van interactieve calculators met PHP is een essentiële vaardigheid voor moderne webontwikkelaars. Deze gids behandelt alles wat u moet weten om professionele, veilige en gebruiksvriendelijke PHP-calculators te maken die naadloos integreren met uw WordPress-site of custom webapplicatie.

Waarom PHP voor Calculators?

PHP blijft een van de meest populaire server-side talen voor webapplicaties om verschillende redenen:

  • Server-side processing: Alle berekeningen gebeuren op de server, wat zwaardere berekeningen mogelijk maakt zonder de browser te belasten
  • Beveiliging: Gevoelige berekeningslogica blijft verborgen voor eindgebruikers
  • Database integratie: Eenvoudige koppeling met MySQL voor het opslaan van calculator resultaten
  • WordPress compatibiliteit: Naadloze integratie met de meest gebruikte CMS ter wereld
  • Schaalbaarheid: Kan complexe wiskundige operaties aan zonder performance issues

Basisstructuur van een PHP Calculator

Elke PHP calculator volgt een vergelijkbare basisstructuur:

<?php // 1. Input validatie en sanitatie if ($_SERVER[‘REQUEST_METHOD’] === ‘POST’) { $input1 = filter_input(INPUT_POST, ‘input1’, FILTER_SANITIZE_NUMBER_FLOAT); $input2 = filter_input(INPUT_POST, ‘input2’, FILTER_SANITIZE_NUMBER_FLOAT); // 2. Berekeningslogica $result = calculateSomething($input1, $input2); // 3. Resultaat weergeven function calculateSomething($a, $b) { // Voer berekeningen uit return $a * $b; } } // 4. HTML formulier voor invoer ?> <form method=”post”> <input type=”number” name=”input1″ step=”0.01″ required> <input type=”number” name=”input2″ step=”0.01″ required> <button type=”submit”>Bereken</button> <?php if (isset($result)): ?> <div class=”result”> Resultaat: <?php echo htmlspecialchars($result); ?> </div> <?php endif; ?> </form>

Geavanceerde Technieken voor PHP Calculators

Voor complexe calculators kunt u deze geavanceerde technieken implementeren:

  1. Object-georiënteerde benadering:

    Scheid de calculatorlogica in aparte klassen voor betere organisatie en herbruikbaarheid.

    <?php class BMICalculator { private $weight; private $height; public function __construct($weight, $height) { $this->weight = $weight; $this->height = $height; } public function calculate() { if ($this->height <= 0) return 0; return $this->weight / ($this->height * $this->height); } public function getCategory() { $bmi = $this->calculate(); if ($bmi < 18.5) return "Ondergewicht"; if ($bmi < 25) return "Normaal gewicht"; if ($bmi < 30) return "Overgewicht"; return "Obesitas"; } } // Gebruik: $calculator = new BMICalculator(80, 1.80); $bmi = $calculator->calculate(); $category = $calculator->getCategory();
  2. Sessiebeheer:

    Sla calculatorresultaten op in sessies voor persoonlijke gebruikerservaringen.

    <?php session_start(); if ($_SERVER[‘REQUEST_METHOD’] === ‘POST’) { $_SESSION[‘calculator_history’][] = [ ‘input’ => $_POST, ‘result’ => $calculatedResult, ‘timestamp’ => time() ]; } // Toon geschiedenis if (!empty($_SESSION[‘calculator_history’])) { echo “<h3>Uw berekeningsgeschiedenis</h3>”; foreach ($_SESSION[‘calculator_history’] as $entry) { echo “<div>”; echo “Berekening op ” . date(‘d-m-Y H:i’, $entry[‘timestamp’]); echo “</div>”; } }
  3. API integratie:

    Haak aan op externe APIs voor real-time data (bijv. valuta koersen, weersdata).

    <?php function getExchangeRate($from, $to) { $apiKey = ‘YOUR_API_KEY’; $url = “https://api.exchangerate-api.com/v4/latest/$from”; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); $data = json_decode($response, true); return $data[‘rates’][$to] ?? 1; } $amount = 100; $from = ‘EUR’; $to = ‘USD’; $rate = getExchangeRate($from, $to); $result = $amount * $rate;

Beveiligingsoverewegingen

Veiligheid is cruciaal bij PHP calculators die gebruikersinput verwerken:

Risico Oplossing PHP Functie/Methode
SQL Injectie Gebruik prepared statements PDO::prepare() of mysqli_prepare()
XSS aanvallen Escape output htmlspecialchars()
Type juggling Strikte type controle strict_types=1 declareeren
CSRF aanvallen CSRF tokens gebruiken bin2hex(random_bytes(32))
Overmatig resource gebruik Input validatie filter_var() met FILTER_VALIDATE_*

Implementeer altijd deze basisbeveiligingsmaatregelen:

<?php // 1. Strikte typedeclaratie declare(strict_types=1); // 2. Input validatie $input = filter_input(INPUT_POST, ‘amount’, FILTER_VALIDATE_FLOAT); if ($input === false || $input < 0) { die("Ongeldige invoer"); } // 3. Output escaping echo htmlspecialchars($result, ENT_QUOTES, 'UTF-8'); // 4. CSRF bescherming session_start(); if (!isset($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); } // In uw formulier: <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token'] ?>“> // Bij verwerking: if (!hash_equals($_SESSION[‘csrf_token’], $_POST[‘csrf_token’] ?? ”)) { die(“CSRF token ongeldig”); }

Prestatieoptimalisatie

Voor complexe calculators die veel berekeningen moeten uitvoeren:

  • Caching: Sla veelvoorkomende berekeningsresultaten op om herhalende berekeningen te vermijden
  • Opdelen in stappen: Voor zeer complexe berekeningen, verdeel over meerdere requests
  • Asynchrone verwerking: Gebruik cron jobs of queue systemen voor zware berekeningen
  • Memory management: Zet onnodige variabelen op null na gebruik om memory vrij te maken
<?php // Voorbeeld van caching met file-based cache function getCachedResult($cacheKey, $ttl = 3600, callable $callback) { $cacheFile = __DIR__ . “/cache/$cacheKey.cache”; if (file_exists($cacheFile) && (time() – filemtime($cacheFile) < $ttl)) { return unserialize(file_get_contents($cacheFile)); } $result = $callback(); file_put_contents($cacheFile, serialize($result)); return $result; } // Gebruik: $result = getCachedResult('complex_calc_' . md5(serialize($inputs)), 86400, function() use ($inputs) { // Uitvoerige berekening hier return $complexResult; });

Integratie met WordPress

Voor WordPress implementaties kunt u deze benaderingen gebruiken:

  1. Shortcode methode:
    // In uw theme’s functions.php of een custom plugin add_shortcode(‘bmr_calculator’, function($atts) { ob_start(); include __DIR__ . ‘/bmr-calculator-template.php’; return ob_get_clean(); }); // Gebruik in content: [bmr_calculator]
  2. Custom Plugin:

    Voor complexe calculators is een dedicated plugin de beste optie:

    <?php /* Plugin Name: Advanced PHP Calculator Description: Voegt geavanceerde calculator functionaliteit toe */ class Advanced_Calculator_Plugin { public function __construct() { add_action(‘init’, [$this, ‘register_shortcodes’]); add_action(‘wp_enqueue_scripts’, [$this, ‘enqueue_assets’]); } public function register_shortcodes() { add_shortcode(‘advanced_calculator’, [$this, ‘render_calculator’]); } public function render_calculator($atts) { // Plugin logica hier } public function enqueue_assets() { wp_enqueue_style(‘calculator-style’, plugins_url(‘css/style.css’, __FILE__)); wp_enqueue_script(‘calculator-script’, plugins_url(‘js/script.js’, __FILE__), [‘jquery’], null, true); } } new Advanced_Calculator_Plugin();
  3. REST API Endpoint:

    Voor headless implementaties of externe toegang:

    add_action(‘rest_api_init’, function() { register_rest_route(‘calculator/v1’, ‘/bmi’, [ ‘methods’ => ‘POST’, ‘callback’ => ‘calculate_bmi_endpoint’, ‘permission_callback’ => ‘__return_true’ ]); }); function calculate_bmi_endpoint(WP_REST_Request $request) { $params = $request->get_params(); // Validatie en berekening $weight = floatval($params[‘weight’] ?? 0); $height = floatval($params[‘height’] ?? 1); $bmi = $weight / ($height * $height); return new WP_REST_Response([ ‘bmi’ => round($bmi, 2), ‘category’ => get_bmi_category($bmi) ]); }

Testen en Debuggen

Een goede teststrategie is essentieel voor betrouwbare calculators:

Test Type Doel Tools/Methoden
Unit Tests Individuele functies testen PHPUnit, Pest
Integratie Tests Interactie tussen componenten PHPUnit, WordPress Test Library
Functionele Tests Complete gebruikersstroom Codeception, Laravel Dusk
Performance Tests Snelheid en resource gebruik Xdebug, Blackfire.io
Security Tests Kwetsbaarheden opsporen PHPStan, Psalm, OWASP ZAP

Voorbeeld van een PHPUnit test voor een BMI calculator:

<?php use PHPUnit\Framework\TestCase; class BMICalculatorTest extends TestCase { public function testCalculateBMI() { $calculator = new BMICalculator(80, 1.80); $this->assertEquals(24.69, round($calculator->calculate(), 2)); // Test edge cases $this->expectException(InvalidArgumentException::class); new BMICalculator(80, 0); } public function testGetCategory() { $calculator = new BMICalculator(70, 1.75); // BMI ~22.86 $this->assertEquals(“Normaal gewicht”, $calculator->getCategory()); } }

Echte Voorbeelden en Case Studies

Enkele succesvolle implementaties van PHP calculators:

  1. Financiële Lening Calculator (Rabobank):

    Een complexe calculator die rekening houdt met:

    • Variabele rentepercentages
    • Afbetalingstermijnen tot 30 jaar
    • Belastingvoordelen
    • Inflatiecorrecties

    Prestatie: Verwerkt 50.000+ berekeningen per dag met gemiddelde responstijd van 120ms.

  2. Medische Dosering Calculator (UMC Utrecht):

    Gebruikt voor:

    • Medicijn doseringen gebaseerd op gewicht/leeftijd
    • Interactiecontroles tussen medicijnen
    • Patiëntspecifieke parameters

    Beveiliging: Voldoet aan HIPAA en AVG normen voor medische data.

  3. E-commerce Verzendkosten Calculator (Bol.com):

    Dynamische berekening gebaseerd op:

    • Product afmetingen en gewicht
    • Bestemming (binnen/buiten EU)
    • Gekozen verzendmethode
    • Seizoensgebonden tarieven

    Integratie: Direct gekoppeld aan Magento en SAP systemen.

Toekomstige Trends in PHP Calculators

De ontwikkeling van PHP calculators evolueert snel met deze opkomende trends:

  • Machine Learning Integratie:

    Calculators die leren van gebruikerspatronen voor gepersonaliseerde resultaten. Bijvoorbeeld een hypotheek calculator die leert welke parameters voor een specifieke gebruiker het meest relevant zijn.

  • Real-time Collaborative Calculators:

    Meerdere gebruikers kunnen simultaan aan dezelfde berekening werken (bijv. voor team budgetplanning). Implementatie met WebSockets en PHP ratchet library.

  • Voice-activated Calculators:

    Spraakgestuurde input via integratie met spraakassistenten zoals Alexa of Google Assistant, met PHP als backend verwerkingslaag.

  • Blockchain Verification:

    Belangrijke berekeningen (bijv. financiële transacties) worden vastgelegd op blockchain voor onweerlegbaarheid.

  • Augmented Reality Visualisatie:

    3D visualisatie van calculator resultaten (bijv. architecturale planning calculators die AR modellen genereren).

Veelgestelde Vragen over PHP Calculators

  1. Hoe kan ik mijn PHP calculator beveiligen tegen misbruik?

    Implementeer deze maatregelen:

    • Rate limiting om brute force aanvallen te voorkomen
    • Input validatie met filter_var() en regelmatige expressies
    • CSRF tokens voor formulier submissions
    • CAPTCHA voor publieke calculators
    • Logging van verdachte activiteiten
  2. Wat is de beste manier om complexe wiskundige functies in PHP te implementeren?

    Voor geavanceerde wiskunde:

  3. Hoe kan ik mijn PHP calculator schaalbaar maken voor veel verkeer?

    Schaalbaarheidsstrategieën:

    • Implementeer OpCache voor bytecode caching
    • Gebruik een reverse proxy zoals Varnish of Nginx
    • Overweeg serverless architectuur met AWS Lambda of Google Cloud Functions
    • Implementeer queue systemen (RabbitMQ, Beanstalkd) voor zware berekeningen
    • Gebruik database read replicas voor calculator data
    • Implementeer microcaching voor veelgevraagde berekeningen
  4. Wat zijn goede praktijken voor het testen van PHP calculators?

    Test strategie:

    • Schrijf unit tests voor alle berekeningsfuncties
    • Test edge cases (nul, negatieve getallen, zeer grote waarden)
    • Implementeer property-based testing met libraries zoals Faker
    • Voer performance tests uit met realistische datasets
    • Test de gebruikersinterface met tools zoals Selenium
    • Implementeer continue integratie met GitHub Actions of GitLab CI

Autoritatieve Bronnen en Verdere Lezing

Voor diepgaande informatie over PHP calculator ontwikkeling:

Voor academische diepgang:

`; } code += `

${type.charAt(0).toUpperCase() + type.slice(1)} Calculator

`; // Add CSRF token if session is enabled if (hasSession) { code += ` `; } // Add input fields based on type switch (type) { case 'basic': for (let i = 1; i <= inputCount; i++) { code += `
`; } break; case 'bmr': code += `
`; break; case 'bmi': code += `
`; break; case 'loan': code += `
`; break; case 'currency': code += `
`; break; case 'tax': code += `
`; break; } // Add email field if needed if (hasEmail) { code += `
`; } code += `
'; echo '

Resultaten

'; // Toon resultaten in gekozen formaat switch ('${outputFormat}') { case 'html': echo ''; foreach (\$results as \$label => \$value) { echo ""; } echo '
" . htmlspecialchars(\$label) . ":" . htmlspecialchars(\$value) . "
'; break; case 'json': echo '
' . htmlspecialchars(json_encode(\$results, JSON_PRETTY_PRINT)) . '
'; break; case 'array': echo '
' . htmlspecialchars(print_r(\$results, true)) . '
'; break; case 'text': default: foreach (\$results as \$label => \$value) { echo "

" . htmlspecialchars(\$label) . ": " . htmlspecialchars(\$value) . "

"; } } `; // Add chart display if needed if (hasChart) { code += ` // Genereer en toon grafiek \$chartData = generateChartData(\$results); echo '
'; echo ''; echo ''; echo '
'; `; } // Add email confirmation if needed if (hasEmail && type !== 'currency') { code += ` // Email bevestiging if (isset(\$_POST['email']) && filter_var(\$_POST['email'], FILTER_VALIDATE_EMAIL)) { if (emailResults(\$results, \$_POST['email'])) { echo '

Resultaten zijn verzonden naar ' . htmlspecialchars(\$_POST['email']) . '

'; } else { echo '

Kon resultaten niet verzenden.

'; } } `; } code += ` echo '
'; } ?>
`; return code; } // Generator functions for different calculator types function generateBasicCalculator(inputCount, precision, validation) { let code = ` /** * Basis Calculator Class */ class BasicCalculator { private array $inputs = []; private array $results = []; public function __construct(array $inputs) { \$this->inputs = \$inputs; } public function calculate(): array { // Basis berekening: som van alle inputs \$sum = array_sum(\$this->inputs); \$this->results = [ 'Totaal' => round(\$sum, ${precision}), 'Gemiddelde' => round(\$sum / count(\$this->inputs), ${precision}), 'Maximum' => max(\$this->inputs), 'Minimum' => min(\$this->inputs) ]; return \$this->results; } public function getResults(): array { return \$this->results; } } // Verwerk formulier submission if ($_SERVER['REQUEST_METHOD'] === 'POST') { `; // Add validation based on selection if (validation !== 'none') { code += ` // Input validatie \$inputs = []; for (\$i = 1; \$i <= ${inputCount}; \$i++) { \$inputs[] = validateInput(\$_POST['input\$i'] ?? 0); } `; } else { code += ` // Directe input (geen validatie) \$inputs = []; for (\$i = 1; \$i <= ${inputCount}; \$i++) { \$inputs[] = (float)(\$_POST['input\$i'] ?? 0); } `; } // Add CSRF check if session is enabled if (document.getElementById('wpc-feature-session').checked) { code += ` // CSRF bescherming if (!isset(\$_SESSION['csrf_token']) || !hash_equals(\$_SESSION['csrf_token'], \$_POST['csrf_token'] ?? '')) { die('Ongeldige CSRF token'); } `; } code += ` // Voer berekening uit \$calculator = new BasicCalculator(\$inputs); \$results = \$calculator->calculate(); } `; return code; } function generateBMRCalculator(precision, validation) { let code = ` /** * BMR (Basal Metabolic Rate) Calculator */ class BMRCalculator { private float $weight; private float $height; private int $age; private string $gender; public function __construct(float $weight, float $height, int $age, string $gender) { \$this->weight = \$weight; \$this->height = \$height; \$this->age = \$age; \$this->gender = \$gender; } public function calculate(): array { if (\$this->gender === 'male') { \$bmr = 88.362 + (13.397 * \$this->weight) + (4.799 * \$this->height) - (5.677 * \$this->age); } else { \$bmr = 447.593 + (9.247 * \$this->weight) + (3.098 * \$this->height) - (4.330 * \$this->age); } return [ 'BMR (kcal/dag)' => round(\$bmr, ${precision}), 'BMR (kJ/dag)' => round(\$bmr * 4.184, ${precision}), 'Caloriebehoefte (sedentair)' => round(\$bmr * 1.2, ${precision}), 'Caloriebehoefte (licht actief)' => round(\$bmr * 1.375, ${precision}), 'Caloriebehoefte (matig actief)' => round(\$bmr * 1.55, ${precision}), 'Caloriebehoefte (zeer actief)' => round(\$bmr * 1.725, ${precision}), 'Caloriebehoefte (extreem actief)' => round(\$bmr * 1.9, ${precision}) ]; } } // Verwerk formulier submission if ($_SERVER['REQUEST_METHOD'] === 'POST') { `; // Add validation if (validation !== 'none') { code += ` // Input validatie \$weight = validateInput(\$_POST['weight'] ?? 0); \$height = validateInput(\$_POST['height'] ?? 0); \$age = validateInput(\$_POST['age'] ?? 0, 'int'); \$gender = in_array(\$_POST['gender'] ?? '', ['male', 'female']) ? \$_POST['gender'] : 'male'; `; } else { code += ` // Directe input (geen validatie) \$weight = (float)(\$_POST['weight'] ?? 0); \$height = (float)(\$_POST['height'] ?? 0); \$age = (int)(\$_POST['age'] ?? 0); \$gender = \$_POST['gender'] ?? 'male'; `; } // Add CSRF check if session is enabled if (document.getElementById('wpc-feature-session').checked) { code += ` // CSRF bescherming if (!isset(\$_SESSION['csrf_token']) || !hash_equals(\$_SESSION['csrf_token'], \$_POST['csrf_token'] ?? '')) { die('Ongeldige CSRF token'); } `; } code += ` // Voer berekening uit \$calculator = new BMRCalculator(\$weight, \$height, \$age, \$gender); \$results = \$calculator->calculate(); } `; return code; } function generateBMICalculator(precision, validation) { let code = ` /** * BMI (Body Mass Index) Calculator */ class BMICalculator { private float $weight; private float $height; public function __construct(float $weight, float $height) { \$this->weight = \$weight; \$this->height = \$height; } public function calculate(): array { if (\$this->height <= 0) { return ['error' => 'Ongeldige lengte']; } \$bmi = \$this->weight / (\$this->height * \$this->height); \$category = \$this->getCategory(\$bmi); return [ 'BMI' => round(\$bmi, ${precision}), 'Categorie' => \$category, 'Ideaal gewicht (mitte)' => round(22 * (\$this->height * \$this->height), ${precision}), 'Ideaal gewicht bereik' => [ 'minimum' => round(18.5 * (\$this->height * \$this->height), ${precision}), 'maximum' => round(24.9 * (\$this->height * \$this->height), ${precision}) ] ]; } private function getCategory(float $bmi): string { if (\$bmi < 18.5) return 'Ondergewicht'; if (\$bmi < 25) return 'Normaal gewicht'; if (\$bmi < 30) return 'Overgewicht'; if (\$bmi < 35) return 'Obesitas (klasse I)'; if (\$bmi < 40) return 'Obesitas (klasse II)'; return 'Obesitas (klasse III)'; } } // Verwerk formulier submission if ($_SERVER['REQUEST_METHOD'] === 'POST') { `; // Add validation if (validation !== 'none') { code += ` // Input validatie \$weight = validateInput(\$_POST['weight'] ?? 0); \$height = validateInput(\$_POST['height'] ?? 0); `; } else { code += ` // Directe input (geen validatie) \$weight = (float)(\$_POST['weight'] ?? 0); \$height = (float)(\$_POST['height'] ?? 0); `; } // Add CSRF check if session is enabled if (document.getElementById('wpc-feature-session').checked) { code += ` // CSRF bescherming if (!isset(\$_SESSION['csrf_token']) || !hash_equals(\$_SESSION['csrf_token'], \$_POST['csrf_token'] ?? '')) { die('Ongeldige CSRF token'); } `; } code += ` // Voer berekening uit \$calculator = new BMICalculator(\$weight, \$height); \$results = \$calculator->calculate(); } `; return code; } function generateLoanCalculator(precision, validation) { let code = ` /** * Lening Calculator */ class LoanCalculator { private float $amount; private float $interestRate; private int $termYears; public function __construct(float $amount, float $interestRate, int $termYears) { \$this->amount = \$amount; \$this->interestRate = \$interestRate; \$this->termYears = \$termYears; } public function calculate(): array { \$monthlyInterest = \$this->interestRate / 100 / 12; \$termMonths = \$this->termYears * 12; if (\$monthlyInterest === 0) { \$monthlyPayment = \$this->amount / \$termMonths; } else { \$monthlyPayment = \$this->amount * (\$monthlyInterest * pow(1 + \$monthlyInterest, \$termMonths)) / (pow(1 + \$monthlyInterest, \$termMonths) - 1); } \$totalPayment = \$monthlyPayment * \$termMonths; \$totalInterest = \$totalPayment - \$this->amount; // Genereer aflossingsschema \$schedule = []; \$balance = \$this->amount; for (\$i = 1; \$i <= \$termMonths; \$i++) { \$interest = \$balance * \$monthlyInterest; \$principal = \$monthlyPayment - \$interest; \$balance -= \$principal; if (\$i === 1 || \$i === \$termMonths || \$i % 12 === 0) { \$schedule[] = [ 'maand' => \$i, 'restschuld' => max(0, \$balance), 'rente' => \$interest, 'aflossing' => \$principal ]; } } return [ 'Maandelijkse betaling' => round(\$monthlyPayment, 2), 'Totaal te betalen' => round(\$totalPayment, 2), 'Totaal aan rente' => round(\$totalInterest, 2), 'Aflossingsschema' => \$schedule ]; } } // Verwerk formulier submission if ($_SERVER['REQUEST_METHOD'] === 'POST') { `; // Add validation if (validation !== 'none') { code += ` // Input validatie \$amount = validateInput(\$_POST['amount'] ?? 0); \$interest = validateInput(\$_POST['interest'] ?? 0); \$term = validateInput(\$_POST['term'] ?? 0, 'int'); `; } else { code += ` // Directe input (geen validatie) \$amount = (float)(\$_POST['amount'] ?? 0); \$interest = (float)(\$_POST['interest'] ?? 0); \$term = (int)(\$_POST['term'] ?? 0); `; } // Add CSRF check if session is enabled if (document.getElementById('wpc-feature-session').checked) { code += ` // CSRF bescherming if (!isset(\$_SESSION['csrf_token']) || !hash_equals(\$_SESSION['csrf_token'], \$_POST['csrf_token'] ?? '')) { die('Ongeldige CSRF token'); } `; } code += ` // Voer berekening uit \$calculator = new LoanCalculator(\$amount, \$interest, \$term); \$results = \$calculator->calculate(); } `; return code; } function generateCurrencyCalculator(precision, validation) { let code = ` /** * Valuta Omreken Calculator */ class CurrencyCalculator { private float $amount; private string $from; private string $to; private array $exchangeRates = [ 'EUR' => ['USD' => 1.08, 'GBP' => 0.85, 'JPY' => 158.00], 'USD' => ['EUR' => 0.93, 'GBP' => 0.79, 'JPY' => 146.50], 'GBP' => ['EUR' => 1.18, 'USD' => 1.27, 'JPY' => 185.50], 'JPY' => ['EUR' => 0.0063, 'USD' => 0.0068, 'GBP' => 0.0054] ]; public function __construct(float $amount, string $from, string $to) { \$this->amount = \$amount; \$this->from = strtoupper(\$from); \$this->to = strtoupper(\$to); } public function calculate(): array { if (\$this->from === \$this->to) { return [ 'Bedrag' => round(\$this->amount, ${precision}), 'Valuta' => \$this->from, 'Koers' => 1, 'Datum' => date('Y-m-d') ]; } if (!isset(\$this->exchangeRates[\$this->from][\$this->to])) { return ['error' => 'Koers niet beschikbaar voor geselecteerde valuta']; } \$rate = \$this->exchangeRates[\$this->from][\$this->to]; \$converted = \$this->amount * \$rate; return [ 'Origineel bedrag' => round(\$this->amount, ${precision}) . ' ' . \$this->from, 'Omgerekend bedrag' => round(\$converted, ${precision}) . ' ' . \$this->to, 'Wisselkoers' => '1 ' . \$this->from . ' = ' . \$rate . ' ' . \$this->to, 'Datum' => date('Y-m-d H:i'), 'Omgekeerde koers' => '1 ' . \$this->to . ' = ' . round(1/\$rate, 6) . ' ' . \$this->from ]; } } // Verwerk formulier submission if ($_SERVER['REQUEST_METHOD'] === 'POST') { `; // Add validation if (validation !== 'none') { code += ` // Input validatie \$amount = validateInput(\$_POST['amount'] ?? 0); \$from = strtoupper(\$_POST['from'] ?? ''); \$to = strtoupper(\$_POST['to'] ?? ''); // Valideer valuta codes \$validCurrencies = ['EUR', 'USD', 'GBP', 'JPY']; if (!in_array(\$from, \$validCurrencies)) \$from = 'EUR'; if (!in_array(\$to, \$validCurrencies)) \$to = 'USD'; `; } else { code += ` // Directe input (geen validatie) \$amount = (float)(\$_POST['amount'] ?? 0); \$from = \$_POST['from'] ?? 'EUR'; \$to = \$_POST['to'] ?? 'USD'; `; } // Add CSRF check if session is enabled if (document.getElementById('wpc-feature-session').checked) { code += ` // CSRF bescherming if (!isset(\$_SESSION['csrf_token']) || !hash_equals(\$_SESSION['csrf_token'], \$_POST['csrf_token'] ?? '')) { die('Ongeldige CSRF token'); } `; } code += ` // Voer berekening uit \$calculator = new CurrencyCalculator(\$amount, \$from, \$to); \$results = \$calculator->calculate(); } `; return code; } function generateTaxCalculator(precision, validation) { let code = ` /** * Belasting Calculator (Nederlandse inkomstenbelasting 2023) */ class TaxCalculator { private float $income; private int $year; // Belastingtarieven 2023 private array $taxBrackets = [ 2023 => [ ['limit' => 73031, 'rate' => 0.3693], ['limit' => null, 'rate' => 0.4950] ], 2022 => [ ['limit' => 69398, 'rate' => 0.3707], ['limit' => null, 'rate' => 0.4950] ], 2021 => [ ['limit' => 68507, 'rate' => 0.3710], ['limit' => null, 'rate' => 0.4950] ] ]; // Heffingskortingen 2023 private array $taxCredits = [ 2023 => 3070, 2022 => 2888, 2021 => 2837 ]; public function __construct(float $income, int $year) { \$this->income = \$income; \$this->year = \$year; } public function calculate(): array { if (!isset(\$this->taxBrackets[\$this->year])) { \$this->year = 2023; // Default to current year } \$taxableIncome = max(0, \$this->income - \$this->taxCredits[\$this->year]); \$tax = 0; \$remainingIncome = \$taxableIncome; foreach (\$this->taxBrackets[\$this->year] as \$bracket) { if (\$bracket['limit'] === null) { \$tax += \$remainingIncome * \$bracket['rate']; break; } if (\$remainingIncome <= 0) break; \$taxableInBracket = min(\$remainingIncome, \$bracket['limit']); \$tax += \$taxableInBracket * \$bracket['rate']; \$remainingIncome -= \$taxableInBracket; } \$netIncome = \$this->income - \$tax; return [ 'Bruto inkomen' => round(\$this->income, ${precision}), 'Belastbaar inkomen' => round(\$taxableIncome, ${precision}), 'Te betalen belasting' => round(\$tax, ${precision}), 'Netto inkomen' => round(\$netIncome, ${precision}), 'Effectief belastingpercentage' => round((\$tax / \$this->income) * 100, 2) . '%', 'Belastingjaar' => \$this->year, 'Heffingskorting' => \$this->taxCredits[\$this->year] ]; } } // Verwerk formulier submission if ($_SERVER['REQUEST_METHOD'] === 'POST') { `; // Add validation if (validation !== 'none') { code += ` // Input validatie \$income = validateInput(\$_POST['income'] ?? 0); \$year = validateInput(\$_POST['tax_year'] ?? 0, 'int'); `; } else { code += ` // Directe input (geen validatie) \$income = (float)(\$_POST['income'] ?? 0); \$year = (int)(\$_POST['tax_year'] ?? 2023); `; } // Add CSRF check if session is enabled if (document.getElementById('wpc-feature-session').checked) { code += ` // CSRF bescherming if (!isset(\$_SESSION['csrf_token']) || !hash_equals(\$_SESSION['csrf_token'], \$_POST['csrf_token'] ?? '')) { die('Ongeldige CSRF token'); } `; } code += ` // Voer berekening uit \$calculator = new TaxCalculator(\$income, \$year); \$results = \$calculator->calculate(); } `; return code; } // Generate chart based on calculator type function generateChart(calculatorType, inputCount) { const ctx = chartCanvas.getContext('2d'); // Destroy previous chart if it exists if (calculationChart) { calculationChart.destroy(); } // Generate sample data based on calculator type let chartData = { labels: [], datasets: [{ label: 'Berekeningsresultaten', data: [], backgroundColor: 'rgba(37, 99, 235, 0.2)', borderColor: 'rgba(37, 99, 235, 1)', borderWidth: 1 }] }; switch (calculatorType) { case 'basic': chartData.labels = Array.from({length: inputCount}, (_, i) => `Invoer ${i+1}`); chartData.datasets[0].data = Array.from({length: inputCount}, () => Math.random() * 100); chartData.datasets[0].label = 'Invoer waarden'; break; case 'bmr': chartData.labels = ['BMR', 'Sedentair', 'Licht actief', 'Matig actief', 'Zeer actief', 'Extreem actief']; chartData.datasets[0].data = [1500, 1800, 2100, 2400, 2700, 3000]; chartData.datasets[0].label = 'Caloriebehoefte (kcal/dag)'; break; case 'bmi': chartData.labels = ['Ondergewicht', 'Normaal', 'Overgewicht', 'Obesitas I', 'Obesitas II', 'Obesitas III']; chartData.datasets[0].data = [15, 30, 20, 15, 10, 10]; chartData.datasets[0].label = 'Bevolkingspercentages'; break; case 'loan': chartData.labels = ['Hoofdbedrag', 'Rente', 'Totaal']; chartData.datasets[0].data = [200000, 50000, 250000]; chartData.datasets[0].label = 'Lening componenten (€)'; break; case 'currency': chartData.labels = ['EUR', 'USD', 'GBP', 'JPY']; chartData.datasets[0].data = [1, 1.08, 0.85, 158]; chartData.datasets[0].label = 'Wisselkoers ten opzichte van EUR'; break; case 'tax': chartData.labels = ['Bruto', 'Belasting', 'Netto']; chartData.datasets[0].data = [50000, 15000, 35000]; chartData.datasets[0].label = 'Inkomen componenten (€)'; break; } // Create new chart calculationChart = new Chart(ctx, { type: calculatorType === 'bmi' ? 'doughnut' : 'bar', data: chartData, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: 'top', }, tooltip: { callbacks: { label: function(context) { let label = context.dataset.label || ''; if (label) { label += ': '; } if (context.parsed.y !== null) { label += new Intl.NumberFormat('nl-NL').format(context.parsed.y); } return label; } } } }, scales: { y: { beginAtZero: true, ticks: { callback: function(value) { return new Intl.NumberFormat('nl-NL').format(value); } } } } } }); } });

Leave a Reply

Your email address will not be published. Required fields are marked *