Server-Side Scripting/Requests/PHP

From Wikiversity
Jump to navigation Jump to search

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

$GET_FORM = '
<form method="GET">
<label for="fahrenheit">Enter Fahrenheit temperature:</label>
<input type="text" id="fahrenheit" name="fahrenheit">
<input type="submit" value="Submit">
</form>
';

$EMPTY_PARAGRAPH = '
<p>&nbsp;</p>
';

$POST_FORM = '
<form method="POST">
<label for="celsius">Enter Celsius temperature:</label>
<input type="text" id="celsius" name="celsius">
<input type="submit" value="Submit">
</form>
';

$result = $GET_FORM;

if (isset($_GET["fahrenheit"]) && strlen($_GET["fahrenheit"]) > 0) {
    $fahrenheit = $_GET["fahrenheit"];
    $celsius = ($fahrenheit - 32) * 5 / 9;
    $result = $result . "<p>" . $fahrenheit . "° Fahrenheit is " .
        $celsius . "° Celsius</p>";
}
else {
    $result = $result . $EMPTY_PARAGRAPH;
}

$result = $result . $POST_FORM;

if (isset($_POST["celsius"]) && strlen($_POST["celsius"]) > 0) {
    $celsius = $_POST["celsius"];
    $fahrenheit = $celsius * 9 / 5 + 32;
    $result = $result . "<p>" . $celsius . "° Celsius is " .
        $fahrenheit . "° Fahrenheit</p>";
}
else {
    $result = $result . $EMPTY_PARAGRAPH;
}

echo $result;

?>

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.