WP使用Curl在第一次加载时自动登录Yii2

时间:2016-04-18 04:56:55

标签: php wordpress curl yii2

我正在从YII2开始使用WordPress自动登录以下是我的代码。

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.'"}';
    }

此函数每次在加载wordpress网站时调用。但第一次它没有登录到网站。

如果我使用wp_redirect( esc_url( home_url() ) );登录功能正常,但使用重定向后wp-admin无法正常工作。

1 个答案:

答案 0 :(得分:4)

我找到了解决方案。 下面是autologin()函数中的functions.php中的Changed Code

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;
        }

如果用户没有登录该时间登录并重定向该页面。 :)