Prashant Patil Prashant Patil - 6 months ago 92
PHP Question

WP Auto Login From Yii2 using Curl not working on First Load

I'm Working on WordPress auto login 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 call every time on load wordpress site. but first time it not loging in to site.

If I use
wp_redirect( esc_url( home_url() ) );
the login functionality working fine but wp-admin not working after using redirect.

Answer

I found solution. Below is Changed Code in functions.php in 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 user not login that time login and redirect the page. :)