Authenticate out WP to get current user - php

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

Related

Check if user had autologin & if so, logout

With Wordpress, I'm trying to create a function which autologins users, but upon visiting certain pages also performs an autologout if the initial login was obtained via autologin.
I've written the following code but I guess my boolean check for the autologin boolean does not work.
/* AUTO LOGIN / LOGOUT */
function autologinout() {
global $wp;
// Autologin
if( isset($_GET['username']) ) {
$user = get_user_by('login', $_GET['username']);
// Redirect URL //
if ( !is_wp_error( $user ) ) {
if ( in_array( 'customer', (array) $user->roles ) ) {
wp_clear_auth_cookie();
wp_set_current_user ( $user->ID );
wp_set_auth_cookie ( $user->ID );
wp_redirect( '/lovelists/toon-lovelist/' );
$autologin = true;
exit();
}
}
}
// Autologout
$path = $_SERVER['REQUEST_URI'];
if ( is_user_logged_in() && $autologin = true && ( $path == '/lovelists/maak-lovelist/' || $path == '/lovelists/login/' ) ) {
wp_clear_auth_cookie(); // so you don't get the cache error
wp_logout(); // this will logout user
$autologin = false;
}
}
add_action( 'init', 'autologinout' );
Any idea what I'm doing wrong?

Wordpress Password Reset since 4.3 upgrade

I've been using a Wordpress tutorial to build a suitable login and pawords reset process as outlined here:
http://code.tutsplus.com/tutorials/build-a-custom-wordpress-user-flow-part-1-replace-the-login-page--cms-23627
It worked super well until upgrade to Wordpress 4.3 in when the password reset stopped working and I now get an invalid key error message.
I have presumed that the mechanism has changed since the upgrade/ use of hashing/password expiration but cant seem to find any documentation. Does anyone know how to fix this, the password reset is outlined below:
/**
* Resets the user's password if the password reset form was submitted.
*/
public function do_password_reset() {
if ( 'POST' == $_SERVER['REQUEST_METHOD'] ) {
$rp_key = $_REQUEST['rp_key'];
$rp_login = $_REQUEST['rp_login'];
$user = check_password_reset_key( $rp_key, $rp_login );
if ( ! $user || is_wp_error( $user ) ) {
if ( $user && $user->get_error_code() === 'expired_key' ) {
wp_redirect( home_url( 'member-login?login=expiredkey' ) );
} else {
wp_redirect( home_url( 'member-login?login=invalidkey' ) );
}
exit;
}
// Reset password
reset_password( $user, $_POST['pass1'] );
wp_redirect( home_url( 'member-login?password=changed' ) );
} else {
echo "Invalid request.";
}
exit;
}
}

Redirect if it's not certain user - wordpress

I have created a page for a certain user in wordpress. Let's say his username is John. I am looking for PHP script that allow only 'John' to access that page and if users with different username other than 'John' tries to access the page they are redirected to another page.
I am new to PHP, so here's some code I have tried. But it redirects all users, even the user with username 'John'
<?php $user_info = get_userdata(1);
$username = $user_info->user_login;
if ( $username=='John' ) {
echo '';
} else {
wp_redirect( home_url() );
exit;
}
?>
Here's a wordpress page with parameters to get userdata - https://codex.wordpress.org/Function_Reference/get_userdata
You can use wp_get_current_user() function instead.
global $current_user;
get_currentuserinfo();
$username = $current_user->user_login;
if ( $username == 'John' ) {
echo '';
} else {
wp_redirect( home_url() );
exit;
}
This may solve your problem.
add_action( 'init', 'blockusers_init' );
function blockusers_init() {
global $current_user;
$current_user = wp_get_current_user();
if ( 'John' == $current_user->user_login ) {
//your desire page url
wp_redirect( 'your page url' );
exit;
} else {
wp_redirect( home_url() );
exit;
}
}
Take reference from
add_action( 'init', 'blockusers_init' );
function blockusers_init() {
if ( is_admin() && ! current_user_can( 'administrator' ) &&
! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
wp_redirect( home_url() );
exit;
}
}
https://premium.wpmudev.org/blog/limit-access-to-your-wordpress-dashboard/
Try this : First check if user is logged_in if yes then take the user information and do what ever you want with it
if(is_user_logged_in()){
$current_user = wp_get_current_user();
if($current_user->user_login == "John"){
wp_safe_redirect("Where ever you want");
exit;
}
else
wp_safe_redirect(home_url('/'));
NOTE : Make sure to check your username in database , I set my username as my lastname.

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;
}
}

Categories