很多用wordpress做站的朋友,都会遇到有人尝试破解后台登录,又得小伙伴还开了登录邮件提醒。不得不说对网站,对服务器的压力肯定会有影响的,主题笔记也一直在寻找相关的解决办法。前段时间沐风除了一款后台扫码登录,但是需要配合相应的APP,且只有IOS版本。今天为大家带来最实用的解决办法,wordpress后台邮箱授权登录。
<?php
/*强制性跳转代码,访问/wp-admin 即可跳转*/
//function redirect_logged_user() {
// if(is_user_logged_in() && (empty($_GET['action']) || $_GET['action'] == 'login'|| $_GET['action'] == 'register')) {
// wp_redirect( home_url() );
// exit;
// }elseif(empty($_GET['action']) || $_GET['action'] == 'login'|| $_GET['action'] == 'register'){
// wp_redirect( get_template_directory_uri().'/mail-login.php' );
// exit;
// }
//}
//add_action( 'login_init', 'redirect_logged_user' );
/*不强制性跳转,在后台登录框右下角显示按钮,点击跳转*/
add_action('login_footer','mail_login_link');
function mail_login_link() {
echo '<p style="width: 30px; margin: auto; padding-top: 10px;"><a class="button" style="color: #999; margin-left: 24px;" href="'.get_template_directory_uri().'/mail-login.php">通过邮件验证身份登录</a></p>';
}
/*以下代码不用改动*/
function mail_login_access_check($hash){
$email = generrate_access_token($hash,$operation='DECODE');
if ($email != '') login_required($email);
wp_die('认证失败!', 'Authorization Not Allowed | '.get_option('blogname'), array('response' => '403'));
}
function login_required($user_email){
if (is_user_logged_in()) return;
if ($user = get_user_by('email',$user_email)) {
wp_set_current_user($user->ID);
wp_set_auth_cookie($user->ID);
do_action('wp_login', $user->user_login);
$redirect_to=home_url();
wp_safe_redirect($redirect_to);
exit();
}
}
function send_mail_login_token($email){
if (get_user_by('email',$email)) {
$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
$wp_email = 'no-reply@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME']));
$subject = '[' . $blogname . '] 后台登录授权申请';
$message = '如果您确定该申请,请点击链接授权:';
$message .= mail_login_access_link($email);
$headers[] = 'From: "'.$blogname.'" <'.$wp_email.">";
$headers[] = 'Content-Type: text/plain; charset="UTF-8"';
wp_mail( $email, $subject, $message, $headers );
wp_die('授权信息已发送到邮箱,请到邮箱点击登录!', '后台登录授权申请 | '.get_option('blogname'), array('response' => '200'));
}
wp_die('邮箱错误或拒绝访问!', '后台登录授权申请 | '.get_option('blogname'), array('response' => '403'));
}
function mail_login_access_link($email){
$authkey=generrate_access_token($email,$operation='ENCODE');
return get_template_directory_uri().'/mail-login.php?hash='.$authkey;
}
function generrate_access_token($string, $operation = 'ENCODE', $key = 'Mail-Login-Key', $expiry = 600) {
$hash = substr(md5(time().$string.rand()),8,16);
if($operation == 'DECODE') {
if($result = get_transient($key.'_'.$string)){
delete_transient($key.'_'.$string);
return $result;
}else{
return '';
}
} else {
set_transient($key.'_'.$hash, $string, $expiry);
return $hash;
}
}
?>
上面代码引用在functions.php中,前端文件mail-login.php在文章结尾处下载,下载后放在主题目录。
文件下载

