I use form to send POST request to a page and to login user with wp_signon() in order to authenticate user to my wordpress installation as described in WP documentation:
$creds = array();
$creds['user_login'] = $_POST["user-login"];
$creds['user_password'] = $_POST["user-password"];
$creds['remember'] = true;
$user = wp_signon( $creds, false );
After this little piece of code I'm checking if user was logged in:
if ( is_user_logged_in() ) { echo "SUCCESS"; } else { echo "FAIL!"; }
But I got FAIL! all the time. Then after sniffing around I found this little trick:
wp_set_current_user( $user );
if ( is_user_logged_in() ) { echo "SUCCESS"; } else { echo "FAIL!"; }
I've got SUCCESS on this one but when I leave this page I got FAIL again and again.
Can anyone explain me how to login user with wp_signon() without logging her out after page is changed or reloaded or whatever.
I've got desirable result when I go to /wp_admin and login with WP's default login form. I can navigate through every page of my WP site remaining logged-in all the time. But when I try to do this outside the default form with wp_signon(); I FAIL!.
Maybe I use it wrong? Guide me! PLEASE!
It was my mistake. I used the whole structure on my localhost server which for some reason didn't allow wordpress to work correctly. After I've uploaded the template into an external server I've got this working.
Sorry for bothering! It won't happen again ...
Related
I am trying to log in a wordpress user on my test site only by the user ID.
My goal is to send out an email to remind them to review a product they recently purchased, and via the email link I want to auto log them in and take them to the review form.
Then when the review is submitted, it's marked off as a 'verified buyer'
I made this user class and login test script to see if I could get it to work following the other documentation I found...
class UserAPI {
private $_id = 0;
private $_wpUser;
public function __construct(int $userID) {
$this->_id = $userID;
$this->_wpUser = get_user_by('id', $this->_id);
}
/*
* Log the user in
*/
public function login() {
wp_clear_auth_cookie();
wp_set_current_user( $this->_id, $this->_wpUser->user_login );
wp_set_auth_cookie( $this->_id, true );
do_action( 'wp_login', $this->_wpUser->user_login, $this->_wpUser );
$currentUser = wp_get_current_user();
if ( is_user_logged_in() ){
echo 'logged in: ' . $currentUser->user_login;
}
else { echo 'not logged in'; }
}
}
// Login test
require('../../includes/userAPI.php');
require('../../../../../wp-load.php');
$userID = 1118; // random user in DB
$userAPI = new \mynamespace\UserAPI($userID);
// Log in user
$userAPI->login();
The output from login() shows the current user is the person I chose as a test from the existing db.
However if I load the wordpress site after I have done this - the user is NOT logged in.
I even confirmed with this...
add_action('init', function() {
$currentUser = wp_get_current_user();
if ( is_user_logged_in() ){
echo 'logged in: ' . $currentUser->user_login;
}
else { echo 'not logged in'; }
});
When I load the site, the test code shows "not logged in"
So I have the login by id test script open in one browser, and the wordpress home page in the other tab.
How can I fix this so that when I run the login script, then go to the wordpress home page tab and refresh it - the login is remember and the site loads with the user logged in?
Thank you
The problem was a url missmatch when working with xampp locally
sometimes the browser or xampp would change my explict call to
http://127.0.0.1/devsite/
to...
http://localhost/devsite/
I imagine that was screwing up login cookies.
How can i this? You cannot access the site without a member, but google bot can enter. How can I do this? You cannot access the site without a member, but Google bot can enter. I tried to create a variable and exclude the IP number, but I failed.
It would be best to test by using reverse DNS lookup since User Agent can be spoofed. PHP makes it pretty easy, here's a sample test:
// $ip = $_SERVER['REMOTE_ADDR']; // Use to check the visitor IP
$ip = '66.249.66.1'; // Sample Google IP from their docs
$host_name = gethostbyaddr($ip);
$is_google = strpos($host_name, 'google') !== false ? 'is' : 'is <b>NOT</b>';
echo "<p>$host_name</p>";
echo "<p>IP Address $is_google Google</p>";
Now we can check if the user is logged in and if they are not a google bot. Using the WordPress template_redirect hook is recommended. Add this to your functions.php theme file:
/**
* Redirect the user to login if they are not logged in and not a google bot
*/
function redirect_not_logged_in_not_google() {
$host_name = gethostbyaddr($_SERVER['REMOTE_ADDR']);
if( strpos($host_name, 'google') === false && !is_user_logged_in() ) {
wp_redirect( home_url( '/login/' ) );
die;
}
}
add_action( 'template_redirect', 'redirect_not_logged_in_not_google' );
I've read couple of previous post here but none of them is working in my case.. Basically, my blogging site is installed in a sub-directory of main website.. Main website in plain php and sub-directory is wordpress.. I allow users to read my blogs only after logged in. So, the thing is I frequently share the blog links in facebook where lots of new users come in from the link.
Main website is installed in => example.com
wordpress sub-directory in => example.com/blog
As I'm using the custom template login page (login.php), whenever the non-logged in users comes- first they are redirected to example.com/blog/login. I'm using this function to redirect to login page:
function redirect_user() {
if ( ! is_user_logged_in() && !is_page( 'login' ) ) {
$return_url = esc_url('http://www.example.com/blog/login');
wp_redirect( $return_url );
exit;
}
}
add_action( 'template_redirect', 'redirect_user' );
It redirect fine, without problem.. Then the main task of redirecting to the referrer url, I'm using the similar code above to direct to every logged in users to the referring url irrespective or post or page.. Again in the functions.php
if(is_user_logged_in())
wp_redirect('' . $_SERVER["REQUEST_URI"]);
I thought they would work but can't seems to understand that referring url is appending the sub-directory name... For example; the above code show result as:
example.com/blog/blog/blabla-blahblah.. You see the directory name is doubling..
Anyone's advice would be highly appreciated..
Having your WordPress website in a subdirectory will have no impact on what you are trying to do. Why? Because WordPress knows where it's located at, as you set the home and site URLs either in your wp-config.php file like this:
define('WP_HOME','http://example.com/blog');
define('WP_SITEURL','http://example.com/blog');
or by setting both in the Settings > General admin page:
Therefore, all of the rewrites and URLs will be relative to these URLs.
Handling the Referer Capture
When someone comes to one of the pages on your site, you want to capture that original request and add it as a redirect_to= query arg. Then you can send them to the login page.
add_action( 'wp', 'redirect_to_login_if_unauthorized', 3 );
/**
* Redirect the user to the login, but capture the original
* referer and add to the query arg.
*
* #since 1.0.0
*
* #param WP $wp_environment Current WordPress environment instance (passed by reference).
*
* #return void
*/
function redirect_to_login_if_unauthorized( WP $wp_environment ) {
if ( is_user_logged_in() ) {
return;
}
if ( $wp_environment->request ) {
$request = home_url( add_query_arg( array(), $wp_environment->request ) );
} else {
$request = home_url();
}
$redirect = home_url() . '/wp-login.php?redirect_to=' . $request;
wp_redirect( $redirect );
die();
}
How it Works
The event wp fires in wp-includes/class-wp.php. It passes the object instance of the WordPress environment setup. Here is the code from WordPress Core:
do_action_ref_array( 'wp', array( &$this ) );
This environment object has a property that we want called request. That property has the URL request (minus the blog's home URL).
If the $wp_environment->request has a value, we'll add it to the home URL as a query arg; else, we just want the home URL. Now we have the referer.
Next, you create the redirect URL, which has the path to the login page and the redirect_to query arg.
An Example
Let's say you have a post called Why I Love WordPress and the path to that post is http://example.com/blog/why-i-love-wordpress.
The value in the $request would be:
http://example.com/blog/why-i-love-wordpress
and the redirect URL would be:
http://example.com/blog/wp-login.php?redirect_to=http://example.com/why-i-love-wordpress
Upon logging in, the user is then redirected to the original page request.
Tip - Handle Logout Too
You'll want to think about the pathing after a user logs out and then build a proper request to it too.
I have so far integrated a multisite wordpress that uses 4 main subdomain templates in a single wordpress installation: college.mysite.com | jobs.mysite.com | advisors.mysite.com | answers.mysite.com
A wp user is only required to login once and they inmediately have acccess to any wp template.
However, What I would like to achieve is a bit more complicated than that. I don't want new users and existing members to use wordpress as their main user interface to access private content.
In fact I have disabled registration and hidden wp login altogether.
I would like a more secure and less public signup/login.
For this occassion I would like wordpress to ignore the default login credentials and use instead custom db table names and hashmethod pulled from the same wordpress database.
For instance I have a yii platform called: humhub.
For a user to use wordpress they would need to login through humhub and have wp read the db table names:
user instead of wp_users
a secondary db name would need to be read for the password because humhub uses:
user_password instead of the default value within wp_users (user_pass)
I've tried integrating yii framework with wordpress, I've tried tweaking here and about within the yii framework so that it reads two databases separately but it's far more complicated than simply redirecting the wp login credentials by changing the default login table names within the wordpress files,
please help me,
Let's assume you have some unique identifier so that one user will not accidentally collide with another (in YII/HumHub)
You can load up the WordPress API via
require_once("/path/to/wp-load.php");
//Found normally in the WordPress root directory alongside wp-config.php
You can then when creating a new user in HumHub do:
wp_create_user( $username, $password, $email );
//Where username is the unique identifier
//password is ideally a random hash
//email is their email if relevant
And then log them in (assuming you remembered the username and password!!)
$creds = array();
$creds['user_login'] = $username;
$creds['user_password'] = $password;
$creds['remember'] = true;
$user = wp_signon( $creds, false );
if ( !is_wp_error($user) ) {
ob_start(); //flush buffers - otherwise login won't work or user gets redirected to dashboard
$user_id = $user->ID;
wp_set_current_user( $user_id, null );
wp_set_auth_cookie( $user_id,true );
do_action( 'wp_login', $username );
ob_end_clean();
} else {
//Handle the login error
}
They are then logged into WordPress with cookies etc without any headers interfering with HumHub
Note - the above method may not work is there is a name conflict between WordPress and YII/HumHub. You will get a php error with details of the conflict if that is the case and will have to try something else (such as Oauth plugin)
Lately I've started seeing a lot of users on my website and the usernames/emails seem like spam. I do have captcha as well. What is going on?
kathleenfentonzry tiotelisco1977+fenton8995#outlook.com<br>
kristofertroywtq selfraledig1988+troy7366#outlook.com<br>
mindyrichifnngaeeqe bosspesepe1985+rich1855#outlook.com<br>
Please let me know if I can somehow prevent this.
Thanks
function custom_url_rewrite_outbound(&$path, &$options, $original_path) {
if (preg_match('|^admin(?![^/])(.*)|', $path, $matches)) {
$path = 'user'. $matches[1];
}
}
function custom_url_rewrite_inbound(&$result, $path, $path_language) {
if (preg_match('|^backend(?![^/])(.*)|', $path, $matches)) {
$result = 'member'. $matches[1];
}
if (preg_match('|^admin(?![^/])(.*)|', $path, $matches)) {
$result = '404'. $matches[1];
}
}
Include the above code in your settings.php file. This will replace the paths on your site that contain "user" with "member". This prevented the spam for me.
I use a module called Spambot (https://drupal.org/project/spambot) to prevent spam user registrations on my D6 site. It checks all new user registrations against the spam database at http://www.stopforumspam.com based on IP, Username, and Email. This has stopped 99.9% of the spam registrations I used to get.
We have sites that have the same issue where the captcha is getting beaten. I use Access rules to block certain email addresses that I assume are spam accounts. If that doesn't help the next thing we are using is Mollom to block to spam content. Mollom won't help with spam accounts but it will stop the site from being flooded with spam.
Add re-captcha on registration page!