问题描述
我有一个WordPress网站,我已经设置了一个自动登录PHP脚本,该脚本检查URL中与表中用户相对应的KEY值,然后将该用户登录到该网站中。之所以这样,是因为我有一个用户要求通过单击链接即可登录该站点,而不必每次都输入用户名和密码。
我已经开始使用它了,奇怪的是尽管它只在某些时候起作用。用户单击链接后,会将他们带到该用户的登录页面。
自动登录链接如下所示:https://mywebsite.org/home/autologin.php?key=54321
有时,单击链接时,它只是位于该URL,而有时它会正确登录并重定向到登录页面URL,即https://mywebsite.org/library-portal-landing-page/
当链接停滞并位于自动登录URL上时,如果重新加载自动登录链接,则页面将重定向并加载,我不确定为什么有时需要重新加载它,而其他时候它仍然可以正常工作。
<?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,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>