0

I made custom plugin about login, register, and forgot password.

And I give my plugin add_action template_redirect hooks to verify email, when user login and then redirect to homepage, and forgot password.

But I have bugs, I think the template_redirect hooks do not know which is redirect for verify and which is redirect for forgot password.

Please take a look at my code:

this is custom-plugin.php

    <?php
    
    if( ! defined('PLUGIN_PATH') ){
        define('PLUGIN_PATH' , plugin_dir_path(__FILE__));
    }
    
    require_once ABSPATH . 'wp-admin/includes/plugin.php';
    require_once ABSPATH . 'wp-admin/includes/upgrade.php';
    require_once PLUGIN_PATH . 'includes/register.php';
    require_once PLUGIN_PATH . 'includes/login.php';
    require_once PLUGIN_PATH . 'includes/forgot-password.php';
    require_once PLUGIN_PATH . 'includes/change-password.php';
    require_once PLUGIN_PATH . 'includes/functions.php';


    if( ! class_exists('main')){
        class main {
       
            function register(){

                // Start session on init hook.
                add_action( 'init', array('myFunctions','wpse16119876_init_session') );
          
                add_action ('template_redirect', array( 'forgotPasswordForm', 'forgotPassword'));
              
  
                add_action ('template_redirect', array( 'loginForm', 'verify'));
               
                add_action ('template_redirect', array( 'loginForm', 'set_submit_login_func'));
           
               
            }
       

        }

        $main = new main();
        $main->register();
        
       
  

   }

    

    
  ?>

lets assume that I insert SMTP email setting and have the form. I'm only giving functions that have wp_redirect.

And then this is login.php,

<?php
        class loginForm extends registerForm{
    
        public function set_submit_login_func(){
            global $wpdb;
    
            $account = filter_input(INPUT_POST, 'account');
            $password = filter_input(INPUT_POST, 'password');
    
            $users = $wpdb->get_row( $wpdb->prepare("SELECT * FROM {$wpdb->prefix}users WHERE user_email = '$account' OR user_login = '$account'", ARRAY_A));
           
            ob_start();
    
            if(isset($_POST["login"])){
                if($users){
                    if($users->user_status == 0){
                        if(wp_check_password($password, $users->user_pass)){
                            $credentials = array(
                                'user_login' => $account,
                                'user_password' => $password
                            );
    
                            wp_signon($credentials, true);
                            wp_redirect(site_url());
                            exit;
                        } else{
                            $_SESSION["message"] = '<div style="background-color: indianred; color: #FFFFFF; line-height: 30px; height: 10%; text-align: center; top: 0px; width: 100%; z-index: 100; margin-bottom: 10px;">Password Salah</div>';
                        }
                    } else{
                        $_SESSION["message"] = '<div style="background-color: indianred; color: #FFFFFF; line-height: 30px; height: 10%; text-align: center; top: 0px; width: 100%; z-index: 100; margin-bottom: 10px;">Akun Belum di Aktifkan!</div>';
                    }
                   
                }else{
                    if($account != ($users->user_email && $user_login)){
                        $_SESSION["message"] = '<div style="background-color: indianred; color: #FFFFFF; line-height: 30px; height: 10%; text-align: center; top: 0px; width: 100%; z-index: 100; margin-bottom: 10px;">Akun Belum Terdaftar!</div>';
                    }
                  
                }
    
            }
            
            session_destroy();
    
            return ob_get_clean(); 
    
        }
    
        
        public function verify(){
        
                global $wpdb;
                
                $email = $_GET["em"];
                $token = $_GET["tk"];
                $url = site_url() .'/login';
                
                $registered_date = date( 'Y-m-d H:i:s', current_time( 'timestamp', 0 ) );  
         
                $users = $wpdb->get_row( $wpdb->prepare("SELECT * FROM {$wpdb->prefix}users WHERE user_email = '$email'", ARRAY_A));
         
                if($users){
         
                    $user_token = $wpdb->get_row( $wpdb->prepare("SELECT * FROM {$wpdb->prefix}user_token WHERE token = '$token'", ARRAY_A));
         
                    if($user_token){
                        if(time() - $user_token->date_created < (60*60*24)){
         
                            $wpdb->update($wpdb->prefix . 'users', ["user_status" => 0, "user_registered" => $registered_date], ["user_email" => $email]);
         
                            $wpdb->delete($wpdb->prefix . 'user_token', ['email' => $email]);
         
                            $_SESSION["message"] = '<div style="background-color: darkcyan; color: #FFFFFF; line-height: 30px; height: 10%; text-align: center; top: 0px; width: 100%; z-index: 100; margin-bottom: 10px;">'.$email.'&nbsp'.'telah aktif, silahkan login'.'</div>';
         
                            wp_redirect($url);
                            exit;
         
         
                        }else{
                            $wpdb->delete($wpdb->prefix . 'users', ['user_email' => $email]);
                            $wpdb->delete($wpdb->prefix . 'user_token', ['email' => $email]);
         
         
                            $_SESSION["message"] = '<div style="background-color: indianred; color: #FFFFFF; line-height: 30px; height: 10%; text-align: center; top: 0px; width: 100%; z-index: 100; margin-bottom: 10px;">'.'Aktivasi akun gagal! Token kadaluarsa'.'</div>';
                          
                            wp_redirect($url);
                            exit;
                        }
         
                 
                    }else{
                        if(($token != $user_token) === true){
                            $_SESSION["message"] = '<div style="background-color: indianred; color: #FFFFFF; line-height: 30px; height: 10%; text-align: center; top: 0px; width: 100%; z-index: 100; margin-bottom: 10px;">'.'Aktivasi akun gagal! Token salah'.'</div>';
                          
                            wp_redirect($url);    
                            exit;
                 
                        }
                    }
                       
                }else{
         
                    if(($email != $users->user_email) === true){   
                         
                        $_SESSION["message"] = '<div style="background-color: indianred; color: #FFFFFF; line-height: 30px; height: 10%; text-align: center; top: 0px; width: 100%; z-index: 100; margin-bottom: 10px;">'.'Aktivasi akun gagal! Email salah'.'</div>';
                         
                        wp_redirect($url);    
                        exit;
                         
                    }
         
                }
        
                session_destroy();
             
            } 
        
        
        }
