php - Form with random number as validation -


the following php code generating random number of 4 digits ($numero) , using validation simple html form 3 input boxes. last input box entering code (the random number). if user doesn't write right number in last input box program skips purpose, adding text database (agregar.txt). think code fine, except if ($_post['password'] != $numero) {. should change string or use kind of variable? each time run code acts if $numero different password, , i'm sure i'm writing right number. please help.

<html> <body> <center> <h2>agregar entradas diccionarioie</h2>  <?php // random 4 digits number $numero = rand(1000, 9999); echo "<b>código: </b><big>".$numero."</big><p>"; if ($_post['password'] != $numero) { ?>  <form name="form" method="post" action=""> <input title=" lema " size="30" type="text" name="lema" autofocus><br> <input title=" traducciÓn " size="30" type="text" name="trad"><br> <input title=" cÓdigo " size="30" type="text" name="password"><br> gracias por colaborar <input title=" enviar " type="submit" value="•"></form>  <?php } else { $lema = $_post['lema']; $trad = $_post['trad']; // adding text database $texto = $lema." __ ".$trad."\n"; $docu = fopen("agregar.txt", "a+"); fwrite($docu, $texto); fclose($docu); } ?>  </center> </body> </html> 

as pointed out @fred -ii-, problem in code $numero generated different random number when submit form. solution use session: php session example

the session can used store $numero value after form being submitted. here's updated code:

<?php  // make sure start session before output. session_start();  if (isset($_post['password']) && isset($_session['numero']) && $_post['password'] == $_session['numero']) {     unset($_session['numero']);     $lema = $_post['lema'];     $trad = $_post['trad'];     // adding text database     $texto = $lema." __ ".$trad."\n";     $docu = fopen("agregar.txt", "a+");     fwrite($docu, $texto);     fclose($docu); } else {     // random 4 digits number & store in session.     $numero = $_session['numero'] = rand(1000, 9999); ?> <html> <body>     <center>         <h2>agregar entradas diccionarioie</h2>         <b>código: </b><big><?php echo $numero; ?></big><p>         <form name="form" method="post" action="">             <input title="lema " size="30" type="text" name="lema" autofocus><br>             <input title="traducciÓn " size="30" type="text" name="trad"><br>             <input title="cÓdigo " size="30" type="text" name="password"><br>             gracias por colaborar <input title=" enviar " type="submit" value="•">         </form>     </center> </body> </html> <?php } 

just make sure call session_start() before output (in case html document).

hope help.


Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -