HexDecBinCalc/index.php

112 lines
4.2 KiB
PHP

<?php
include "./conversions.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="./style.css">
<title>HexDecBin Calc</title>
</head>
<body>
<div class="inputs">
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="get">
<?php
session_start();
$bin = $dec = $hex = 0;
$new = false;
// Check if GET params are set
if (!isset($_GET['binary']) || !isset($_GET['decimal']) || !isset($_GET['hexadecimal'])) {
$new = true;
}
if (!isset($_SESSION['bin']) || !isset($_SESSION['dec']) || !isset($_SESSION['hex'])) {
$_SESSION['bin'] = $_SESSION['dec'] = $_SESSION['hex'] = 0;
}
$last_bin = $_SESSION['bin'];
$last_dec = $_SESSION['dec'];
$last_hex = $_SESSION['hex'];
if (!$new) {
$bin = $_GET['binary'];
$dec = $_GET['decimal'];
$hex = $_GET['hexadecimal'];
}
// Check if it's a pasted url (all params are passed and aren't 0)
if (isset($_GET['binary']) && isset($_GET['decimal']) && isset($_GET['hexadecimal']) &&
$_GET['binary'] != 0 && $_GET['decimal'] != 0 && $_GET['hexadecimal'] != 0 &&
$bin == $last_bin && $dec == $last_dec && $hex == $last_hex) {
$new = true;
}
if (!$new) {
if ($bin == 0 && $dec == 0) {
$bin = hex_to_binary($hex);
$_SESSION['bin'] = $bin;
$dec = hex_to_decimal($hex);
$_SESSION['dec'] = $dec;
$_SESSION['hex'] = $hex;
} else if ($bin == 0 && $hex == 0) {
$bin = decimal_to_binary($dec);
$_SESSION['bin'] = $bin;
$_SESSION['dec'] = $dec;
$hex = decimal_to_hex($dec);
$_SESSION['hex'] = $hex;
} else if ($dec == 0 && $hex == 0) {
$_SESSION['bin'] = $bin;
$dec = binary_to_decimal($bin);
$_SESSION['dec'] = $dec;
$hex = binary_to_hex($bin);
$_SESSION['hex'] = $hex;
}
else {
if ($bin == $last_bin && $dec == $last_dec && $hex != $last_hex) {
$bin = hex_to_binary($hex);
$_SESSION['bin'] = $bin;
$dec = hex_to_decimal($hex);
$_SESSION['dec'] = $dec;
$_SESSION['hex'] = $hex;
} else if ($bin == $last_bin && $hex == $last_hex && $dec != $last_dec) {
$bin = decimal_to_binary($dec);
$_SESSION['bin'] = $bin;
$_SESSION['dec'] = $dec;
$hex = decimal_to_hex($dec);
$_SESSION['hex'] = $hex;
} else if ($dec == $last_dec && $hex == $last_hex && $bin != $last_bin) {
$_SESSION['bin'] = $bin;
$dec = binary_to_decimal($bin);
$_SESSION['dec'] = $dec;
$hex = binary_to_hex($bin);
$_SESSION['hex'] = $hex;
} else {
$bin = $dec = $hex = 0;
}
}
}
?>
<div>
<label for="binary">Binary: </label>
<input type="text" id="binary" name="binary" value="<?php echo $bin; ?>">
</div>
<div>
<label for="decimal">Decimal: </label>
<input type="text" id="decimal" name="decimal" value="<?php echo $dec; ?>">
</div>
<div>
<label for="hexadecimal">Hexadecimal: </label>
<input type="text" id="hexadecimal" name="hexadecimal" value="<?php echo $hex; ?>">
</div>
<div>
<input class="submit" type="submit">
</div>
</form>
</div>
</body>
</html>