?>

this is forgot-password.php

<?php
    class forgotPasswordForm extends loginForm{
    
    
        public function forgotPassword(){
    
            global $wpdb;
    
            $email = $_GET["em"];
            $token = $_GET["tk"];
            $url = site_url() .'/login/forgotpassword';
    
            $other_url = add_query_arg(
                array(
                    'req:em' =>$email,
                    'tk' => $token
                ), site_url().'/changepassword'
            );
    
            
            
            $users = $wpdb->get_row( $wpdb->prepare("SELECT * FROM {$wpdb->prefix}users WHERE user_email = '$email'", ARRAY_A));
            
          
            if($users){
                $user_token = $wpdb->get_row( $wpdb->prepare("SELECT * FROM {$wpdb->prefix}user_token WHERE token = '$token'", ARRAY_A));
               
                if($user_token){
                    if(time() - $user_token->date_created < (60*60*24)){
                     
                        $_SESSION["message"] = '<div style="background-color: darkcyan ; color: #FFFFFF; line-height: 30px; height: 10%; text-align: center; top: 0px; width: 100%; z-index: 100; margin-bottom: 10px;">'.'Setel ulang kata sandi: '.$email.'</div>';
        
                        wp_redirect($other_url);
    
                        exit;
    
                    }
                    else{
                        $wpdb->delete($wpdb->prefix . 'user_token', ['email' => $email]);
     
                        $_SESSION["message"] = '<div style="background-color: indianred; color: #FFFFFF; line-height: 30px; height: 10%; text-align: center; top: 0px; width: 100%; z-index: 100; margin-bottom: 10px;">'.'Setel ulang kata sandi gagal! Token kadaluarsa'.'</div>';
                      
                        wp_redirect($url);
                        exit;
                    }
    
                }
                
                else{
                    if($token != $user_token){
                        
                        $_SESSION["message"] = '<div style="background-color: indianred; color: #FFFFFF; line-height: 30px; height: 10%; text-align: center; top: 0px; width: 100%; z-index: 100; margin-bottom: 10px;">'.'Setel ulang kata sandi gagal! Token salah'.'</div>';
                      
                        wp_redirect($url);    
                        exit;
                  
                    }
                }
                   
            }else{
     
                if($email != $users->user_email){   
                    
                    $_SESSION["message"] = '<div style="background-color: indianred; color: #FFFFFF; line-height: 30px; height: 10%; text-align: center; top: 0px; width: 100%; z-index: 100; margin-bottom: 10px;">'.'Setel ulang kata sandi gagal! Email salah'.'</div>';
                    
                    wp_redirect($url); 
                    exit;
            
                }
           
            }
            
    
        }
    
    
    }

?>

