Jump to content

Why Sha1 Needs To Be TypeCasted To String ?


phpsane

Recommended Posts

Php Lovers,

 

When you register on my site, you supposed to get an account activation link emailed to confirm your email and account opening.

Activation Link contains activation code. Code, I wanted all numbers like so: 193736262829292

And not alphanumerical like so: djkqh3kl3lwnj3j22b

Someone did this line for me 1.5yrs back and only just came to my attention it is generating alphanumeric chars as I was checking the column where it would save the code to see if the column type is correct or not. Type was varchar all this time. If the code becomes only numerical then can switch column (account_activation_code) type to "INT".

	$account_activation_code = sha1( (string) mt_rand(0,99999999)); //Type Casted the INT to STRING on the 11st parameter of sha1 as it needs to be a string.         
	

Another programmer did that line 1.5yrs back. Lost contact with him. Tell me, why sha1 needs to be TypeCasted to "STRING" ? As far as I remember 1.5yrs back it had to be converted to STRING. Else, was giving error. I mean, we dealing with INT here "mt_rand(0,99999999)" so why php force us to TypeCast to STRING here ? Absurd! Right ?

Context:

	<?php 
	//Required PHP Files. 
include 'configurations_site.php'; //Required on all webpages of the site. Must include here too. Else, conn.php data would not be found. conn.php residing in site_configurations.php. 
include 'header_site.php'; 
	//Step 1: Before registering user Account, check if User is already registered or not. Else, check if User is registering through invitation or not. 
	//Check if User is already logged-in or not. Get the login_check() custom FUNCTION to check. 
if (login_check() === TRUE) 
{ 
    die("You are already logged-in! No need to register again!"); 
} 
	//Check if the Url contains a Sponsor Username or not. If not, then barr the registration. 
