Convert Temperature with This PHP Script

Close-Up Of Thermometer By Wood
Brandy Arivett/EyeEm/Getty Images

This PHP script can be used to convert temperature values to or from Celsius, Fahrenheit, Kelvin, and Rankine. Follow this step-by-step tutorial and create your own temperature conversion program.

of 04

Setting Up the Form

The first step in creating an online temperature conversion program is to collect the data from the user. In this case, the form collects the degrees and the units the degrees are measured in. You are using a drop-down menu for the units and giving them four options. This form uses the ​​$_SERVER[’PHP_SELF’] command to indicate it sends the data back to itself.

Put the code below into a file called convert.php

of 04

Using IF for Conversions

If you recall, the form is sending data back to itself. This means that all of your PHP will be contained in the same file you placed your form in. Continuing to work in the convert.php file, place this PHP code under the HTML you entered in the last step.

This code converts a Celcius temperature to Fahrenheit, Kelvin, and Rankine and then prints their values in a table below the original form. The form is still at the top of the page and is ready to accept new data. Currently, if the data is anything but Celcius it will be ignored. In the next step, you will add in the other conversions so options other than Celcius work.

of 04

Adding More Conversions

Still working in the convert.php file, add the following code at the end of the document, just before the ?> end PHP tag.

and put this code after the ?> closing PHP tag to close up the HTML

of 04

The Script Explained

First, the script collects data from the user and then submits this information to itself. When the page reloads after hitting submit, the PHP at the bottom now has variables to work with and can execute.

Your convert temperature PHP consists of four IF statements, one for each of the unit measurements available on our form. The PHP then makes the appropriate conversions based on the users choice and outputs a table. The complete code for this script can be downloaded from GitHub.

mla apa chicago
Your Citation
Bradley, Angela. "Convert Temperature with This PHP Script." ThoughtCo, Feb. 16, 2021, Bradley, Angela. (2021, February 16). Convert Temperature with This PHP Script. Retrieved from Bradley, Angela. "Convert Temperature with This PHP Script." ThoughtCo. (accessed May 29, 2023).