Wordpress自动登录链接仅在单击两次或重新加载时有效



我有一个Wordpress网站,我设置了一个自动登录的PHP脚本,该脚本检查URL中对应于表中用户的KEY值,然后将该用户登录到该网站。我之所以这样做,是因为我有一个用户要求只需点击一个链接就可以登录网站,而不必每次都输入用户名和密码。

我已经让它发挥了作用,奇怪的是,尽管它只在某些时候起作用。当用户单击链接时,它会将用户带到该用户的登录页。

自动登录链接如下所示:https://mywebsite.org/home/autologin.php?key=54321

有时,当点击链接时,它只是位于该url,其他时候,它会正确登录并重定向到登录页url,即:https://mywebsite.org/library-portal-landing-page/

当链接只是暂停并位于自动登录URL上时,如果自动登录链接被重新加载,页面将重定向和加载,我不确定为什么有时需要重新加载,而其他时候它只是起作用。

这是我的autologin.php php脚本:

<?php
require_once("wp-load.php");
global $wpdb;
// Check if user is already logged in, redirect to account if true
if (!is_user_logged_in()) {
// Check if the key is set and not emtpy
if(isset($_GET['key']) && !empty($_GET['key'])){
// Sanitize the received key to prevent SQL Injections
$received_key = sanitize_text_field($_GET['key']);

// Find the username from the database using the received key
$get_username = $wpdb->get_var($wpdb->prepare("SELECT avatar FROM wp_autologin WHERE random_key = %s", $received_key ) );

// Check if query returned a result, throw an error if false
if(!empty($get_username)){

// Get user info from username then save it to a variable
$user = get_user_by('login', $get_username );

// Get the user id then set the login cookies to the browser
wp_set_auth_cookie($user->ID);

// To make sure that the login cookies are already set, we double check.
foreach($_COOKIE as $name => $value) {

// Find the cookie with prefix starting with "wordpress_logged_in_"
if(substr($name, 0, strlen('wordpress_logged_in_')) == 'wordpress_logged_in_') {

// Redirect to account page if the login cookie is already set.
wp_redirect( home_url('/library-portal-landing-page/') );

} else {

// If NOT set, we loop the URL until login cookie gets set to the browser
wp_redirect( home_url('/home/autologin/?key=' . $received_key) );

}
}

} else {
echo 'Invalid Authentication Key';
}
} else {
wp_redirect( home_url() );
}
} else {
wp_redirect( home_url('/library-portal-landing-page/') );
exit;
}
?>

我在几秒钟后添加了一个javascript重定向来运行,这就成功了,我在PHP文件结束后添加了这个:

<script>
setTimeout(function () {
window.location.href = "https://mywebsite.org/library-portal-landing-page/";
}, 2000);
</script>

最新更新