lundi 20 février 2017

PHP Compare random array elements to user input

http://ift.tt/2m00R7i

I am trying to create a similar style of password entry in php to that which can be found in the Youtube Kids app. I am new to the language and am having difficulty in trying to code it.

I have created 4 separate input boxes for the user to input the numbers, and have been able to generate the random text to be displayed. I tried saving the values that are randomly generated to a text file and then try to compare it with the user input, but this does not seem to work.

//HTML code to create input boxes
<form action="embed.php" method="POST">
    <div id="pinFrm">
        <input type ="text" class="a" maxlength="1" name="inputA"/>
        <input type ="text" class="b" maxlength="1" name="inputB"/>
        <input type ="text" class="c" maxlength="1" name="inputC"/>
        <input type ="text" class="d" maxlength="1" name="inputD"/>

        <div class="sBtn">
            <button type="submit" name="submit" class="submit">
            <p class="submitTxt">Submit</p>    
        </div>
    </div>
</form>

//PHP code to generate random strings and compare values
$numStr = array( 
  '0' => "ZERO",'1' => "ONE",'2' => "TWO",'3' => "THREE",'4' => "FOUR",'5' => "FIVE",'6' => "SIX",'7' => "SEVEN",'8' => "EIGHT",'9' => "NINE");

function generateRandTxt() {
  global $numStr;
    foreach($numStr as $x => $x_value);

    $NumTxt = array_rand($numStr, 4);
    $GLOBALS['a'] = $numStr[$NumTxt[0]];
    $GLOBALS['b'] = $numStr[$NumTxt[1]];
    $GLOBALS['c'] = $numStr[$NumTxt[2]];
    $GLOBALS['d'] = $numStr[$NumTxt[3]];

    echo $GLOBALS['a'] . ",\n";
    echo $GLOBALS['b'] . ",\n";
    echo $GLOBALS['c'] . ",\n";
    echo $GLOBALS['d'];

//store random text values into file
function saveRandTxt() {
  global $a;
  global $b;
  global $c;
  global $d;

  $RandTxtfile = fopen("RandTxt.txt", "w");
  $txtA = $a;
  fwrite($RandTxtfile, $txtA);
  $txtB = $b;
  fwrite($RandTxtfile, $txtB);
  fclose($RandTxtfile);
}

To check if what the user input matches I tried to code it below but only with d but when the correct value is input it does not output 'match'.

//check if input matches random value generated
function checkMatch() {
  global $numStr;
  global $a;
  global $b;
  global $c;
  global $d;   

  $inputD = (isset($_POST["inputD"]) ? $_POST["inputD"] : null);

    echo array_search($GLOBALS['d'],$numStr);
    if ($inputD == array_search($d, $numStr)) {
           echo 'match' ...
       }
    }

    function
    echo checkMatch();

When the user enters all the correct values I would like them to be displayed a pop-up but if any one of the values do not match then they should be displayed an error.




Aucun commentaire:

Enregistrer un commentaire