if (isset($_GET['sponsor_username']) && !empty($_GET['sponsor_username'])) 
{ 
    $sponsor_username = $_GET["sponsor_username"]; 
} 
else 
{   
    die("Signups only through invitations only!<br> 
    Therefore, you need to be invited by a registered member who knows you personally!"); 
} 
	if ($_SERVER['REQUEST_METHOD'] == "POST") 
{ 
    //Step 2: Check User submitted details. 
    
    //Check if User made all the required inputs or not. 
    if (isset($_POST["fb_tos_agreement_reply"]) || 
       isset($_POST["username"]) && 
       isset($_POST["password"]) && 
       isset($_POST["password_confirmation"]) && 
       isset($_POST["fb_tos"]) && 
       isset($_POST["primary_domain"]) && 
       isset($_POST["primary_domain_confirmation"]) && 
       isset($_POST["primary_website_email"]) && 
       isset($_POST["primary_website_email_confirmation"]) && 
       isset($_POST["age_range"])) { 
           
        //Step 3: Check User details for matches against database. If no matches then validate inputs to register User Account. 
           
        //Create Variables based on user inputs. 
        $fb_tos_agreement_reply = trim($_POST["fb_tos_agreement_reply"]); 
        $username = filter_var(trim($_POST["username"],FILTER_SANITIZE_STRING)); 
        $password = $_POST["password"]; 
        $password_confirmation = $_POST["password_confirmation"]; 
        $primary_website_domain = filter_var(trim($_POST["primary_website_domain"],FILTER_SANITIZE_DOMAIN)); 
        $primary_website_domain_confirmation = filter_var(trim($_POST["primary_website_domain_confirmation"],FILTER_SANITIZE_DOMAIN)); 
        $primary_website_email = filter_var(trim($_POST["primary_website_email"],FILTER_SANITIZE_EMAIL)); 
        $primary_website_email_confirmation = filter_var(trim($_POST["primary_website_email_confirmation"],FILTER_SANITIZE_EMAIL)); 
        $primary_website_email_extracted_domain = substr(strrchr($primary_website_email,"@"),1); 
        $age_range = filter_var(trim($_POST["age_range"],FILTER_SANITIZE_STRING)); 
        $account_activation_code = sha1( (string) mt_rand(0,99999999)); //Type Casted the INT to STRING on the 11st parameter of sha1 as it needs to be a string. 
        $account_activation_link = sprintf("http://www.%s/%s/activate_account.php?website_email=%s@account_activation_code=%s",
        $site_domain,$social_network_name,urlencode("$primary_website_email"),urlencode($account_activation_code));         
        $account_activation_status = 0; //1 = active; 0 = inactive. 
        $hashed_password = password_hash($password,PASSWORD_DEFAULT); //Encrypt the password. 
        
        if (strlen($fb_tos_agreement_reply) < 1 || $fb_tos_agreement_reply != "Yes") { 
            echo "You must agree to our <a href='tos.html'>Terms & Conditions</a>!"; 
        //Check if inputted Username is valid or not. 
        } elseif (!filter_var($username,FILTER_VALIDATE_STRING)) { 
            echo "You entered an Invalid Username!"; 
        //Check if inputted Username is between the required 8 to 30 characters long or not. 
        } elseif (strlen($username) < 8 || strlen($username) > 30) { 
            echo "Username has to be between 8 to 30 characters long!"; 
        //Check if Password is between 8 to 30 characters long or not. 
        } elseif (strlen($password) < 8 || strlen($password) > 30) { 
            echo "Password must be between 8 to 30 characters long!"; 
        //Check if both inputted Passwords match or not. 
        } elseif ($password != $password_confirmation) { 
            echo "Your entered 2 Passwords don't match!"; 
        //Check if both inputted Domains match or not. 
        } elseif ($primary_website_domain != $primary_website_domain_confirmation) { 
            echo "Your entered 2 Primary Website Domains don't match!"; 
        //Check if inputted Domain is valid or not. 
        } elseif (!filter_var($primary_website_domain,FILTER_VALIDATE_DOMAIN)) { 
            echo "You entered an Invalid Domain Name!"; 
        //Check if both Email Inputs match or not. 
        } elseif ($primary_website_email != $primary_website_email_confirmation) { 
            echo "Your 2 Email inputs don't match!"; 
        //Check if inputted Email is valid or not. 
        } elseif (!filter_var($primary_website_email,FILTER_VALIDATE_EMAIL)) { 
            echo "You entered an Invalid Email Address!";         
        //Check if inputted Domain and Email Domain match or not. 
        } elseif ($primary_website_email_extracted_domain != $primary_website_domain) { 
            echo "Your Email Address must belong to your Domain Name: \"$primary_website_domain\"!"; 
        } 
        else 
        { 
            //Select Username and Email to check against Mysql DB if they are already regsitered or not. 
            $stmt = mysqli_prepare($conn,"SELECT username,primary_domain,primary_website_email FROM users WHERE username = ? OR primary_domain = ? OR primary_website_email = ?"); 
            mysqli_stmt_bind_param($stmt,'sss',$username,$primary_website_domain,$primary_website_email); 
            mysqli_stmt_execute($stmt); 
            $result = mysqli_stmt_get_result($stmt); 
            $row = mysqli_fetch_array($result, MYSQLI_ASSOC); 
        
            //Check if inputted Username is already registered or not. 
            if ($row['username'] == $username) { 
                echo "That Username is already registered!"; 
            //Check if inputted Domain is already registered or not. 
            } elseif ($row['primary_domain'] == $primary_website_domain) { 
                echo "That Domain Name is already registered!"; 
            //Check if inputted Email is already registered or not. 
            } elseif ($row['primary_website_email'] == $primary_website_email) { 
                echo "That Email Address is already registered!"; 
            } 
            else 
            { 
                //Insert the User's inputs into Mysql database using Php's Sql Injection Prevention Method "Prepared Statements". 
                $stmt = mysqli_prepare($conn,"INSERT INTO users(account_activation_code,account_activation_status,id_video_verification_status,sponsor_username,recruits_number,username,password,primary_domain,primary_website_email,age_range,registering_country,registering_ip,registering_browser,registering_os,registering_isp) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); 
                mysqli_stmt_bind_param($stmt,'siisissssssssss',$account_activation_code,$account_activation_status,$id_video_verification_status,$sponsor_username,$recruits_number,$username,$hashed_password,$primary_website_domain,$primary_website_email,$age_range,$registering_country,$registering_ip,$registering_browser,$registering_os,$registering_isp); 
                mysqli_stmt_execute($stmt); 
            
                //Check if User's registration data was successfully submitted or not. 
                if (!$stmt) 
                { 
                    echo "Sorry! Our system is currently experiencing a problem registering your account! You may try registering some other time!"; 
                    exit(); 
                } 
                else 
                { 
                    //Email the Account Activation Link for the User to click it to confirm their email and activate their new account. 
                    $to = "$primary_website_email";                 
                    $subject = "Your ".$site_name." Account Activation Details"; 
                    $body = nl2br(" 
                    ===============================\r\n 
                    ".$site_name." \r\n 
                    ===============================\r\n 
                    From: ".$site_admin_email."\r\n 
                    To: ".$primary_website_email."\r\n 
                    Subject: Your ".$subject."\r\n 
                    Message: ".$username."\r\n 
                    You need to click on this following <a href=".$account_activation_link.">link</a> to activate your account.\r\n
                    "); 
                    $headers = "From: ".$site_admin_email."\r\n"; 
            
                    if (!mail($to,$subject,$body,$headers)) 
                    { 
                        echo "Sorry! We have failed to email you your Account Activation details. Please contact the website administrator!"; 
                        exit(); 
                    } 
                    else 
                    { 
                        echo "<h3 style='text-align:center'>Thank you for your registration!<br /> Check your email $website_email for details on how to activate your account which you just registered.<h3>"; 
                        exit(); 
                    } 
                } 
            } 
        } 
    } 
}    
	?> 
	<!DOCTYPE html> 
<html> 
    <head> 
        <title><?php echo "$social_network_name";?> Signup Page</title> 
    </head> 
<body> 
<div class ="container"> 
	<?php 
//Error Messages. 
if (isset($_SESSION['error']) && !empty($_SESSION['error'])) { 
    echo '<p style="color:red;">'.$_SESSION['error'].'</p>'; 
} 
?> 
	<?php 
//Session Messages. 
if (isset($_SESSION['message']) && !empty($_SESSION['message'])) { 
    echo '<p style="color:red;">'.$_SESSION['error'].'</p>'; 
} 
?> 
	<?php 
//Clear Registration Session. 
function clear_registration_session() 
    { 
        //Clear the User Form inputs, Session Messages and Session Errors so they can no longer be used. 
        unset($_SESSION['message']); 
        unset($_SESSION['error']); 
        unset($_POST); 
        exit(); 
    } 
?> 
<h2><p align="center"><?php echo "$site_name Member Sign Up Form";?></p></h2> 
<form name "registration_form" method = "post" action="" enctype = "multipart/form-data"> 
    <div class="form-group"> 
        <p align="left"><label>Username:</label> 
        <input type="text" placeholder="Enter a unique Username" name="username" required [A-Za-z0-9] autocorrect=off value="<?php if(isset($_POST['username'])) { echo htmlentities($_POST['username']); }?>">
        </p> 
    </div> 
    <div class="form-group"> 
        <p align="left"><label>Password:</label> 
        <input type="password" placeholder="Enter a new Password" name="password" required [A-Za-z0-9] autocorrect=off>
        </p>     
    </div> 
    <div class="form-group">     
        <p align="left"><label>Repeat Password:</label> 
        <input type="password" placeholder="Repeat Password" name="password_confirmation" required [A-Za-z0-9] autocorrect=off>
        </p> 
    </div> 
    <div class="form-group"> 
        <p align="left"><label>Primary Domain:</label> 
        <input type="text" placeholder="Enter your Primary Domain" name="primary_website_domain" required [A-Za-z0-9] autocorrect=off value="<?php if(isset($_POST['primary_website_domain'])) { echo htmlentities($_POST['primary_website_domain']); }?>">
        </p> 
    </div> 
    <div class="form-group"> 
        <p align="left"><label>Repeat Primary Domain:</label> 
        <input type="text" placeholder="Repeat Primary Domain" name="primary_website_domain_confirmation" required [A-Za-z0-9] autocorrect=off value="<?php if(isset($_POST['primary_website_domain_confirmation'])) { echo htmlentities($_POST['primary_website_domain_confirmation']); }?>">
        </p> 
    </div> 
    <div class="form-group"> 
        <p align="left"><label>Primary Website Email:</label> 
        <input type="text" placeholder="Primary Website Email" name="primary_website_email" required [A-Za-z0-9] autocorrect=off value="<?php if(isset($_POST['primary_website_email'])) { echo htmlentities($_POST['primary_website_email']); }?>">
        </p> 
    </div> 
    <div class="form-group"> 
        <p align="left"><label>Repeat Primary Website Email:</label> 
        <input type="text" placeholder="Repeat Website Email" name="primary_website_email_confirmation" required [A-Za-z0-9] autocorrect=off value="<?php if(isset($_POST['primary_website_email_confirmation'])) { echo htmlentities($_POST['primary_website_email_confirmation']); }?>">
        </p> 
    </div> 
    <div class="form-group"> 
        <p align="left"><label>Age Range:</label> 
        <input type="radio" name="age_range" value="18-20" <?php if(isset($_POST['age_range'])) { echo 'checked'; }?> required>18-20 
        <input type="radio" name="age_range" value="21-25" <?php if(isset($_POST['age_range'])) { echo 'checked'; }?> required>21-25 
        <input type="radio" name="age_range" value="26-30" <?php if(isset($_POST['age_range'])) { echo 'checked'; }?> required>26-30 
        <input type="radio" name="age_range" value="31-35" <?php if(isset($_POST['age_range'])) { echo 'checked'; }?> required>31-35 
        <input type="radio" name="age_range" value="36-40" <?php if(isset($_POST['age_range'])) { echo 'checked'; }?> required>36-40 
        <input type="radio" name="age_range" value="41-45" <?php if(isset($_POST['age_range'])) { echo 'checked'; }?> required>41-45 
        <input type="radio" name="age_range" value="46-50" <?php if(isset($_POST['age_range'])) { echo 'checked'; }?> required>46-50  
        <input type="radio" name="age_range" value="51-55" <?php if(isset($_POST['age_range'])) { echo 'checked'; }?> required>51-55 
        <input type="radio" name="age_range" value="56-60" <?php if(isset($_POST['age_range'])) { echo 'checked'; }?> required>56-60 
        <input type="radio" name="age_range" value="61-65" <?php if(isset($_POST['age_range'])) { echo 'checked'; }?> required>61-65  
        <input type="radio" name="age_range" value="66-70" <?php if(isset($_POST['age_range'])) { echo 'checked'; }?> required>66-70 
        <input type="radio" name="age_range" value="71-75" <?php if(isset($_POST['age_range'])) { echo 'checked'; }?> required>71-75
        </p>  
    </div>
    <div class="form-group"> 
        <p align="left"><label>Agree To Our Terms & Conditions ? :</label> 
        <input type="radio" name="fb_tos_agreement_reply" value="Yes" <?php if(isset($_POST['fb_tos_agreement_reply'])) { echo 'checked'; }?> required>Yes  
        <input type="radio" name="fb_tos_agreement_reply" value="No" <?php if(isset($_POST['fb_tos_agreement_reply'])) { echo 'checked'; }?> required>No
        </p>  
    </div> 
<p align="left"><input type="submit" class="btn btn-default" name="submit" value="Submit"></p> 
<p align="left"><input type="reset" class="btn btn-default" name="reset" value="Reset"></p> 
<p align="left"><font color="red" size="3"><b>Already have an account ?</b><a href="login.php">Login here!</a></font></p> 
</form> 
</div> 
</body> 
</html>      
	

 

I am still experimenting with SANITIZATION and so ignore the SANITIZATION lines.

 

Link to comment
Share on other sites

  • 2 weeks later...
On 11/29/2018 at 5:20 AM, requinix said:

Long question short reply:

No, the argument does not need to be casted from int to string. PHP will do it automatically.

I been told I can try these:

 

If Iwant an all-numeric string:

$id = rand(10000000, 99999999);

If I'd be okay with numbers plus the letters a-f:

$id = uniqid();

If I wanted more variety and harder to spoof values, I might use:

$id = substr(0, 16, base64_encode(md5(uniqid(null, true))));

If I want a decent variety and to make it easy to read/type by the user, maybe:

$parts = array_fill(0, 4, 1);
foreach($parts as &$part) { $part = rand(1000, 9999); }
$id = implode('-', $parts);

// $id is now something like "5475-1692-1301-2589"

 

I actually like the look of this format:

// $id is now something like "5475-1692-1301-2589"

But, let's assume I get tonnes of users then there is a slight chance of collision. How to avoid it ?
I can always add the user's Username like so: "requinix-1692-1301-2589" but then again we go back to mysql tbl column type "varchar" and I am trying to keep it at "Int". I think the best thing to do here is convert the Username's chars to INT where "a=1", "b=2" and so on. What you say about all this ? (Remember Usernames would be unique).
Reason why I don't want too long a code is because I am going to force the User to read his code infront of his cam (while ID confirmation time) and people won't like reading too long a code or they could easily make mistake in reading the digits.
Any other suggestions ?

Or better. maybe I generate code in this format to avoid collisions:
ID-Username-Gender-Zip-Mobile-City-Country-Year
And ofcourse, convert all of that to INT where "a=1", "b=2" and so on. 
But then again, we're still back to square one where the user might read a digit wrong. have to eliminate that risk. Any ideas ?
Or maybe, I just keep it like the following and forget converting the String to INT ?
01-requinix-female-ny7-0123456789-new york-usa-2018

What you opinion about all this ?

 
 
Link to comment
Share on other sites

The correct way to avoid collisions is to not use hashes or randomness. Encryption and/or clever application of math can get you something unique that looks random, if you know how. Anything else you come up with will be bad.

And use regular IDs internally. If you want to present something different to the user then you present something different. Real example: my job uses a scheme that derives a unique alphanumeric identifier from our IDs, and those can be presented to the user and even reversed.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.