while use wp_signon( $creds, false ) get the error - php

I want to login user automatically when user is activated in multisite.
but when I am trying to use wp_signon() it response with the error
Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\krosswall\wp-includes\class.wp-styles.php:127) in C:\xampp\htdocs\krosswall\wp-includes\pluggable.php on line 955
I am trying to do this
function kw_activate_blogs( $user_id, $password, $meta ) {
add_user_to_blog( '2', $user_id, get_site_option( 'default_user_role', 'subscriber' ) );
$user = new WP_User( (int) $user_id );
$creds = array();
$creds['user_login'] = $user->user_login;
$creds['user_password'] = $password;
$creds['remember'] = true;
$user = wp_signon( $creds, false );
wp_set_current_user($user->ID);
if ( is_wp_error($user) ) {
echo $user->get_error_message();
} else {
// safe redirect to actually login the user - otherwise they would need to manually refresh the page
// PLUS: this clears the activation confirmation page with the plain text password printed on screen
//wp_safe_redirect( get_home_url() );
exit;
}
}
add_action( 'wpmu_activate_user', 'kw_activate_blogs', 10, 3 );
I added this code in functions.php file. Please help me to solve it.

You can do this:
function kw_activate_blogs($user_id, $password, $meta)
{
$result=add_user_to_blog('2', $user_id, get_site_option('default_user_role', 'subscriber'));
if (!is_wp_error($result))
{
wp_set_current_user($user_id);
if (wp_validate_auth_cookie() == FALSE)
{
wp_set_auth_cookie($user_id, true, false);
}
}
else
{
//do something here on error
}
}
You don't need their password in this case. You can also remove 2nd and 3rd arguments if you don't need $meta and change add_action to add_action( 'wpmu_activate_user', 'kw_activate_blogs', 10);

Related

Create auto login links on get_checkout_payment_url in Woocommerce

Im looking at this guide https://www.pirenko.com/creating-wordpress-auto-login-links/ and Im trying to adjust it to a quote mail that uses the customer-invoice.php template.
Problems:
how do I fetch the correct key for the order?
How do I update current users with a secret key so I can call it for the url?
$secret_string=wp_generate_password( 8, false );
$login_link ='http://website.com/wp-json/sand_login/prk_route?username='.$username.'&secret='.$user_info->secret_key;
I started with removing the check for secret key, just to see if i could get it to work with email-adress to start with and added a redirect to checkout. I will add the check for the security key once I can get this updated on current user meta.
Added to functions.php
add_action( 'rest_api_init', function () {
register_rest_route(
'sand_login',
'prk_route',
array(
'methods' => 'GET',
'callback' => 'pirenko_login_user',
)
);
});
function pirenko_login_user() {
// Validate input
if (isset($_GET['username']) && $_GET['username']!="") {
$username = $_GET['username'];
$user = get_user_by('email', $username );
if ($user) {
//Check if secret key matches
$check_user = get_user_by( 'id', $user->ID );
//Login info is correct - let's proceed
// Manage login cookies
wp_clear_auth_cookie();
wp_set_current_user ( $user->ID );
wp_set_auth_cookie ( $user->ID );
// Finally redirect user
$order = new WC_Order($order_id);
$payment_page = $order->get_checkout_payment_url($order->ID);
wp_safe_redirect( $payment_page );
exit();
}
else {
echo "Could not find user!";
exit();
}
}
else {
echo "Parameters are missing!";
exit();
}
}
The email function in customer-invoice.php looks like this:
if ($order && $order->has_status('enquiry')) {
$email_text = str_replace('{betaallink}', '<a class="payment" href="' . esc_url($order->get_checkout_payment_url()) . '">', $email_text);
$email_text = str_replace('{/betaallink}', '</a>', $email_text);
}
And I updated it to this, without the secret key to start with:
if ($order && $order->has_status('enquiry')) {
$user = $order->get_user();
$username = $user ? $user->__get('user_email') : '';
$login_link ='http://website.com/wp-json/sand_login/prk_route?username='.$username;
$email_text = str_replace('{betaallink}', '<a class="payment" href="'. $login_link .'">', $email_text);
$email_text = str_replace('{/betaallink}', '</a>', $email_text);
}
This works. The user gets logged in and redirected to cart with this url with all open orders registered on the user:
https://website.com/afrekenen/order-pay/?pay_for_order=true&key
Do I go about this totally wrong?

