Server-Side Scripting/Strings and Files/PHP

From Wikiversity
Jump to navigation Jump to search

index.php[edit | edit source]

<?php

// This program reads a user-selected text file of Fahrenheit
// temperatures and converts the temperatures to Celsius.
//
// File format:
// 32° F
// 98.6° F
// 212° F
//
// References:
//  https://www.mathsisfun.com/temperature-conversion.html
//  https://en.wikibooks.org/wiki/PHP_Programming
//  https://www.php.net/manual/en/features.file-upload.post-method.php

$FORM = '
<h1>Temperature Conversion</h1>
<p>Select a file of Fahrenheit temperatures for conversion:</p>
<form method="POST" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="1048576" />
<input type="file" id="file" name="file">
<input type="submit">
</form>
';

main();

function main() {
    switch($_SERVER["REQUEST_METHOD"]) {
        case "GET":
            echo $GLOBALS["FORM"];
            break;
        case "POST":
            if ($_FILES["file"]["error"] == UPLOAD_ERR_OK &&
                is_uploaded_file($_FILES["file"]["tmp_name"])) {
                echo "<h1>Temperature Conversion</h1>";
                echo "<h2>" . $_FILES["file"]["name"] . "</h2>";
                echo process_file($_FILES["file"]["tmp_name"]);
            }
            break;
        default:
            echo "Unexpected request method:" . $_SERVER["REQUEST_METHOD"];
            break;
    } 
}

function process_file($filename) {
    $result = "<table><tr><th>Fahrenheit</th><th>Celsius</th></tr>";
    $text = file_get_contents($filename);
    $lines = explode("\n", trim($text));
    foreach ($lines as $line) {
        $result = $result . process_line($line);
    }

    $result = $result . "</table>";
    return $result;
}

function process_line($line) {
    $index = strpos($line, "° F");
    if ($index < 0) {
        return "Invalid file format";
    }

    $fahrenheit = floatval(substr($line, 0, $index));
    $celsius = ($fahrenheit - 32) * 5 / 9;
    $result = "<tr><td>" . $fahrenheit . "</td>";
    $result = $result . "<td>" . number_format($celsius, 1) . "</td></tr>";

    return $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.