and I put sendEmail functions in functions.php

<?php
class myFunctions {


  protected static function _sendEmail($token, $type){

            $sendto = filter_input(INPUT_POST, 'email');
            $sendfrom = 'hendratrisno@gmail.com';
            $headers = array("Content-type:text/html; charset=UTF-8","From: Me Myself <". $sendfrom . ">");
            if($type == 'verify'){
                $sendsub = 'Verify Account';
                $sendmess = 'Please click to activate your account:<a href="'.site_url(). '/login/verify?em='.filter_input(INPUT_POST, 'email'). '&tk='.urlencode_deep($token).'">Activate</a>';
            }
            if($type == 'forgot'){
                $sendsub = 'Reset Password';
                $sendmess = 'Please click to reset your password:<a href="'.site_url(). '/login/forgotpassword?em='.filter_input(INPUT_POST, 'email'). '&tk='.urlencode_deep($token).'">Reset Password</a>';
    
            }
                   
            wp_mail($sendto, $sendsub, $sendmess, $headers);
            
        }




}


?>

and for inheritance, my code like this:

class myFunctions
class registerForm extends myFunctions 
class loginForm extends registerForm
class forgotPasswordForm extends loginForm
class changePasswordForm extends forgotPasswordForm

This is where _sendEmail static functions called:

this is inside forgot-password.php

public function set_submit_forgot_password_func(){
        global $wpdb;
    
        $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);

        $token = $this->token = base64_encode(random_bytes(32));

        ob_start();

        if(isset($_POST["forgot-password"])){

            if(!filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL) === true){
                $this->error["email"] = "* email tidak valid";
            }
            else if(!email_exists($email)){
                $this->error["email"] = "* email tidak terdaftar";
            }
            else{
                if($this->error["email"]){
                    unset($_POST);
                    return false;
                }
                else{
                    $_SESSION["message"] = '<div style="background-color: darkcyan; color: #FFFFFF; line-height: 30px; height: 10%; text-align: center; top: 0px; width: 100%; z-index: 100; margin-bottom: 10px;">Kami kirim email ke '.$_POST["email"].', mohon segera setel ulang kata sandi sebelum 24 jam dari sekarang!'.'</div>';
                   
                    $user_token = [
                        'id' => '',
                        'email' => $email,
                        'token' => $token,
                        'date_created' => time()
                    ];

            
                    $wpdb->insert($wpdb->prefix . 'user_token', $user_token);

                    forgotPasswordForm::_sendEmail($token, 'forgot');
          
                }
            }
        }

        session_destroy();


        return ob_get_clean();

    }

and here is register.php when code send email verification:

public function set_submit_func(){
        global $wpdb;
        
        $fname = filter_input(INPUT_POST, 'fname', FILTER_SANITIZE_STRING);
        $lname = filter_input(INPUT_POST, 'lname', FILTER_SANITIZE_STRING);
        $username  = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
        $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
        $password = wp_hash_password(filter_input(INPUT_POST, 'password', FILTER_DEFAULT));
        $repeat_password = wp_hash_password(filter_input(INPUT_POST, 'repeat_password', FILTER_DEFAULT));

        $regexp_username = array("options"=>array("regexp"=>"/^[a-zA-Z\d\D]+$/"));
        $regexp_name = array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/"));
        $regexp_password = array("options"=>array("regexp"=>"/^[a-zA-Z\d\D]+$/"));

        $token = $this->token = base64_encode(random_bytes(32));


        ob_start();
        
        if(isset($_POST["submit2"])){
            
            if(!filter_input(INPUT_POST, 'fname', FILTER_VALIDATE_REGEXP, $regexp_name ) === true){
                $this->error["fname"] = "* nama depan tidak valid";
            }
            if(!filter_input(INPUT_POST, 'lname', FILTER_VALIDATE_REGEXP, $regexp_name) === true){
                $this->error["lname"] = "* nama belakang tidak valid";
            }

            if(!filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL) === true){
                $this->error["email"] = "* email tidak valid";
            }
            else if (email_exists($email)) {
                $this->error["email"] = "* email sudah ter-registrasi";
            }

            if(!filter_input(INPUT_POST, 'username', FILTER_VALIDATE_REGEXP, $regexp_username ) === true){
                $this->error["username"] = "* username tidak valid";
            }
            else if (username_exists($username)){
                $this->error["username"] = "* username telah terdaftar";
            }

            if(!filter_input(INPUT_POST, 'password', FILTER_VALIDATE_REGEXP, $regexp_password) === true){
                $this->error["password"] = "* password tidak valid";
            }
            else if(strlen($_POST["password"]) < 5){
                $this->error["password"] = "* password tidak boleh kurang dari 5 karakter";
            }
            else if($_POST["repeat_password"] != $_POST["password"]){
                $this->error["repeat_password"] = "* password tidak sama";
            }
     

            else{
            
                if($this->error["lname"] || $this->error["fname"] || $this->error["username"] || $this->error["email"] || $this->error["password"] || $this->error["repeat_password"] ){
                    unset($_POST);
                    return false;
                }
                else{
                    $_SESSION["message"] = '<div style="background-color: darkcyan; color: #FFFFFF; line-height: 30px; height: 10%; text-align: center; top: 0px; width: 100%; z-index: 100; margin-bottom: 10px;">Kami kirim email ke '.$_POST["email"].', mohon segera verifikasi sebelum 24 jam dari sekarang!</div>';
                   
                    $data = [
                        'ID' => '',
                        'user_login' => $username,
                        'user_pass' => $repeat_password,
                        'user_nicename' => $username,
                        'user_email' => $email,
                        'user_status' => '1',
                        'display_name' => $username
                    ];

                    $user_token = [
                        'id' => '',
                        'email' => $email,
                        'token' => $token,
                        'date_created' => time()
                    ];

                    $wpdb->insert($wpdb->prefix . 'users', $data);
                    $wpdb->insert($wpdb->prefix . 'user_token', $user_token);

                    registerForm::_sendEmail($token, 'verify');

                }
            }
        }

        return ob_get_clean();
    }
  