Authenticate out WP to get current user

I am trying to get user detail out side wordpress file (But same server) and for that I am using this code
<?php
define( 'WP_USE_THEMES', false ); // Do not use the theme files
define( 'COOKIE_DOMAIN', false ); // Do not append verify the domain to the cookie
define( 'DISABLE_WP_CRON', true ); // We don't want extra things running...
//$_SERVER['HTTP_HOST'] = ""; // For multi-site ONLY. Provide the
// URL/blog you want to auth to.
// Path (absolute or relative) to where your WP core is running
require("/var/www/yourdomain.com/htdocs/wp-load.php");
if ( is_user_logged_in() ) {
$user = wp_get_current_user();
} else {
$creds = array();
// If you're not logged in, you should display a form or something
// Use the submited information to populate the user_login & user_password
$creds['user_login'] = "";
$creds['user_password'] = "";
$creds['remember'] = true;
$user = wp_signon( $creds, false );
if ( is_wp_error( $user ) ) {
echo $user->get_error_message();
} else {
wp_set_auth_cookie( $user->ID, true );
}
}
if ( !is_wp_error( $user ) ) {
// Success! We're logged in! Now let's test against EDD's purchase of my "service."
if ( edd_has_user_purchased( $user->ID, '294', NULL ) ) {
echo "Purchased the Services and is active.";
} else {
echo "Not Purchased";
}
}
?>
but it doesn't worked, I am creating custom dashboard out wp, which user wp info, as back-end. So please tell me what wrong am i doing? Any help is highly appreciated.
Since you are using easy-digital-downloads be sure it was included
if ( !function_exists( 'edd_has_user_purchased' ) ) {
require_once 'path-to-plugin/user-functions.php';
}
In your if ( !is_wp_error( $user ) ) statement you can use
echo "<p>ID: ".$user->ID;
echo "<p>Name: ".$user->data->display_name;
echo "<p>Login: ".$user->data->user_login;
echo "<p>Email: ".$user->data->user_email;
echo "<p>URL: ".$user->data->user_url;
echo "<p>Registered: ".$user->data->user_registered;
to show user wp info.
Try
print_r($user);
to overview all accessible fields

How to set is_user_logged_in() true in Wordpress

I am using wp_signon from inside a plugin and inside a shortcode function to login a user. To clarify, the short code is being called from a page content. The wp_signon function successfully returns the user info. But is_user_logged_in() is returning false. Why it's happening or how can I set is_user_logged_in() true so that user stays login?
ob_start();
$user_data = array();
$user_data['user_login'] = $username;
$user_data['user_password'] = $password;
$user_data['remember'] = $remember;
$user = wp_signon( $user_data, false );
ob_get_clean();
if ( is_wp_error($user) ) {
$err = $user->get_error_message();
} else {
$_SESSION['fc_user']=$user->ID;
var_dump($user); // gives the user info
var_dump(is_user_logged_in()); // gives false
}
The function wp_signon
sends headers to the page. It must be run before any content is returned.
So running it inside a shortcode (like you specified in your comment) is too late: headers have already been sent.
In order to achieve what you want you should divide your code in two parts, to be run at different time, something like this:
add_action( 'after_setup_theme', function() {
// run this only on the page you want
if( !is_page('the_page_you_want') )
return;
$user_data = array();
$user_data['user_login'] = $username;
$user_data['user_password'] = $password;
$user_data['remember'] = $remember;
$user = wp_signon( $user_data, false );
if ( is_wp_error($user) ) {
$GLOBALS['user_error_message'] = $user->get_error_message();
} else {
$_SESSION['fc_user'] = $user->ID;
}
} );
add_shortcode( 'your_shortcode', function( $atts ) {
if( is_user_logged_in() ) {
// get user info
return print_r( get_userdata(get_current_user_id()), 1 );
} elseif( isset($GLOBALS['user_error_message']) ) {
// show error
return print_r( $GLOBALS['user_error_message'], 1 );
}
} );
I just ran into a similar issue with an MVC Wordpress plugin.
For me the solution was to include
require_once($_SERVER['DOCUMENT_ROOT'].'/wp-includes/pluggable.php');
to have access to the core function via a plugin.

