WP Auto Login From Yii2 using Curl not working with first boot

I am working on WordPress startup from YII2. Below is my code.

function.php (WP)

function autologin() 
{   
    $strCookie = 'PHPSESSID=' . $_COOKIE['PHPSESSID'] . '; path=/';
    session_write_close();
    $ch = curl_init("http://example.com/testregister/wplogin"); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt( $ch, CURLOPT_COOKIE, $strCookie ); 
    $response = curl_exec($ch); 
    curl_close($ch);

    $newres = json_decode($response);
    $email = $newres->email;
    $password = $newres->password;
    $result = $newres->result;

    if($result == 1)
    {
        $creds = array();
        $creds['user_login'] = $email;
        $creds['user_password'] = $password;
        $creds['remember'] = false;

        $user = wp_signon( $creds );

        if ( is_wp_error( $user ) )
        {
            echo $user->get_error_message();
        }
    }
    else
    {
        wp_destroy_current_session();
        wp_clear_auth_cookie();
        do_action( 'wp_logout' );
    }
}
// ADD CODE JUST BEFORE HEADERS AND COOKIES ARE SENT
add_action( 'init', 'autologin' );

testregister / wplogin: (YII2)

public function actionWplogin()
    {
        $userEmail = Yii::$app->user->identity->Email;
        $userpw = Yii::$app->user->identity->Password;
        $result = 1;
        if($userEmail == "")
        {
            $result = 0;
        }

        return  '{"email":"'.$userEmail.'", "password":"'.$userpw.'" ,"result":"'.$result.'"}';
    }

This function is called every time the wordpress site loads. but the first time he didn’t enter the site.

If I use wp_redirect( esc_url( home_url() ) );, the login function works fine, but wp-admin does not work after using the redirect.

+4
source share
1 answer

I have found a solution. Below is the code in the .php function in the autologin () function

if (!is_user_logged_in ())
        {
            $creds = array();
            $creds['user_login'] = $email;
            $creds['user_password'] = $password;
            $creds['remember'] = false;

            $user = wp_signon( $creds );

            if ( is_wp_error( $user ) )
            {
                echo $user->get_error_message();
            }
            wp_redirect( esc_url(  "http://" . $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'] ) );
            exit;
        }

if the user did not start logging in and redirected the page. :)

+4
source

All Articles