[RESOLVED] Why does the variable $token5 change 3 times when I run this script?
Results 1 to 7 of 7

Thread: [RESOLVED] Why does the variable $token5 change 3 times when I run this script?

  1. #1
    Member
    Join Date
    Jan 2017
    Location
    Michigan / United States
    Posts
    46

    resolved [RESOLVED] Why does the variable $token5 change 3 times when I run this script?

    Hi. Attempting email address confirmation script. My attempt contains three files: (email_token_test.php)
    require_once (gen_email_token.php)
    require (PHPMailer-master/PHPMailerAutoload.php)

    I am expecting the variable $token5 to contain a 5 character string and for that string to remain the same through the whole script. To the best of my limited knowledge I am only calling the token generation function 1 time, but doing several var_dumps on $token5 shows that $token5 is changing as the script progresses.

    I know that a standard way of email address confirmation is with user registeration and database population, but in this instance user aren't signing in or registering. They will just be submitting email address for a quote request.

    What am I doing wrong and how do I correct it?

    gen_email_token.php
    PHP Code:
    require_once "random_compat-2.0.10/lib/random.php";
        include 
    "password_compat-1.0.4/lib/password.php";
        
        function 
    generateEmailToken() {
            try {
            
    $string random_bytes(32);
            } catch (
    TypeError $e) {
                
    // Well, it's an integer, so this IS unexpected.
                
    die("An unexpected error has occurred"); 
            } catch (
    Error $e) {
                
    // This is also unexpected because 32 is a reasonable integer.
                
    die("An unexpected error has occurred");
            } catch (
    Exception $e) {
                
    // If you get this message, the CSPRNG failed hard.
                
    die("Could not generate a random string. Is our OS secure?");
            }
                    
            
    $myRandomString = (bin2hex($string));
            
            if(
    $myRandomString = (bin2hex($string))){
            
    $randomToken password_hash($myRandomStringPASSWORD_BCRYPT);
                
    //return $randomToken.'<br>';
            
    }

            if(
    $randomToken password_hash($myRandomStringPASSWORD_BCRYPT)){
            
    $newRandomToken substr($randomToken7);
                
    //return $newRandomToken.'<br>';
            
    }

            global 
    $token5;
            
            if(
    $newRandomToken substr($randomToken7)){
            
    $token5 substr($newRandomToken, -5);
                
    //return $token5.'<br>';
            
    }
            
            if(
    $token5 substr($newRandomToken, -5)){
                return 
    $token5;
            }
                
        } 
    email_token_test.php

    PHP Code:
    require_once "gen_email_token.php";
        require "PHPMailer-master/PHPMailerAutoload.php";
        global $token5;
        global $newEmailToken;
        $newEmailToken = generateEmailToken();
        var_dump($token5);
        
        
        if(isset($_POST['submit'])){
            //echo 'Submit button pressed!'.'<br>';
            print_r($_POST);
            
            $postedEmail = null;
            if($_POST['req-email']){
                $postedEmail = $_POST['req-email'];
                //var_dump($postedemail);
                //echo $newEmailToken;
            }
            
            if(strlen($postedEmail) === 0){
            //Blank string, add error to $errors array.
                $errors[] = "You must enter your email address.";
            }
            
            
            if(strlen($postedEmail)<3){
                $errors[] = "You have entered an invalid email address.";
            }
            
            
            //  MAKE SURE THE "FROM" EMAIL ADDRESS DOESN'T HAVE ANY NASTY STUFF IN IT
            $pattern = '/^(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){255,})(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){65,}@)(?:(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)|(?:\x22(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]|(?:\x5C[\x00-\x7F]))*\x22))(?:\.(?:(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)|(?:\x22(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]|(?:\x5C[\x00-\x7F]))*\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-[a-z0-9]+)*\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-[a-z0-9]+)*)|(?:\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\]))$/iD'; 
            if (preg_match($pattern, trim(strip_tags($postedEmail)))) { 
                $cleanedEmail = trim(strip_tags($postedEmail)); 
                //var_dump('<br>'.$cleanedEmail);
                //echo '<span style="color:green;">Success'.'&nbsp;'.'</span>'.'<b>'.$cleanedEmail.'</b>'.'<span style="color:green;">'.'&nbsp;'.'is a valid Email.'.'<br>'.'</span>';
                } else { 
                    $errors[] = "The email address you entered was invalid. Please try again!";
                    //var_dump($errors);
            }
            
            $Email = $cleanedEmail;
            

            if(!empty($errors)){ 
                echo '<h1>Error(s)!</h1>';
                foreach($errors as $errorMessage){
                    echo '<span style="color:red;">'.$errorMessage .'</span>';
                }
            }

            if(empty($errors)){
                                        
                $message  =    '<html><body>';
                $message .= '<img src="http://res.cloudinary.com/dx1tairmq/image/upload/v1499127233/miles%20away%20travel/newmatlogo_small.png" alt="miles away travel">';
                $message .= 'Miles Away Travel has sent an email verification code.';
                $message .= '<table rules="all" style="border-color: #666;" cellpadding="10">';
                $message .= "<tr><td><strong> Your verification code: </strong></td><td>"  . $token5 ."</td></tr>";
                $message .= "</table>";
                $message .= '<p>Please enter this code in the email Verification form</p>';
                $message .= "</body></html>";
                
                $mail = new PHPMailer;

                //$mail->SMTPDebug = 1;                               // Enable verbose debug output

                $mail->isSMTP();                                      // Set mailer to use SMTP
                $mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers
                $mail->SMTPAuth = true;                               
                $mail->Username = 'kentest894@gmail.com';                 // set gmail email id
                $mail->Password = 'My_New_Gmail_894';                           // gmail email password
                $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
                $mail->Port = 587;                                    // TCP port to connect to

                $mail->setFrom('kentest894@gmail.com', 'Miles Away Travel');
                $mail->addAddress($Email, 'Ken Smith');     // Add a recipient
                //$mail->addAddress('kenneth894@hotmail.com'  , 'K-man');            // Name is optional
                $mail->addReplyTo('friend_one_email_Addess', 'Information');


                $mail->isHTML(true);                                  // Set email format to HTML

                $mail->Subject = 'EMAIL verification code';
                $mail->Body    = $message;
                $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

                if(!$mail->send()) {
                    echo 'Message could not be sent.';
                    echo 'Mailer Error: ' . $mail->ErrorInfo;
                } else {
                    echo 'Message has been sent'.'<br>';
                }
                
                    
                var_dump($token5);
                
                
                function buildform(){
                    echo '<h3>Your email address must be verified for quote submission.</h3>
                        <form name="e-verify" method="post" action="email_token_test.php" id="form2">
                            <h3>Email Verification form</h3><br> 
                            <label for="req-codeField">ENTER CODE HERE:</label>
                            <input type="text" name="req-codeField" max length="5"/>
                            <input type="submit" name="e-verify-submit" value="verify"/>
                        </form>';
                }
        
                function show_form(){
                    echo'<!DOCTYPE html>
                        <html lang="en">
                        <head>
                            <link rel="stylesheet" href="form_show.css" type="text/css" media="all" />
                        </head>
                        <body>
                            <div id="innerdiv">
                            <?php buildform(); ?>
                            </div>
                        </body>
                    </html>';
                }
                
                buildform();
                show_form();
            }
            
            var_dump($token5);
        }
            
        if(isset($_POST['e-verify-submit'])){
            print_r($_POST);
            $errors = array();
            
            $postedCode = null;
            if($_POST['req-codeField']){
                $postedCode = $_POST['req-codeField'];
                $postedCode = trim(stripslashes($postedCode));
                //var_dump($postedfname);
            }
            
            if(strlen($postedCode) === 0){
            //Blank string, add error to $errors array.
                $errors[] = "You must enter your verification code.";
            }
            
            if (strlen($postedCode) < 5 || strlen($postedCode) > 5) {
                $errors[] ='Verification code should contain 5 characters.';
            }

            If ($postedCode === $token5){
                echo '<span style="color:green;">Success your email has been verified</span>';
            }else{
                echo '<span style="color:red;">Email verification has failed. Please contact us by phone.</span>';
                
            }
            var_dump($postedCode);
            var_dump($token5);
        }

    HTML Code:
    <!DOCTYPE html>
    <html lang="en">
    	<head>
    		<meta charset="utf-8">
    		<link rel="stylesheet" href="form_show.css" type="text/css" media="all" />
    	</head>
    	
    	<body>
    		<h1>Email Token Test</h1>
    		<form name="e-mail" action="email_token_test.php" method="post" id="form1">
    			<label for="req-email">Email*:</label>
    			<input type="email" id="req-email" name="req-email" required="required" minlength="3" value="" />
    			<br>
    			<br>
    			<input type="submit" name="submit" value="submit"/>
    		</form>
    	</body>
    </html>

  2. #2
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Contact Unit "Coping Mechanism"
    Posts
    22,503
    It looks to me you're generating the token anew every time you process a user-submitted form. It's pretty much the first thing that happens whenever email_token_test.php is called. In particular you generate a token, ask the user to verify it, and then before checking that what they submitted matches that token (which you don't have anymore anyway), you generate a new one.

    By itself HTTP doesn't remember anything from one request to the next, so if you want anything on one request to carry over to another you have to remember it youself. No, global doesn't do it. See intro.session.

    BTW:
    Code:
     //  MAKE SURE THE "FROM" EMAIL ADDRESS DOESN'T HAVE ANY NASTY STUFF IN IT
            $pattern = '/^(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){255,})(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){65,}@)(?:(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)|(?:\x22(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]|(?:\x5C[\x00-\x7F]))*\x22))(?:\.(?:(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)|(?:\x22(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]|(?:\x5C[\x00-\x7F]))*\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-[a-z0-9]+)*\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-[a-z0-9]+)*)|(?:\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\]))$/iD';
    You know, PHP does have a function for this (see filter-var).
    Last edited by Weedpacket; 09-09-2017 at 06:53 PM.
    THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

  3. #3
    Member
    Join Date
    Jan 2017
    Location
    Michigan / United States
    Posts
    46
    If I understand this correctly, every time the submit is pressed regardless of which form, it is like the page is being reloaded. This in turn causes the Token generation function which is at the beginning of the script to be called again.
    So, what I should do is start a SESSION session_start(); on each page. Create SESSION variables array not global variables.
    Since I will have SESSION. I will process email address on one page. Generate token on another page and process token verification on another.
    I am not very familiar with working with SESSIONS, which is why I was trying to do all of this on one page to begin with.
    I will check out a few tutorials and try to get the hang of it.
    You know php has a function for this filter_var()
    Yes. I am aware of the function. I have read that it is unreliable and that comprehensive regex is better.
    Last edited by New_PHP_Guy; 09-10-2017 at 09:58 PM. Reason: add additional comment

  4. #4
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Contact Unit "Coping Mechanism"
    Posts
    22,503
    Quote Originally Posted by New_PHP_Guy
    Yes. I am aware of the function. I have read that it is unreliable and that comprehensive regex is better.
    Giving false positives or false negatives?

    See https://fightingforalostcause.net/co...mail-regex.php and https://github.com/php/php-src/blob/...filters.c#L576. TL;DR: Guess how filter_var works.
    Last edited by Weedpacket; 09-10-2017 at 10:39 PM.
    THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

  5. #5
    Member
    Join Date
    Jan 2017
    Location
    Michigan / United States
    Posts
    46
    False negatives.
    Guess how filter_var works.
    I am assuming with regex also.

    As per the first part of my previous post, was I understanding correctly?

  6. #6
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Contact Unit "Coping Mechanism"
    Posts
    22,503
    Quote Originally Posted by New_PHP_Guy
    I am assuming with regex also.
    If you followed the links given, you'd see that it is with the exact same regex you're using (plus corrections that yours doesn't have).

    As per the first part of my previous post, was I understanding correctly?
    Yes, except you're confusing "page" with "request".
    THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

  7. #7
    Member
    Join Date
    Jan 2017
    Location
    Michigan / United States
    Posts
    46
    @Weedpacket.
    Thanks for taking time to review my code and pointing out the flaws.
    Soooooo much to learn.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •