automatic login to wordpress dashboard from anothe

2019-03-11 20:20发布

问题:

I want to log in automatically to WP admin/dashboard from another site without going thru the login process.. I've tried the following but with no luck:

<?php

$username="admin";
$password="mypasw";
$url="http://example.com/";
$cookie="cookie.txt";

$postdata = "log=". $username ."&pwd=". $password ."&wp-submit=Log%20In&redirect_to=". $url ."wp-admin/&testcookie=1";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url . "wp-login.php");
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
curl_setopt ($ch, CURLOPT_TIMEOUT, 60);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt ($ch, CURLOPT_REFERER, $url . "wp-admin/");
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt ($ch, CURLOPT_POST, 1);
$result = curl_exec ($ch);
curl_close($ch);
echo $result;
exit;


?>

It's kind of like only showing me the dashboard page but I'm not really logged in since clicking on any buttons on the admin page is only redirecting to same page which is the site page.. :(

回答1:

If you have access to the files of the website where you trying to login. You could add a auto login php script and $_POST the username and password to this script, example:

if ($_POST) {

    $errors = array();

    $username = esc_sql($_REQUEST['username']);
    $password = esc_sql($_REQUEST['password']);
    $remember = esc_sql($_REQUEST['rememberme']);
    $remember = ($remember) ? "true" : "false";

    $login_data = array();
    $login_data['user_login'] = $username;
    $login_data['user_password'] = $password;
    $login_data['remember'] = $remember;
    $user_verify = wp_signon($login_data, true);

    if (is_wp_error($user_verify)) {
        $errors[] = 'Invalid username or password. Please try again!';
    } else {
        wp_set_auth_cookie($user_verify->ID);
        wp_redirect(admin_url());
        exit;
    }

}

Wordpress codex references:

  • Login function: http://codex.wordpress.org/Function_Reference/wp_signon
  • Set cookie for admin login http://codex.wordpress.org/Function_Reference/wp_set_auth_cookie
  • Get the admin page url: http://codex.wordpress.org/Function_Reference/admin_url

Hope it helps.

Edit: $wpdb->escape is deprecated since Wordpress version 3.6, use wpdb::prepare() or esc_sql() instead! I've changed the code to use esc_sql().

  • esc_sql(): http://codex.wordpress.org/Function_Reference/esc_sql