how to retrieve wp error in custom login form

I have create template for login with help of wp_login_form() function.
Now If user enter wrong password or username it will redirect me to the same page with argument login=failed with the following code :
add_action( 'wp_login_failed', 'front_end_login_fail' );
function front_end_login_fail( $username ) {
$_SESSION['uname'] = $username;
// Getting URL of the login page
$referrer = $_SERVER['HTTP_REFERER'];
$login_failed_error_codes = array( 'empty_password', 'empty_email', 'invalid_email', 'invalidcombo', 'empty_username', 'invalid_username', 'incorrect_password' );
// if there's a valid referrer, and it's not the default log-in screen
if( !empty( $referrer ) && !strstr( $referrer,'wp-login' ) && !strstr( $referrer,'wp-admin' ) ) {
wp_redirect( get_permalink( 93 ) . "?login=failed" );
exit;
}
}
NOW this function works ok but now as per wordpress functionality which provide as follow:
1.If user enter true username but wrong password it will show error as "incorrect_password"
2.If user enter false username but true password it will show error as "invalid_username"
3.If user enter wrong username but wrong password it will show error as "invalidcombo"
Add so on please check variable $login_failed_error_codes in code...
I have made some search.I got some class called "WP_error".But I dont know how it works with this code.
I am just stuck in how to pass object of WP_error from wp-login.php to my csutom template?
Thanks...any help would be appriciable.
I think I understand what you are trying to achieve. You want to be able to display the reason login failed on your own custom login page. I assume you already know how to fetch the $_GET parameters, since you are using that to pass your login_failed parameter.
Use the login_redirect filter instead:
add_filter('login_redirect', 'my_login_redirect', 10, 3);
function my_login_redirect($redirect_to, $requested_redirect_to, $user) {
if (is_wp_error($user)) {
//Login failed, find out why...
$error_types = array_keys($user->errors);
//Error type seems to be empty if none of the fields are filled out
$error_type = 'both_empty';
//Otherwise just get the first error (as far as I know there
//will only ever be one)
if (is_array($error_types) && !empty($error_types)) {
$error_type = $error_types[0];
}
wp_redirect( get_permalink( 93 ) . "?login=failed&reason=" . $error_type );
exit;
} else {
//Login OK - redirect to another page?
return home_url();
}
}
If you have created custom template for login then Why don't you use wp_signon method with the help of custom form ?. it will return WP_error object on false, and on true it will return $user object.
<?php
if(isset($_POST['submit'])){
$creds = array();
$creds['user_login'] = $_POST['user_email'];
$creds['user_password'] = $_POST['user_password'];
$creds['remember'] = true;
$user = wp_signon( $creds, false );
if ( is_wp_error($user) )
echo $user->get_error_message();
}
?>
<form id="user-credentials" method="post" action="<?php the_permalink(); ?>">
<p><input name="user_email" type="text" placeholder="Email" /></p>
<p><input name="user_password" type="password" placeholder="Password" /></p>
<p><input type="submit" value="Submit" /></p>
</form>
I've not tested in but it should work.
Looks like following answer is what you need:
You need to hook into the authenticate wordpress hook. Then return a
new WP_Error object to generate an error message and redirect back to
the login page. Here is an example.
add_filter('authenticate', 'check_login_submit', 40, 3);
function check_login_submit($user, $username, $password) {
$WP_Error = new WP_Error();
$WP_Error->add('my_error', '<strong>Error</strong>: Something went wrong.');
return $WP_Error;
}
function front_end_login_fail( $username ) {
$set_confirm=0;
$_SESSION['uname'] = $username;
/*******Check whether user entered username or email to login*********/
if(is_email( $username ) ){
if( email_exists( $username )) {
$uid = email_exists( $username );
$confirm_mail =get_user_meta($uid,'confirm_mail',true);
if($confirm_mail!=1){
$set_confirm=1;
}
}
//$user_check = get_user_by( 'email', $username );
//print_r($user_check);
}else{
if ( username_exists( $username ) ){
$uid = username_exists( $username );
$confirm_mail =get_user_meta($uid,'confirm_mail',true);
if($confirm_mail!=1){
$set_confirm=1;
}
}
}
//$user_check = get_user_by( 'user_login ', $username );
//print_r($user_check);
// Getting URL of the login page
$referrer = $_SERVER['HTTP_REFERER'];
// if there's a valid referrer, and it's not the default log-in screen
if( !empty( $referrer ) && !strstr( $referrer,'wp-login' ) && !strstr( $referrer,'wp-admin' ) ) {
wp_redirect( get_permalink( 93 ) . "?login=failed&confirm_email=".$set_confirm);
exit;
}
}
add_action( 'wp_login_failed', 'front_end_login_fail' );
i tried this way it worked for me
foreach ($array as $key => $value)
{
foreach ($value as $sub_key => $sub_val)
{
echo $sub_val;
}
}

Can't set cookie in Wordpress plugin after theme has started rendering

When I set a cookie in a Wordpress plugin, I get the "headers already sent" error. Can someone suggest how I can fix this?
Warning: Cannot modify header information – headers already sent by (output started at /home/content/53/7742253/html/wordpress/wp-content/themes/twentyten/header.php:11) in /home/content/53/7742253/html/wordpress/wp-includes/pluggable.php on line 692,693,694
my code:-
if(isset($_REQUEST['id']) && !is_user_logged_in())
{
require_once( ABSPATH . WPINC . '/registration.php' );
$registration = get_option( 'users_can_register' );
global $wpdb;
$user_id = $wpdb->get_var( $wpdb->prepare("SELECT user_id FROM
$wpdb->usermeta WHERE
meta_key = 'id' AND meta_value =%s",$id) );
if ( empty($user_id) )
{
$wp_user_obj = get_user_by('email', $email);
$user_id = $wp_user_obj->ID;
}
if ( $user_id)
{
wp_set_auth_cookie( $user_id );
wp_set_current_user( $user_id );
if ( isset( $_REQUEST['redirect_to'] ) && !empty(
$_REQUEST['redirect_to'] ) )
{
wp_redirect( home_url() );
}
else
{
wp_redirect(home_url() );
}
}
else
{
$userdata = array();
$user_id = wp_insert_user($userdata );
wp_new_user_notification($user_id,$user_pass);
if ( $user_id )
{
$creds = array();
$creds['user_login'] = $username;
$creds['user_password'] = $user_pass;
if ( !empty( $remember ) )
{
$creds['remember'] = true;
}
$user = wp_signon( $creds, true );
update_usermeta( $user_id,'id',esc_attr( $_REQUEST['id']));
update_usermeta( $user_id,'fname',esc_attr( $_REQUEST['fname']));
update_usermeta( $user_id,'lname',$_REQUEST['lname']);
update_usermeta( $user_id, 'email',esc_attr( $_REQUEST['email']) );
wp_redirect(home_url() );
}
}
}
global $user_ID; $user = get_userdata( $user_ID );
if(is_user_logged_in())
{
echo $user->user_login ;
}
and heder.php line:- `<html <?php language_attributes(); ?>>`
You're calling your set_cookies function too late. At the time you call it, output has already started. You need call it before any output has started, because cookies can not be set if output has already started (see as well: setcookieDocs).
In your case before header.php line 11 is being executed.
That's merely before the theme get's loaded.
You can avoid header modification warning messages by buffering your source, before it makes it to the browser. If you do not have access to php.ini you can add php_value output_buffering 4096 to your .htaccess or you can add ob_start("ob_gzhandler"); at the top and ob_end_flush() at the bottom of your wordpresses root index.php

Categories