2

I am using Screets Wordpress Sessions plugin and it works really well. The problem I am having is this, I am going to manage my site users out of wordpress through a different table and etc. I have my signup form working, were it sends out confirmation emails to stop spam. The issue I am having is that my simple form:

 mysql_connect("localhost", "%username%", "%password%") or die(mysql_error()); // Connect to database server(localhost) with username and password.
    mysql_select_db("%database%") or die(mysql_error()); // Select registration database.
    if(isset($_POST['name']) && !empty($_POST['name']) AND isset($_POST['password']) && !empty($_POST['password']) AND isset($_POST['name']) && !empty($_POST['name'])){
                $username = mysql_escape_string($_POST['name']);
                $password = mysql_escape_string(md5($_POST['password']));

                $search = mysql_query("SELECT username, password, active FROM %table% WHERE username='".$username."' AND password='".$password."' AND active='1'") or die(mysql_error()); 
                $match  = mysql_num_rows($search);

                if($match = 1){
                    $msg = 'Login Complete! Thanks';
                    //$email = $row['EmailAddress'];  
                    //;  
                    //$_SESSION['EmailAddress'] = $email;  
                    //$_SESSION['LoggedIn'] = 1; 
                    $session->set_userdata( 'username', $username);
                    header ("Location: /"); 
                }else{
                    $msg = 'Login Failed!<br /> Please make sure that you enter the correct details and that you have activated your account.';
                }
            }


        ?>
        <!-- stop PHP Code -->

        <!-- title and description -->  
        <h2>Login Form</h2>
        <p>Please enter your name and password to login</p>

        <?php 
            if(isset($msg)){ // Check if $msg is not empty
                echo '<div class="statusmsg">'.$msg.'</div>'; // Display our message and add a div around it with the class statusmsg
            } ?>

        <!-- start sign up form --> 
        <form action="" method="post">
            <label for="name">Username:</label>
            <input type="text" name="name" value="" />
            <label for="password">Password:</label>
            <input type="password" name="password" value="" />

            <input type="submit" class="submit_button" value="login" />
        </form>

auto redirects to my wordpress login which is not what I want. I have been told before to use wp_users but I really don't want to use that or a plugin. Any ideas to get it to work the way I need to?

EDIT: To better clarify the question, anyone who clicks submit is redirected to wp-login.php. The page is not even following my SQL connect to check and actually create a session. Any ideas?

6
  • Why not manage users with WordPress's built in user system? It may simplify things for you a great deal. Nov 16, 2012 at 5:14
  • I don't want to have to deal with re-directing users from the WP backend, I need new fields upon registration, don't want to clutter the WP user section with both admin, editors etc + site users. I am integrating a mailing server with my registration page with double opt-in. I know alot of these things can also be added with plugins, but I don't want to have 30 plugins to do something I can type manually.
    – shayward
    Nov 16, 2012 at 5:19
  • 1
    You could actually use WordPress to manage user authentication and meta ( even adding whatever extra fields you'd like ) without having them go through the WP backend. I can see your point about not wanting to clutter up the user backend, but I find the built in filters ( filter by admin, contributor, author, editor, subscriber ) to be negate this issue. Ultimately, it's up to you which method you use. :) Nov 16, 2012 at 5:33
  • Also, where is this code located? Nov 16, 2012 at 5:40
  • I created it, its located on a page called login. So its mysite.com/login. I changed my wp-login page to be something else. I understand how people prefer to use the WP version of user management; but again I do not want to use it.
    – shayward
    Nov 16, 2012 at 5:44

2 Answers 2

1

The better way is using Ajax to send and sava your data. First, include these codes below into your functions.php:

/**
* User Log in
*/
function sc_login( $params ){   
    global $wpdb;

    // You can check user here
    $sql = $wpdb->prepare( 
        '
            SELECT COUNT(*) FROM ' . $wpdb->prefix . ' users
            WHERE `email`  = %d
            AND `password` = %s
        ',
            $params['user_login'], $params['user_password']
    );
    $auth = $wpdb->get_var( $sql );

    if( $auth ) {
        // Log in system
    } else {
        // Username or password is wrong
    }
}
/**
* Ajax Submit
*/
function sc_ajax_callback() {

    // run function
    $response = call_user_func($_POST['func'], $_POST);

    // response output
    header( "Content-Type: application/json" );
    echo json_encode($response);
    exit;
}

// Ajax Requests
add_action( 'wp_ajax_nopriv_sc_ajax_callback', 'sc_ajax_callback' );
add_action( 'wp_ajax_sc_ajax_callback', 'sc_ajax_callback' );

Create an Ajax.js file into your theme and add these codes:

(function ( $ ) { 
    jQuery(document).ready(function() {
        /**
        * Log in
        */
        $('#sc_login_form').submit(function() {

            jQuery.ajax({
                type: 'POST',
                url: sc_ajax.ajaxurl,
                data: $('#sc_login_form').serialize(),
                dataType: 'json',
                success: function(response, textStatus) {

                    // Show errors?
                    if( response.errors ){
                       // YOU CAN SHOW ERRORS HERE IF YOU WANT
                       // for instance, "Email is required!"

                    // successful log in
                    } else {
                       // refresh page (HERE IS THE POINT)
                       window.location.href = sc_ajax.REDIRECT_URL;
                   }

                    console.log(response);

                }
             });

            return false;

       });

   }); 
}( jQuery ));

Now we need to localize Ajax script. Open header.php and add these codes before wp_head(); function. Don't forget to change REDIRECT_URL variable below:

// insert jquery
wp_enqueue_script( 'jquery' );

// ajax requests
wp_enqueue_script( 'sc-ajax-request', get_template_directory_uri() . '/Ajax.js', array( 'jquery' ) );

// prepare your ajax custom vars
$ajax_vars = array(
    'REDIRECT_URL'  => '', // (!) CHANGE THIS WITH URL WHERE YOU WANT TO GO
    'ajaxurl'   => admin_url( 'admin-ajax.php' )
);

wp_localize_script( 'sc-ajax-request', 'sc_ajax', $ajax_vars );

And last step is edit your form like this:

<form id="sc_login_form">
    <input type="hidden" name="action" value="sc_ajax_callback" />
    <input type="hidden" name="func" value="sc_login" />

    Email:
    <input type="text" name="user_login" />

    Password:
    <input type="password" name="user_password"/>

    <input type="submit" value="Log in" />
</form>

I hope this helps.

3
  • Hey dino, I am a bit confused when is it ever making a call to the database? It looks like its doing something as I see the user name and password being passed in the address but never see it going into the database
    – shayward
    Nov 18, 2012 at 6:07
  • Just look at sc_login() function. I passed params for you and it is ready to call the database. I edited that function for you and include an example how to use it ;) Nov 18, 2012 at 12:51
  • 1
    Finally figured it out. Thanks Dino, I also got some help from the people at screets. I was having issues because in my functions.php i have a redirect if user is not a admin and it was giving this function some issues. All is good now!
    – shayward
    Nov 19, 2012 at 22:14
0

Ah yes. WordPress's Rewrite API is stepping on you. When you submit your form, the script attempts to post back to itself. WordPress takes http://your-site.com/login and rewrites it to http://your-site.com/wp-login.php.

Here's how to fix it.

Create a page in WordPress, name it login, then assign the custom page template to it you'll create in this next step.

Now you'll need to create a custom page template, place it in your currently active theme folder, and put the following code in it:

<?php

/*
 * Template Name: Login
 */

// Put the code for your login here.

?>

Finally, add this next line to your theme's functions.php:

add_rewrite_rule( '^login/?$', 'index.php?page_name=$matches[1]', 'top' );

That should do the trick nicely. :)

3
  • Thanks, but not sure if that is the answer to the problem I am having. The login page runs fine, its just the action of "submiting" on the form is when the page in turn redirects to wp-login.php. On the forum action="" is blank not sure why its redirecting the page after submiting the form.
    – shayward
    Nov 16, 2012 at 7:28
  • When action="" on a form, the form submits to the script it resides in. So, basically the page just calls itself again. I believe that may be where the trouble lies. WordPress rewrite is destroying your intentions of submitting to yourself. Although, this does beg the question of how you're getting to the page to begin with. Nov 21, 2012 at 22:28
  • On a fresh install of WordPress 3.4.2, navigating to a page at http://your-site.com/login will redirect you to http://your-site.com/wp-login.php. I'm fairly certain this is your issue. If you would like to prove ( or disprove ) this, rename the page from login to something unrelated like shiny-disco-ball. Nov 21, 2012 at 22:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.