Server-Side Scripting/Requests/PHP
Appearance
index.php
[edit | edit source]<?php
// Converts a Fahrenheit temperature to Celsius using a GET request and
// converts a Celsius temperature to Fahrenheit using a POST request.
//
// References:
// https://www.mathsisfun.com/temperature-conversion.html
// https://en.wikibooks.org/wiki/PHP_Programming
// https://www.tutorialspoint.com/php/php_get_post.htm
$fahrenheit = process_fahrenheit();
$celsius = process_celsius();
function process_fahrenheit() {
if (isset($_GET["fahrenheit"]) && is_numeric($_GET["fahrenheit"])) {
$fahrenheit = $_GET["fahrenheit"];
$celsius = ($fahrenheit - 32) * 5 / 9;
$result = $fahrenheit . "° Fahrenheit is " .
$celsius . "° Celsius";
}
else {
$result = "";
}
return $result;
}
function process_celsius() {
if (isset($_POST["celsius"]) && is_numeric($_POST["celsius"])) {
$celsius = $_POST["celsius"];
$fahrenheit = $celsius * 9 / 5 + 32;
$result = $celsius . "° Celsius is " .
$fahrenheit . "° Fahrenheit";
}
else {
$result = "";
}
return $result;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Lesson 3</title>
<link rel="stylesheet" href="styles.css">
<style>
p {
min-height: 1em;
}
</style>
</head>
<body>
<form method="GET">
<p>
<label for="fahrenheit">Enter Fahrenheit temperature:</label>
<input type="text" id="fahrenheit" name="fahrenheit">
<input type="submit" value="Submit">
</p>
<p>
<output><?=$fahrenheit?></output>
</p>
</form>
<form method="POST">
<p>
<label for="celsius">Enter Celsius temperature:</label>
<input type="text" id="celsius" name="celsius">
<input type="submit" value="Submit">
</p>
<p>
<output><?=$celsius?></output>
</p>
</form>
</body>
</html>
Try It
[edit | edit source]Copy and paste the code above into the following free online development environment or use your own PHP compiler / interpreter / IDE.