I have created a custom login for wordpress to let user login automatically into wordpress via a custom form on another page that is not on wordpress but on the same hosting. The form saves the name in a cookie and then redirects user to wordpress homepage where the plugin logins user using the following code :
if (!is_user_logged_in()) {
$user_login = $_COOKIE['user_name_from_the_form'];
//get user's ID
$user = get_userdatabylogin($user_login);
$user_id = $user->ID;
//login
wp_set_current_user($user_id, $user_login);
wp_set_auth_cookie($user_id);
do_action('wp_login', $user_login);}
The problem is, this code sucessfully logins the user but if i visit homepage of the website , then it gives runtime error. All other pages work fine but on homepage, it gives runtime Application error (A yellow page open and shows "Server Error in '/' Application" .
If i disable the plugin and login to wordpress via wordpress login form, then it doesn't give any error.
I tried increasing the memory limit from php.ini to 128MB but this fixed the problem temporarily. After some time, if i refresh the homepage several times, this error again occurs.
Please guide me if there is any error in the code or something else. Thank you.
If i logout user via following code
wp_destroy_current_session();
wp_clear_auth_cookie();
wp_logout();
and refresh the home page, it works fine.
I have set the cookie time 3600 (i.e 1 hour).
Here is the complete function, that i am using :
function manage_user(){
if (isset($_COOKIE['user_name_from_the_form'])){} else {return 0;}
if ($_COOKIE['user_name_from_the_form'] != '0') {
if (!is_user_logged_in()) {
$user_login = $_COOKIE['user_name_from_the_form'];
//get user's ID
$user = get_userdatabylogin($user_login);
$user_id = $user->ID;
//login
wp_set_current_user($user_id, $user_login);
wp_set_auth_cookie($user_id);
do_action('wp_login', $user_login);}
} else {
wp_destroy_current_session();
wp_clear_auth_cookie();
wp_logout();
}}
add_action('init', 'manage_user');