Android Code Snippet Register User example using HttpUtils2

Discussion in 'Code Snippets' started by aeric, Mar 27, 2015.

  1. aeric

    aeric Active Member Licensed User

    Do you have mysql database in your hosting server?
     
  2. jchal

    jchal Active Member Licensed User

    as i am new to this i am trying to do a password recovery but....... as i say i am new
    i made anew activity called forgotpwd and a php file caled pwdrecovery.php
    my coude for forgotpwd activity is the following
    #Region Activity Attributes
    #FullScreen: False
    #IncludeTitle: False
    #End Region

    Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.

    End Sub

    Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.
    Dim txtEmail As EditText
    Private btnsendnewpwd As Button
    End Sub

    Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    'Activity.LoadLayout("Layout1")
    Activity.LoadLayout("frmforgotpwd")

    End Sub

    Sub Activity_Resume

    End Sub

    Sub Activity_Pause (UserClosed As Boolean)

    End Sub


    Sub btnsendnewpwd_Click
    Dim strEmail As String = txtEmail.Text.Trim
    If strEmail = "" Then
    Msgbox("Please enter Email", "Error")
    Return
    End If
    If Validate_Email(strEmail) = False Then
    Msgbox("Email format is incorrect", "Error")
    Return
    End If


    Dim forgotpwd As HttpJob
    forgotpwd.Initialize("forgotpwd", Me)
    forgotpwd.Download2("http://www.mydomainname.com/pwdrecovery.php", _
    Array As String("Action", "forgotpwd", "Email", txtEmail.Text))
    ProgressDialogShow("Connecting to server...")
    Msgbox("A mail was sent to your e-mail. Please click on the link to finish registration", "forgotpwd")
    Activity.Finish

    End Sub


    ' // Source: http://www.b4x.com/android/forum/threads/validate-a-correctly-formatted-email-address.39803/
    Sub Validate_Email(EmailAddress As String) As Boolean
    Dim MatchEmail As Matcher = Regex.Matcher("^(?i)[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])$", EmailAddress)

    If MatchEmail.Find = True Then
    Log(MatchEmail.Match)
    Return True
    Else
    Log("Oops, please double check your email address...")
    Return False
    End If
    End Sub


    and the code for php is the following:
    <?php
    $host = "localhost";
    $db = "tmydb";
    $user = "myuserdb";
    $pw = "test";

    $con = mysql_connect($host,$user,$pw) or die(mysql_error());
    mysql_select_db($db) or die(mysql_error());
    mysql_query("SET CHARACTER SET utf8");
    mysql_query("SET NAMES 'utf8'");

    $action = $_GET["Action"];

    switch ($action) {
    case "forgotpwd":
    $user = mysql_real_escape_string($_GET["UserID"]);
    $email = mysql_real_escape_string($_GET["Email"]);


    $q = mysql_query("SELECT * FROM tbl_member WHERE Email= '$email'");

    $user =$rows['UserID'];
    $pass = $rows['pass_word'];
    $count = mysql_num_rows($q);

    $to = $email;
    $subject = 'Your password is';
    $message = 'Hi ' . $user . ',' . "\r\n" . 'this is your password is' . $pass ;
    $message = wordwrap($message, 70, "\r\n");
    $headers = 'From: info@mydomainname.com' . "\r\n" . 'Reply-To: info@mydomainname.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion();


    }
    else

    break;




    }
    break;
    default:
    echo("Unauthorized action! Please use the app to register.");
    }
    ?>

    but the app stops inProgressDialogShow("Connecting to server...")
    what i am making wrong???
     
  3. aeric

    aeric Active Member Licensed User

    You are missing Jobdone.
     
  4. jchal

    jchal Active Member Licensed User

    now i am having a problem with my php i have managed to do the jobdone, but in e-mails i get the $row[pass_word] and $row[user_name] are empty what is my mistaske? cah you help?


    <?php
    $host = "localhost";
    $db = "tmydb";
    $user = "myuserdb";
    $pw = "test";

    $con = mysql_connect($host,$user,$pw) or die(mysql_error());
    mysql_select_db($db) or die(mysql_error());
    mysql_query("SET CHARACTER SET utf8");
    mysql_query("SET NAMES 'utf8'");

    $action = $_GET["Action"];

    switch ($action) {
    case "forgotpwd":

    $email = mysql_real_escape_string($_GET["Email"]);
    $q = mysql_query("SELECT * FROM tbl_member WHERE email = '$email' ");
    $count = mysql_num_rows($q);

    if ($count == 1)
    {

    $res = mysql_query($sql);
    while($r = mysql_fetch_assoc($res))


    $to = $email;
    $subject = 'Your Password';
    $message = 'Hi ' . $row[user_name]. ',' . "\r\n" . 'this is your password as requested. : password=' . $row[pass_word];
    $message = wordwrap($message, 70, "\r\n");
    $headers = 'From:info@mydomainname.com' . "\r\n" . 'Reply-To:info@mydomainname.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);
    // Notify me of new sign up
    mail('info@mydomainname.com', 'password request', 'the member (' . $row[user_name] . ') has asked a new password for the app.', $headers);

    print json_encode ("Mail");
    }

    else
    print json_encode ("Mailnotfound");
    break;

    case "Mail":
    $mail=$_GET["Mail"];

    $q = mysql_query("SELECT * FROM tbl_member WHERE email = '$mail' ");
    $count=mysql_num_rows($q);

    if ($count == 0)
    {
    print json_encode ("This mail address does not exist in our database");
    }
    else {

    echo("$mail is send");
    }
    break;
    default:
    echo("Unauthorized action! Please use the app.");
    }
    ?>
     
  5. aeric

    aeric Active Member Licensed User

     
    lemonisdead likes this.
  6. aeric

    aeric Active Member Licensed User

    I think you also need to modify the following
    to
     
  7. jchal

    jchal Active Member Licensed User

    hre is my new updated code, i still face problems like the first e-mail with the pass word is not cumming any more, and the second e-mail is comming to my mail box but empty.
    e-mail rusult below
    the member () has asked a new password for the app.
    php source code below

    <?php
    $host = "localhost";
    $db = "tmydb";
    $user = "myuserdb";
    $pw = "test";
    $con = mysql_connect($host,$user,$pw) or die(mysql_error());
    mysql_select_db($db) or die(mysql_error());
    mysql_query("SET CHARACTER SET utf8");
    mysql_query("SET NAMES 'utf8'");

    $action = $_GET["Action"];

    switch ($action) {
    case "forgotpwd":

    $email = mysql_real_escape_string($_GET["Email"]);
    $q = mysql_query("SELECT * FROM tbl_member WHERE email = '$email' ");
    $count = mysql_num_rows($q);

    if ($count == 1)
    {

    $res = mysql_query($sql);
    while($row = mysql_fetch_assoc($res))


    $to = $email;
    $subject = 'Your Password';
    $username = $row["user_name"];
    $password = $row["pass_word"];
    $message = 'Hi ' . $username . ',' . "\r\n" .'This is your password as requested. : password : ' . $password;
    $message = wordwrap($message, 70, "\r\n");
    $headers = 'From: nfo@mydomain.com' . "\r\n" . 'Reply-To: info@mydomain.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);
    // Notify me of new sign up
    mail('info@mydomain.com', 'password request', 'the member (' . $username . ') has asked a new password for the app.', $headers);

    print json_encode ("Mail");
    }

    else
    print json_encode ("Mailnotfound");
    break;

    case "Mail":
    $mail=$_GET["Mail"];

    $q = mysql_query("SELECT * FROM tbl_member WHERE email = '$mail' ");
    $count=mysql_num_rows($q);

    if ($count == 0)
    {
    print json_encode ("This mail address does not exist in our database");
    }
    else {

    echo("$mail is send");
    }
    break;
    default:
    echo("Unauthorized action! Please use the app.");
    }
    ?>
     
    Last edited: Mar 9, 2016
  8. aeric

    aeric Active Member Licensed User

    I haven't test hope this would be working for you.
     
  9. jchal

    jchal Active Member Licensed User

    i am getting an Error: Internal Server Error
     
  10. aeric

    aeric Active Member Licensed User

    I try to reproduce this.
     
  11. aeric

    aeric Active Member Licensed User

    Here is my code for the request forgotten password.

    B4A Code
    Code:
    #Region  Activity Attributes 
        
    #FullScreen: False
        
    #IncludeTitle: False
    #End Region

    Sub Process_Globals

    End Sub

    Sub Globals
        
    Private txtEmail As EditText
        
    Dim strEmail As String
    End Sub

    Sub Activity_Create(FirstTime As Boolean)
        
    Activity.LoadLayout("frmForgot")
    End Sub

    Sub Activity_Resume

    End Sub

    Sub Activity_Pause (UserClosed As Boolean)

    End Sub

    Sub btnSubmit_Click
        strEmail = txtEmail.Text.Trim
        
    If strEmail = "" Then
            
    Msgbox("Please enter Email""Error")
            
    Return
        
    End If   
        
    If Validate_Email(strEmail) = False Then
            
    Msgbox("Email format is incorrect""Error")
            
    Return
        
    End If
        
    Dim Forgot As HttpJob
        Forgot.Initialize(
    "SendPassword", Me)
        Forgot.Download2(
    "http://kbase.herobo.com/forgot-password.php", _
          
    Array As String("Action""RequestPassword", _
         
    "Email", strEmail))
        
    ProgressDialogShow("Connecting to server...")   
    End Sub

    Sub JobDone (Job As HttpJob)
        
    ProgressDialogHide
        
    If Job.Success Then
        
    Dim res As String, action As String
            res = Job.GetString        
            
    Dim parser As JSONParser
            parser.Initialize(res)                
            
    Select Job.JobName
                
    Case "SendPassword"
                    action = parser.NextValue
                    
    If action = "ValidEmail" Then
                        
    Msgbox("The password was sent to " & strEmail & ".""Forgot Password")                   
                    
    Else If action = "InvalidEmail" Then
                        
    Msgbox("The email is not registered in our database.""Forgot Password")
                    
    End If
            
    End Select
        
    Else
            
    'Log("Error: " & Job.ErrorMessage)
            ToastMessageShow("Error: " & Job.ErrorMessage, True)
        
    End If
        Job.Release   
    End Sub

    ' // Source: http://www.b4x.com/android/forum/threads/validate-a-correctly-formatted-email-address.39803/
    Sub Validate_Email(EmailAddress As StringAs Boolean
        
    Dim MatchEmail As Matcher = Regex.Matcher("^(?i)[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])$", EmailAddress)

        
    If MatchEmail.Find = True Then
            
    'Log(MatchEmail.Match)
            Return True
        
    Else
            
    'Log("Oops, please double check your email address...") 
            Return False
        
    End If
    End Sub

    PHP Script
    PHP:
    <?php
    $host 
    "mysql16.000webhost.com";
    $db "a1438837_db";
    $user "a1438837_id";
    $pw "a1438837";

    $con mysql_connect($host,$user,$pw) or die(mysql_error());
    mysql_select_db($db) or die(mysql_error());
    mysql_query("SET CHARACTER SET utf8");
    mysql_query("SET NAMES 'utf8'");

    $action $_GET["Action"];
    $email mysql_real_escape_string($_GET["Email"]);

    switch (
    $action) {
        case 
    "RequestPassword":        
            
    $sql "SELECT user_name, pass_word FROM tbl_member WHERE email = '" $email "'";
            
    $res mysql_query($sql);
            if (!
    $res) {
                print 
    json_encode("MySQL_Error");
                echo 
    "<br />" mysql_error();
                exit;
            }
            
    $count mysql_num_rows($res);            
            if (
    $count == 0) {
                print 
    json_encode("InvalidEmail");
            }
            else {
                
    $row mysql_fetch_row($res);
                
    $to      $email;
                
    $subject 'Your Password';
                
    $username $row[0];
                
    $password $row[1];
                
    $message "Hi " $username ",\r\n";
                
    $message .= "This is your password as requested.\r\n";
                
    $message .= "Password: " $password;
                
    $message wordwrap($message70"\r\n");
                
    $headers "From: no-reply@kbase.herobo.com" "\r\n";
                
    $headers .= "Reply-To: no-reply@kbase.herobo.com\r\n";
                
    $headers .= "X-Mailer: PHP/" phpversion();
                
    mail($to$subject$message$headers);
                print 
    json_encode ("ValidEmail");
            }
            break;
        default:
                echo(
    "Unauthorized action! Please use the app to register.");
    }
    ?>

    Cheers!
     
    inakigarm likes this.
  12. aeric

    aeric Active Member Licensed User

    Above method is to send the existing password to the user.

    To request for new password, please use this:
    B4A Code
    Code:
    #Region  Activity Attributes 
        
    #FullScreen: False
        
    #IncludeTitle: False
    #End Region

    Sub Process_Globals

    End Sub

    Sub Globals
        
    Private txtEmail As EditText
        
    Dim strEmail As String
    End Sub

    Sub Activity_Create(FirstTime As Boolean)
        
    Activity.LoadLayout("frmForgot")
    End Sub

    Sub Activity_Resume

    End Sub

    Sub Activity_Pause (UserClosed As Boolean)

    End Sub

    Sub btnSubmit_Click
        strEmail = txtEmail.Text.Trim
        
    If strEmail = "" Then
            
    Msgbox("Please enter Email""Error")
            
    Return
        
    End If   
        
    If Validate_Email(strEmail) = False Then
            
    Msgbox("Email format is incorrect""Error")
            
    Return
        
    End If
        
    Dim Reset As HttpJob
        Reset.Initialize(
    "ResetPassword", Me)
        Reset.Download2(
    "http://kbase.herobo.com/reset-password.php", _
          
    Array As String("Action""RequestPasswordReset", _
         
    "Mail", strEmail))
        
    ProgressDialogShow("Connecting to server...")
    End Sub

    Sub JobDone (Job As HttpJob)
        
    ProgressDialogHide
        
    If Job.Success Then
        
    Dim res As String, action As String
            res = Job.GetString        
            
    Dim parser As JSONParser
            parser.Initialize(res)
            
    Select Job.JobName
                
    Case "ResetPassword"
                    action = parser.NextValue
                    
    If action = "ValidEmail" Then
                        
    Msgbox("An email was sent to " & strEmail & " to reset your password.""Reset Password")                   
                    
    Else If action = "InvalidEmail" Then
                        
    Msgbox("The email is not registered in our database.""Reset Password")
                    
    End If
            
    End Select
        
    Else
            
    'Log("Error: " & Job.ErrorMessage)
            ToastMessageShow("Error: " & Job.ErrorMessage, True)
        
    End If
        Job.Release   
    End Sub

    ' // Source: http://www.b4x.com/android/forum/threads/validate-a-correctly-formatted-email-address.39803/
    Sub Validate_Email(EmailAddress As StringAs Boolean
        
    Dim MatchEmail As Matcher = Regex.Matcher("^(?i)[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])$", EmailAddress)

        
    If MatchEmail.Find = True Then
            
    'Log(MatchEmail.Match)
            Return True
        
    Else
            
    'Log("Oops, please double check your email address...") 
            Return False
        
    End If
    End Sub

    PHP Script
    PHP:
    <?php
    $host 
    "mysql16.000webhost.com";
    $db "a1438837_db";
    $user "a1438837_id";
    $pw "a1438837";

    $con mysql_connect($host,$user,$pw) or die(mysql_error());
    mysql_select_db($db) or die(mysql_error());
    mysql_query("SET CHARACTER SET utf8");
    mysql_query("SET NAMES 'utf8'");

    $action $_GET["Action"];
    switch (
    $action) {
        case 
    "RequestPasswordReset":
            
    $email mysql_real_escape_string($_GET["Mail"]);
            
    $sql "SELECT user_name FROM tbl_member WHERE email = '" $email "'";
            
    $res mysql_query($sql);
            if (!
    $res) {
                print 
    json_encode("MySQL_Error");
                echo 
    "<br />MySQL_Error: " mysql_error();
                exit;
            }
            
    $count mysql_num_rows($res);            
            if (
    $count == 0) {
                print 
    json_encode("InvalidEmail");
                exit;
            }
            else {
                
    // Generate a random code and update to reg_no
                
    $verify_code mt_rand(100000999999);
                
    $row mysql_fetch_row($res);
                
    $username $row[0];
                
    $sql "UPDATE tbl_member SET reg_no = '" $verify_code "' WHERE email = '" $email "'";
                
    $res mysql_query($sql);
                if (!
    $res) {
                    print 
    json_encode("MySQL_Error");
                    echo 
    "<br />MySQL_Error: " mysql_error();
                    exit;
                }
                
    // Send email to user to confirm the reset
                
    $to      $email;
                
    $subject 'Request to reset your password';
                
    $message "Hi " $username ",\r\n";
                
    $message .= "We have received a request from you to reset your password.\r\n";
                
    $message .= "If this action is not requested by you, please ignore this email.\r\n";
                
    $message .= "Otherwise, click the link below:\r\n";
                
    $message .= "http://kbase.herobo.com/reset-password.php?Action=ConfirmPasswordReset&Mail=" $email "&Code=" $verify_code "\r\n\r\n";
                
    $message .= "If not working, please copy the link to your browser.\r\n\r\n";
                
    $message .= "Regards,\r\n";
                
    $message .= "Aeric";
                
    $message wordwrap($message70"\r\n");
                
    $headers "From: no-reply@kbase.herobo.com" "\r\n";
                
    $headers .= "Reply-To: no-reply@kbase.herobo.com\r\n";
                
    $headers .= "X-Mailer: PHP/" phpversion();
                
    mail($to$subject$message$headers);
                print 
    json_encode("ValidEmail");
            }
            break;
        case 
    "ConfirmPasswordReset":
            
    $email mysql_real_escape_string($_GET["Mail"]);
            
    $code mysql_real_escape_string($_GET["Code"]);
            
    $sql "SELECT user_name FROM tbl_member WHERE email = '" $email "' AND reg_no = " $code;
            
    $res mysql_query($sql);
            if (!
    $res) {
                print 
    json_encode("MySQL_Error");
                echo 
    "<br />MySQL_Error: " mysql_error();
                exit;
            }
            
    $count mysql_num_rows($res);            
            if (
    $count == 0) {
                print 
    json_encode("InvalidEmailOrCode");
                exit;
            }
                
    // Generate a default password randomly (e.g. pw1234)
                // You may use other method to generate a more complex password with alphanumeric
                
    $rand_number mt_rand(10009999);
                
    $default "pw" $rand_number;
                
    $row mysql_fetch_row($res);
                
    $username $row[0];
                
    $sql "UPDATE tbl_member SET pass_word = '" $default "' WHERE email = '" $email "'";
                
    $res mysql_query($sql);
                if (!
    $res) {
                    print 
    json_encode("MySQL_Error");
                    echo 
    "<br />MySQL_Error: " mysql_error();
                    exit;
                }
                
    $to      $email;
                
    $subject 'Your New Password';
                
    $message "Hi " $username ",\r\n";
                
    $message .= "Your password has been reset. Please use your new password to log in.\r\n";
                
    $message .= "Password: " $default;
                
    $message wordwrap($message70"\r\n");
                
    $headers "From: no-reply@kbase.herobo.com" "\r\n";
                
    $headers .= "Reply-To: no-reply@kbase.herobo.com\r\n";
                
    $headers .= "X-Mailer: PHP/" phpversion();
                
    mail($to$subject$message$headers);
                
    //print json_encode("PasswordChanged");
                
    echo "Your password has been reset.<br />Your new password is sent to $email.";
            break;
        default:
                echo(
    "Unauthorized action! Please use the app to reset your password.");
    }
    ?>
     
    DonManfred likes this.
  13. aeric

    aeric Active Member Licensed User

    Try to understand the code and further on you can create the activity for "Change Password".
     
  14. jchal

    jchal Active Member Licensed User

    you are super!!! it works greate!!!
     
  15. mangojack

    mangojack Well-Known Member Licensed User

    @aeric .. many thanks for the thread, having not much experience with PHP it was of great help.

    I was wondering if you could look at / edit the Update for signin.php Post #3. I found it a bit confusing and feel others might also.

    Your Updated signin.php Post#3
    PHP:
    if ($count == 0) {
       print 
    json_encode ("Not Found");
    }
    else {
    // if ($row = mysql_fetch_array($res)) {
       
    if ($row["status"] == "M") {
          print 
    json_encode ("Not Activate");
       }
      else {
        
    $res mysql_query("UPDATE tbl_member SET logins = logins + 1 WHERE user_id = '$uid'");
        print 
    json_encode ($row["user_name"]);
      }
    // }
    }//mysql_free_result($res);
    ?>
    I finally managed to get it working with ...
    PHP:
    if ($count == 0) {
      print 
    json_encode ("Not Found");
    }

    else {
       
    $row mysql_fetch_array($res);    //  *******  this row commented
       
    if ($row["status"] == "M") {
          print 
    json_encode ("Not Activate");
       }
       else {
          
    $res mysql_query("UPDATE tbl_member SET logins = logins + 1 WHERE user_id = '$uid'");
          print 
    json_encode ($row["user_name"]);
       }
    }
    ?>

    Something else that too some time to find cause of error ..
    B4A code in the LogIn activity ...
    Code:
    Sub JobDone (Job As HttpJob)
       
    ProgressDialogHide
       
    If Job.Success = True Then
        
    '.............
        '.............

      
    Else If act = "Not Activated" Then  ' Change to "Not Activate"

    One more question ... After some reading I'm led to believe it is not wise to store login info directly
    in the script php's located in public folders but rather in a separate php file in the 'Root folder' and use
    'Include' keyword and the path to the php file .. ie:

    PHP:
    <?php

    include ("/home/my_webhost_account/config.php");

    $con mysql_connect($host$user$pw) or die(mysql_error());
    //.........................
    Any info / advice appreciated .. Thanks and Regards
     
    Last edited: Mar 12, 2016
  16. aeric

    aeric Active Member Licensed User

    Thanks for your suggestions. This example is for learning purpose. May not suitable for production. Actually I have little experience in php too. For my production app, I am now using pdo and encryption. I also store my database login on separate file and use include.
     
    mangojack likes this.
  17. killiak

    killiak Member Licensed User

  18. aeric

    aeric Active Member Licensed User

  19. Celso

    Celso Member Licensed User

    Very cool, work like a charm!
    Tks.
     
  20. Celso

    Celso Member Licensed User

    Change the order and set email at last in the line!!
     
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice