Make website login work on WordPress too

I developed a website using PHP and MySQL, which already has a login and registration form. (myweb.com)

I've added wordpress to it at this url myweb.com/blog

I want to disable the login and registration page on WordPress and force users to use mine. Basically integrate my login with WordPress so that user will be logged in on both sites.

My site members table looks like this. And all registered users are stored here. And passwords in my DB are hashed using md5()

id | name | email | password

and WordPress structure is like this and is currently empty

ID | user_login | user_pass | user_nicename | user_email | user_url | user_registered | user_activation_key | user_status | display_name

I tried following the steps mentioned here

but I get this error on line 254 var_dump($user);

    object(WP_Error)#620 (2) {
  ["errors"]=>
  array(1) {
    ["invalid_username"]=>
    array(1) {
      [0]=>
      string(166) "<strong>ERROR</strong>: Invalid username. <a href="http://localhost/dev/blog/wp-login.php?action=lostpassword" title="Password Lost and Found">Lost your password</a>?"
    }
  }
  ["error_data"]=>
  array(0) {
  }
}

Also, all user info is stored in my members table on my site not in WordPress's db.

Here is my login code for my site, which I recently added the WordPress login to it too.

/*
 *  Login
 *
 *  $email = email of user
 *  $pass = user password (must already be in md5 form)
 *  $url = url of page they are login from
 */
function login($email = '', $pass = '', $url = '', $sticky = false)
{
        global $lang, $_db, $mod, $template_style;

        // Replace nasty things to stop sql injection
        $email = addslashes(strtolower($email));
        $email = strip_tags($email);
        $email = htmlspecialchars($email, ENT_QUOTES);

        //get user id
    $sql = "SELECT `id`, `name`, `username`
                FROM `members`
                WHERE `email`='".mysql_real_escape_string($email)."'
                AND `pass` = '" . mysql_real_escape_string($pass) . "'
                LIMIT 0,1";

        $q = $_db->query($sql);
        list($uid, $name, $username) = $_db->fetch_array($q);

        $login_check = $_db->num_rows($q);

        if ($login_check <= '0')  //check if login matches
        {
                  echo '0'; //login failed
                  die;
        }

        /*
         * wordpress login
         * 
         * read:
         * http://codex.wordpress.org/Function_Reference/wp_update_user
         */ 
         $credentials = array();
         $credentials['user_email'] = $email;
         $credentials['user_password'] = $pass;
         $credentials['remember'] = $sticky; // true/false
         $secure_cookie = false; // true / false

         $user = wp_authenticate($credentials['user_email'], $credentials['user_password']);

    if ( is_wp_error($user) ) {
        if ( $user->get_error_codes() == array('empty_email', 'empty_password') ) {
            //$user = new WP_Error('', '');
            $user = wp_update_user(array ( 'user_login' => $name, 'user_email' => $email, 'user_pass' => $pass ));
        }
    }

        var_dump($user);

        wp_set_auth_cookie($user->ID, $credentials['remember'], $secure_cookie);
        do_action('wp_login', $user->user_login, $user);

        /*
            set login cookies
        */
        set_login_cookie($uid, $pass, $sticky);

        //lock check
        lock_checker($uid);

        update_thisuser_online();           
}

Do I have to copy everything from my members table and populate it into wp_users or is there a way to login into wordpress without having duplicate data in 2 different tables? I don't want to have 2 logins and 2 registration forms on both sites.

Why won't wp_authenticate() in my code above authenticate?

Answers


You can set the wordpress login to use a custom table by editing the config.php and adding these two lines:

define('CUSTOM_USER_TABLE','new_user_table'); //login, pass, email etc
define('CUSTOM_USER_META_TABLE', 'new_usermeta_table'); //optional bio, don't have to include this line

Where new_user_table is your website's table and new_usermeta_table is your website's bio table (if you want one)

The custom table needs to have the same structure as a normal wordpress table. So, to get this working with your existing website's table you'll have to add some fields and make sure the password is hashed the same way.

Here is how to structure the user table

Here is how to structure the user meta table

To hash the passwords correctly at registration, include the file wp-includes/pluggable.php and use the function <?php $hash = wp_hash_password( $password ) ?>

For existing passwords that are not hashed correctly, you'll have to set up an email password reset.

Or. if you'd like to retain your current password hashes (not recommended for security reasons but doable) you can change the wordpress hashing function. In wp-includes/pluggable.php change:

if ( !function_exists('wp_hash_password') ){
    function wp_hash_password($password) {
                //apply your own hashing structure here
            return $password;
    }
}

And change:

if ( !function_exists('wp_check_password') ){
    function wp_check_password($password, $hash, $user_id = '') {
            //check for your hash match
            return apply_filters('check_password', $check, $password, $hash, $user_id);
            }
}

For details on wp_check_password Go Here

Alternatively

You can skip messing around with your custom user table and have the wordpress login apply to the rest of your site. To do this, simple use the following code:

<?php
include 'wp-config.php';
if ( is_user_logged_in() ) {
    echo 'Welcome, registered user!';
} else {
    header( 'Location: http://google.com' ) ;
};
?>

Make sure that 'wp-config.php' is the full relative path to the file, then place this code in every page on your non wordpress site. replace the echo with whatever content is to be displayed for a logged in user, and replace the header with whatever is to be displayed for a guest. If the content is simple html you can do the following:

<?php
include 'wp-config.php';
if ( is_user_logged_in() ) {
?>

<html>
<head></head>
<body><p>Welcome Registered user</p></body>
</html>

<?php
} else {
?>

<html>
<head></head>
<body><p>Please log in</p></body>
</html>

<?php
};
?>

Try changing the options in your wp-config.php file to point to your members database; it's probably a good idea to create a separate user/password with MySQL and grant it privileges to your members DB. There a number of useful options you're able to set/change with that file. I suggest you read the documentation on it for some more in-depth stuff. If you do decide to try the above-mentioned approach, make sure to also change the $table-prefix line to match your existing DB.

Also, see if this blog post is of any help, as it deals with external authentication directly. There's a php script available which you can copy/paste or otherwise adjust to your particular needs. Pay particular attention to the include_once("../wp-config.php"); and include_once("../wp-includes/class-phpass.php"); lines.


I've managed to do that a while ago by using a function from the Wordpress API.

wp_set_auth_cookie( $wordpress_user_id, $remember, false );

$wordpress_user_id is the ID of the user in the Wordpress table.

$remember is a Boolean variable indicating whether Wordpress should create a persisting cookie "remembering" the user between sessions.

I don't remember the third one, but you could Google it easily.


P.S. To have the wp_set_auth_cookie function available you need to include/require some Wordpress files before you use it. Try with the wp-load.php file.


Need Your Help

Get all the table items from DynamoDB table using Java High Level API

java amazon-web-services amazon-dynamodb

I implemented scan operation using in dynamodb table using dynamodbmapper, but I'm not getting all the results. Scan returns different number of items, whenever I run my program.

URL to URI encoding changes a "%3D" to "%253D"

java url encoding uri

I'm having trouble encoding a URL to a URI: