Web Analytics Made Easy -
StatCounter Issue with converter script - CodingForum

Announcement

Collapse
No announcement yet.

Issue with converter script

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Issue with converter script

    Hi,

    I created a simple script that converts miles to kilometer. I added it to an HTML file and it works fine, but when I load the page (and there is nothing to convert) it gives me an error:

    Code:
    Notice: Undefined index: mile in F:\wamp64\www\exchange\convert.php on line 130
    So basically what I want is to display nothing on page load or if there is nothing in the input field. Here is my code:

    PHP Code:
    <h3 class="section-heading">Convert Miles to Kilometer II.</h3>
                                <hr class="primary">
                                <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" style="margin-top: 20px;">

                                    <p>Add Miles:
                                        <input type="text" class="form-control" placeholder="miles" name="mile" size="2" />  
                                    </p>
                                    <p>
                                        <input type="submit" class="btn btn-primary" value="Submit" />  
                                    </p>
                                </form>

                                <?php
                                    $miles 
    $_POST['mile'];

                                    
    // How many km is one mile?
                                    
    $onemile 1.609344;

                                    
    $totalkm $miles $onemile;

                                    print 
    "<p>$miles miles is $totalkm kilometer.</p>";


                                
    ?>
    Any help is appreciated.

  • #2
    That is the correct behaviour for php, what you need to do is check that a valid value has been submitted.

    Your web site can be hacked if you do not validate user input. Do some research on secure web forms and validating and processing user input.

    Comment


    • #3
      Thanks.

      Comment


      • #4
        Here's how to test when the form has been submitted and to check that miles has been entered as a number

        PHP Code:
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
           if(
        filter_var($_POST['mile'], FILTER_VALIDATE_INT) !== false) {
               
        $miles $_POST['mile'];
           } else {
               
        $miles '';
               
        // error message for miles not being a number
            

        Stephen
        Learn Modern JavaScript - http://javascriptexample.net/
        Helping others to solve their computer problem at http://www.felgall.com/

        Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

        Comment

        Working...
        X