redirect user if not logged in - wordpress

I am using customized pages on my site where I need to check that the user is logged in, and if not, redirect to another page.
On successful login, a session variable is set up as:
session_start();
$_SESSION['login'] = "1";
To check whether the user is logged in or not on a page, I use this code at the start of the page:
session_start();
if($_SESSION['login']=='')
{
#header("location:login.php");
}
However the page does not redirect even if the user is not logged in. The error shown is
Notice: Undefined index: login in XXXX/XXXX/XXXX/XXXX
Is there any other method to redirect users other than header(), or maybe some other code can be used to achieve the same purpose?

It appears the login index of $_SESSION is not set at the time you're checking it, most probably the $_SESSION['login'] = "1"; bit comes after your check, so you are going to have to make sure you verify whether it's set or not using the array_key_exists function as follows:
if (array_key_exists('login', $_SESSION) && $_SESSION['login']=='') {
#header("location:login.php");
}
Alternatively you may want to set explicitly $_SESSION['login'] = 0, for example, by default, and only set $_SESSION['login'] = "1"; if login is successful.
At the same time, I do not recommend you to use your own login mechanism, instead use scripts and techniques originally designed by knowledgeable coders of wordpress, and well tested by the community. One such approach is described in this question on the wordpress support site (add this to your theme's functions.php):
add_action( 'init', 'redirect_visitors' );
function redirect_visitors() {
if ( ! is_user_logged_in() ) {
wp_redirect( 'http://your-site.com/wp-login.php' );
exit;
}
}

Related

Wordpress - Form to match registered users

I need to create a form on wordpress for registered users.
Users don't have to reach backend but they land on a page with just a form where they write their email and submit.
If the mail matches with the mail registered as user they'll be redirected to the next page.
If there's no matching mail on user list they just receive an error to try again.
It's for a kind of browser game...
Thanks
For checking whether an email exists or not, you can use the email_exists() function provided by WordPress.
Here's the example:
$email = 'myemail#example.com';
$exists = email_exists( $email );
if ( $exists ) {
echo "That E-mail is registered to user number " . $exists;
} else {
echo "That E-mail doesn't belong to any registered users on this site";
}
You can use it to define your logic.
And for redirection, WordPress has a function called wp_redirect()
Here's an exammple:
wp_redirect( 'http://www.mynewurl.com/blah/' ); exit;
Make sure to call exit just after calling that function.
And if you are having trouble figuring out how to know whether the user is actually a logged in user or not, you can use the is_user_logged_in() function.
Here's an example:
if ( is_user_logged_in() ) {
echo 'Welcome, registered user!';
} else {
echo 'Welcome, guest!';
}
Now you got all the functions needed to complete your task! Just make use of these functions properly based on your logic and you will be able to complete it!

Disable auto login upon registration in Wordpress

[update1] I am using the ClassiCraft theme and I have no idea where to customize the login and register forms
[update2] I know that the registration process does not go through wp_authenticate because I redefined it inside a plugin of mine
I am quite new in the Wordpress world (actually just got my hands on it for the first time yesterday) and I am having some difficulties finishing up a little project I am working on.
The project is rather simple (or so I thought) and consists in adding a confirmation link to email received upon registration in order to validate the email address provided to prevent using fake emails that the registrar does not even own.
I am about all done except that once I hit the register button it leads to log in the freshly created user.
I googled stuff like "wp disable auto login on registration" and whatnot but I have not been able to find anything that worked. I even tested a few plugins supposed to be doing exactly what I need but none of them worked.
Also, I am not using any plugins for the registration/login forms and it appears that the code in the wp-login.php file is actually not even used...
Would anyone have an idea? Thanks
Okay, so without an access to the theme, i can't really answer you.
But i can tell you what I would try.
1. Add action on user_register hook, to add a post meta that will be useful to check if user has confirm his email.
add_action( 'user_register', 'add_has_confirm_email_user_meta');
function add_has_confirm_email_user_meta( $user_id ) {
update_user_meta( $user_id, 'has_confirm_email', 0 );
}
2. Prevent the user from log in automatically after registration.
Here i can't tell you the hook that will works for you. For example, the hook for the wordpress registration is user_register, but if you have woocommerce, the hook I will use, would be woocommerce_registration_redirect. So try to find what hook is available after the registration with your theme.
In all case, the code in the function would be something like :
function custom_registration_redirect() {
// Log out the user
wp_logout();
// The login url could be an other, with woocommerce for example it is : get_permalink(get_option('woocommerce_myaccount_page_id')
$login_url = wp_login_url();
// Redirect on it
wp_redirect( $login_url);
exit;
}
It will also be necessary, to add a message on this page to alert the user, that he will receive an email to confirm his account.
3. Prevent user from login when he submit the log in form
Add action on wp_login hook to achieve that.
add_action('wp_login', 'prevent_user_from_login', 10, 2);
function prevent_user_from_login($user_login, $user = null ) {
if ( !$user ) {
$user = get_user_by('login', $user_login);
}
if ( !$user ) {
// not logged in
return;
}
// Get user meta
$has_confirm_email = get_user_meta( $user->ID, 'has_confirm_email', true );
if ( $has_confirm_email == '0' ) {
// Clear cookies, a.k.a log user out
wp_clear_auth_cookie();
$login_url = wp_login_url();
$login_url = add_query_arg( 'has_confirm_email', '0', $login_url);
wp_redirect( $login_url );
exit;
}
}
4. Add message on log in page if we get the has_confirm_email to 0
add_filter('login_message', 'has_not_confirm_email_login_message');
function has_not_confirm_email_login_message($message) {
if ( isset( $_GET['has_confirm_email'] ) && $_GET['has_confirm_email'] == 0 ) {
$message = '<div id="login_error">You have not confirmed your email.</div>';
}
return $message;
}
5. Send the email with a link to confirm his email.
You will need to generate a token to add to the url.
For the hook to change the default email sent by Wordpress, you can use wp_new_user_notification_email that is available since the 4.9 of Wordpress.
In the function itself you could do something like :
function wp_new_user_notification_email( $wp_new_user_notification_email, $user, $blogname) {
// Generate the token (there is other function available with php 7, but this one works great)
$token = bin2hex(openssl_random_pseudo_bytes(16));
// Add the token to the user
update_user_meta( $user->id, 'confirm_email_token', $token );
// Get your login url
$log_in_url = wp_login_url();
// Add user id and token to the url
$url = add_query_arg(
array(
'token' => $token,
'user_id' => $user->id
),
$log_in_url
);
//
$wp_new_user_notification_email['subject'] = 'Welcome on our website, please confirm your email';
$wp_new_user_notification_email['message'] = 'Blablabla... the url to confirm is: '. $url;
return $wp_new_user_notification_email;
}
6. Hook on the login page to check the $_GET, looking for user_id and token.
Here we check the token and the user. If everything is okay, update the user meta has_confirm_email to 1, so the user can connect, and add a message : "Your email has been confirmed, you can now log in"
add_action( 'login_init', 'custom_login_init');
function custom_login_init(){
if(!empty($_GET['token']) && !empty($_GET['user_id'])) {
if(get_the_author_meta( 'confirm_email_token', $_GET['user_id']) === $_GET['token']) {
// Set the has_confirm_email to 1 so the user can now log in
update_user_meta( $user_id, 'has_confirm_email', 1);
update_user_meta( $user_id, 'confirm_email_token', '');
echo 'Your email has been confirmed, you can now log in';
}
}
}
7. Time for thinking
Okay, after all of his, i'm gonna think a little, and read what i have tell you, to check if there is no mistake ^^. Tell me if you need more explanations.
I think this is a good start for you, and if you find the right hooks, you will achieve this rapidly.
Be careful on some hooks that i have used, because your theme may have use a custom registration or something.
Here is what I did:
added a column in the table wp_users to receive the email confirmation code
built a plugin (details here) called user-emails that allows me to bypass the first email sent upon registration by redefining the function wp_new_user_notification (in which I generate the confirmation code, add it to the user in the DB and send a confirmation email of my own sauce)
redefined the wp_authenticate function inside the same plugin user-emails to allow me to check if the email has been confirmed (column value not null)
created a page for the confirmation with the email and code passed to it that, in case of success, display a message and a link to the home page in order to login
finally got my hands on that one tiny line of code responsible for the auto login after registration located in the page user_auth.php inside the theme folder itself (that file also contains the layout for the login and registration form)
wp_set_auth_cookie( $user_id, true, $secure_cookie );
made sure to display a message after registration informing the user to check his email for the confirmation email

Drupal 7 - How to redirect a user to a certain page until they change a setting on that page?

How can I force Drupal 7 to redirect the user to a certain page (which contains a form) wherever the user clicks on the site, after they logged in, until they fill out that form?
Eg.: Anon User arrives to the site, they can browse around no problem.
Once they login/register, I would like to show a page (with a form) and not allow
them to go anywhere else until they fill that form out.
This solution has to work with cached pages so hook_init() can't be used.
hook_boot() seemed a good idea, but it is loading too early and lots of required includes won't load.
Also, the solution has to check if the page request is the actual form submit (otherwise they won't be able to submit the form)
Any ideas, suggestions?
Ok, so it seems that hook_init() is the solution and the problem was caused by the $user object. The trick is, that you have to reload the $user object, as the global doesn't contain the field values.
Very simple example code:
function mymodule_init(){
global $user;
if($user->uid && $user->uid != 1){
$account = user_load($user->uid);
$account = entity_metadata_wrapper('user', $account);
$destination = drupal_get_destination();
if(!$account->field_setup_completed->value()){
drupal_set_message('Setup incomplete.', 'error');
if($destination['destination'] != 'setup-page' && $destination['destination'] != 'user/logout'){
drupal_set_message('Redirecting to setup', 'error');
drupal_goto('setup-page');
}
}
}
}

Override user_login_submit in Drupal 6 to redirect an authenticated user

I would like to redirect a user that logged in over the user login block. What I have is a module that contains the following code:
Appendix, 3.9.2011, 15:30h: Changed code according to the advice of kiamlaluno.
Appendix, 3.9.2011, 17:08h: Small Fix: Changed node/admin to admin.
Appendix, 3.9.2011, 17:24h: removed []
-> code is working like this now, but do not forget to change the module priority in DB.
function _MYMODULE_user_login_submit($form, &$form_state) {
global $user;
if ($user->uid == 1) {
$form_state['redirect'] = 'admin';
} elseif ($user->uid) {
$form_state['redirect'] = 'node/add/image';
return;
}
}
/**
* Modifies the outfit and behaviour of the user login block.
*/
function MYMODULE_form_user_login_block_alter(&$form, $form_state) {
unset($form['#action']);
// removes the forgot password and register links
$form['links'] = array();
// Redirects the user to the image upload page after login
// This cannot be done by a rule, the rule based redirect is only
// working for the login page not the user login block.
$form['#submit'] = array('_MYMODULE_user_login_submit');
}
It doesn't redirect users; it seems like _MYMODULE_user_login_submit() is simply ignored.
What I know already:
I cannot use Rules/Triggers, because I do not login over the login page but the user login block
It is always said: "use logintoboggan" on posts, but there I only have redirection options for "on registration" and "on confirmation", but I need "on authentication" or "after login".
Anyway, I do not want to use more modules, I prefer a few lines of PHP.
Your code doesn't work because user_block_login() sets the "#action" property for the form; in that case, redirecting the form after submission doesn't work.
$form = array(
'#action' => url($_GET['q'], array('query' => drupal_get_destination())),
'#id' => 'user-login-form',
'#validate' => user_login_default_validators(),
'#submit' => array('user_login_submit'),
);
To make it work, you should first unset $form[#action], and then executing the code you already execute in your hook_form_alter() implementation.
As side notes, I will add:
If you want to be sure your code effectively redirect the user where you want, be sure your module is executed for last; if any other module that implements hook_form_alter() adds a form submission handler to redirect the user to a different page, and that module is executed after yours, then your module would not have any effect. To make sure your module is executed after the others, you should use code similar to the following during the installation of the module, or in an update hook. (Replace "MYMODULE" with the short name of the module.)
db_query("UPDATE {system} SET weight = 100 WHERE name = 'MYMODULE');
Instead of using MYMODULE_form_alter(), you can use `MYMODULE_form_user_login_block_alter(), which would not require to check the form ID.
You should append new form submission handlers, instead of replacing the existing ones. This means you should use $form['#submit'][] = 'user_login_submit_redirected';.
Functions implemented in a module should be prefixed with the short name of the module, which means "MYMODULE_" or "_MYMODULE_" (the latter is for private functions). Not using such prefix could create a compatibility issue with other module, such as the User module, as the function you are using has a name starting with "user_."
can u try this please
function user_login_submit_redirected($form, &$form_state) {
global $user;
if ($user->uid == 0) {
$form_state['redirect'] = 'node/admin';
drupal_goto('node/admin') ;
} elseif ($user->uid) {
$form_state['redirect'] = 'node/add/image';
drupal_goto('node/add/image') ;
return;
}
}

How do I hook into the Wordpress login system to stop some users programmatically?

I am working on a Wordpress based portal which integrates with a custom-made e-commerce.
The e-commerce serves also as a 'control panel': all the roles are set up there. Some users are recorded but 'inactive'; they shouldn't be able to log into Wordpress. For this reason I need to hook into the Wordpress login system.
If a user is, say, "bad_james", he cannot login, even if he has a valid WP login and PWD. The WP admin panel doesn't provide a a flag to block users.
Is there a way to implement a login filter?
Cheers,
Davide
You can either overload the wp_authenticate function (see the function in the code here: http://core.trac.wordpress.org/browser/trunk/wp-includes/pluggable.php) and return a WP_error if you don't want to allow the user to login.
Or better, use the filter authenticate and return null if you don't want the user to log in, e.g.
add_filter('authenticate', 'check_login', 10, 3);
function check_login($user, $username, $password) {
$user = get_userdatabylogin($username);
if( /* check to see if user is allowed */ ) {
return null;
}
return $user;
}
There were a few issues with mjangda answer so I'm posting a version that works with WordPress 3.2
The main issues were with the return statement. He should be returning a WP_User Object. The other issue was with the priority not being high enough.
add_filter('authenticate', 'check_login', 100, 3);
function check_login($user, $username, $password) {
// this filter is called on the log in page
// make sure we have a username before we move forward
if (!empty($username)) {
$user_data = $user->data;
if (/* check to see if user is allowed */) {
// stop login
return null;
}
else {
return $user;
}
}
return $user;
}
Might be an idea or code to borrow and implement: WordPress › External DB authentication « WordPress Plugins

Resources