0

Learning php and I had to write this basic script :

<!DOCTYPE html>
<html>
    <head>
        <title>Whats My Age</title>
    </head>
    <body>
        <form method="get">

             Year of Birth: <input type="text" name="age" />
            <input type="submit" name="submit" />
        </form> 

        <?php
        function isNegative()
        {
            if ($_GET['age'] < 0) 
            {
                echo "Invalid Number";
            }
        }
        isNegative();

        function showMsg() 
        {
                if (is_numeric($_GET['age']) && ($_GET['age'] >= 1) && isset($_GET['submit'])) 
            {
                $year = htmlentities($_GET['age']);
                $asd1 = $year + 1900;
                $today = date('Y');
                $now = $today - $asd1;
                echo "You are " . $now . " years old";
            }
        }
        showMsg();

        ?>  


    </body>
</html>

Got two questions

  1. How can the script run after the user has written something in the input, since the moment you open the file, it gives an error that $_GET['age'] is undefined, which obviously is so or should I not worry about that as its only server side and the front end stuff will fix that ? For the same reasoning if I put the code in showMsg() outside of the function and put an else {} statement, the else runs as the page opens.

  2. I'm supposed to turn a short user input like - "58 " to the complete year such as 1958. I find a problem with that however as if the user puts in 01 for example, how would the script know if its 1901 or 2001, which is probably a problem in the condition of the task ?

Machavity
  • 30,841
  • 27
  • 92
  • 100
Sptfr
  • 29
  • 4
  • For the first question, see http://stackoverflow.com/a/12770836/476. For the second one there is no correct answer. Yes, it's ambiguous. That's why nobody uses two-digit years anymore, it cost everyone a ton of money to fix Y2K. If you still want to use two-digit years, specify yourself how they *should* behave. Something typical would be *"anything < 20 is 20xx, anything >= 20 is 19xx"*. – deceze Sep 30 '16 at 14:42
  • BTW, work on your naming. *"Year of birth"* is not the same as *"age"*. Call year-of-birth variables `$yearOfBirth` and age variables `$age`. You're confusing anyone reading your code, including yourself. – deceze Sep 30 '16 at 14:45

0 Answers0