Hello Friends Today, through this tutorial, I will tell you Convert from Kilometers to Meters Using PHP Script Code with HTML.
Here’s the HTML and PHP code for a simple Kilometer to Meter converter:
index.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Kilometers to Meters Converter Using PHP Script Code</title> </head> <body> <h1>Kilometers to Meters Converter Using PHP Script Code</h1> <form action="convert.php" method="post"> <label for="km">Enter kilometers:</label> <input type="number" name="km" id="km" required> <br> <button type="submit">Convert</button> </form> </body> </html>
convert.php:
<?php // Conversion rate: 1 kilometer = 1000 meters $conversion_rate = 1000; // Check if the form is submitted if (isset($_POST['km'])) { $km = (float) $_POST['km']; $meters = $km * $conversion_rate; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Kilometers to Meters Converter</title> </head> <body> <h1>Kilometers to Meters Converter</h1> <?php if (isset($km) && isset($meters)): ?> <p><b><?php echo $km; ?> kilometers is equal to <?php echo $meters; ?> meters.</b></p> <?php endif; ?> </body> </html>
Explanation:
1. index.html: This file creates a simple form with a label and input field for entering the kilometers. When the user clicks the “Convert” button, the form is submitted to ‘convert.php’.
2. convert.php: This file handles the form submission.
– It defines the conversion rate between kilometers and meters.
– It checks if the form was submitted and retrieves the entered kilometers value from the `$_POST` array.
– If the form is submitted, it performs the conversion by multiplying the kilometers by the conversion rate and stores the result in the `$meters` variable.
– Finally, it displays the converted value in meters if available.
This is a basic example, and you can further improve it by:
* Adding error handling to check for invalid input values.
* Including a link back to the main form from the result page.
* Implementing a function for the conversion logic to improve code reusability.