This when _sendEmail function called for Reset Password:

enter image description here

but, when I click the link, redirect to login page, not changepassword page:

enter image description here

I hope I can get help to solve this bugs. Thank You!

8
  • that's not how those PHP callables work, you've told it to call a static method, but those methods are not static, so your actions are never added, and I expect you will find PHP warnings in your PHP error log that there is no loginForm::set_submit_login_func
    – Tom J Nowell
    Nov 13, 2021 at 20:16
  • thank you for reply.. I use _sendEmail static functions in register.php and forgot-password.php. I'm sorry it's because I'm not giving full code, maybe make you think where is the sendEmail functions called. I will update it right away.
    – Hendra
    Nov 14, 2021 at 16:48
  • I'm already update. Please take a look. Thank You @TomJNowell
    – Hendra
    Nov 14, 2021 at 16:53
  • I think template_redirect hook need to differentiate using if statement, but I don't know how. Any ideas? @TomJNowell
    – Hendra
    Nov 14, 2021 at 17:08
  • That is not true, your question contains the code for set_submit_login_func and it is not a static function. If you want to call a class function that is not dynamic you need to change your callable to specify the object the function should be called on. Your problem has nothing to do with template_redirect or filters, it's a basic PHP issue, a misunderstanding of how the callable type works in PHP. You should read php.net/manual/en/language.types.callable.php
    – Tom J Nowell
    Nov 14, 2021 at 19:19

1 Answer 1

0

The code adds the functions like this:

add_action ('template_redirect', array( 'loginForm', 'set_submit_login_func'));

Which tells PHP to do this when template_redirect happens:

loginForm::set_submit_login_func();

But we can see set_submit_login_func in the questions code and it is clear that it is not a static function:

public function set_submit_login_func(){

What you want is a dynamic callable, e.g.

class MyClass {
    public function test() { }
}

$obj = new MyClass();
add_action( '...', array( $obj, 'test' ) );

Where array( $obj, 'test' ) is the same as $obj->test(). Notice that the first parameter is the object to call the function on, not the name of the class.

I strongly recommend reading about how to use PHP callables to understand this better: https://www.php.net/manual/en/language.types.callable.php

2
  • Hello, sorry for late reply. I'm already do what you tell me. But still not working.. I update my code like this: $obj = new loginForm; $obj2 = new forgotPasswordForm; add_action ('template_redirect', array($obj2, 'forgotPassword')); add_action ('template_redirect', array($obj, 'verify')); add_action ('template_redirect', array($obj, 'set_submit_login_func')); but still not working.
    – Hendra
    Nov 16, 2021 at 16:28
  • then it's likely there is more than one problem, there is not enough information to fix your code as it's not clear what it does and most of it is missing from your question. I'm not even sure what the bug you need help with is, just that whatever it's meant to do, it isn't doing.
    – Tom J Nowell
    Nov 16, 2021 at 17:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.