我正在从YI2进行WordPress自动登录。下面是我的代码。
函数.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:(YI2)
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无法工作。
我找到了解决方案。下面是autologin()函数中functions.php中的更改代码
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;
}
如果用户当时没有登录,请登录并重定向页面。:)