Autologin a WordPress user in your PHP script

WordPress theme code editing

How to automatically login a WordPress user in your PHP script

I was having some problems using the WordPress function wp_insert_post in a cron job I was working on, and I remembered having read somewhere that the wp_insert_post -function reacted differently depending on whether or not a user was logged in or not, so I found some code that automatically logged in a user, which I then added to the top of my PHP-script, and voila, the problem was solved:


require('wp-blog-header.php'); 
$user_login = 'admin'; 
$user = get_userdatabylogin($user_login);
$user_id = $user->ID; 
wp_set_current_user($user_id, $user_login);
wp_set_auth_cookie($user_id); 
do_action('wp_login', $user_login); 

Now, remember to set the proper path for the wp-blog-header.php file. (I know, there are other ways of loading the WordPress functions).

Secondly, remember to set the correct username. In this example, I have used the default ‘admin’.

Notice how you do not need to enter the password for the user? This is powerful stuff, but be careful where you use it.

22 Comments

  1. searbe on 30/06/2009 at 04:56

    Fantastic ๐Ÿ™‚ Needed this so users can be logged in after an ajax-based registration. Thanks for taking the time to post it

    • cleverplugins.com on 30/06/2009 at 08:29

      You are welcome, glad you like it and commented. Comments like this motivate me to continue distributing tips and tricks when I encounter them.

      Best of luck with the code, glad it helped ๐Ÿ™‚



  2. Patricia Jocobi on 22/10/2009 at 18:36

    This is great, just what I was looking for, Thanks a lot!

    I will use it to integrate a blog using WordPress to my site, I’ve already have a user login authentication, and don’t to use wordpress login

    I’m populating my site users table to wp_user table

    Do you think I would have a security issue if I use it for this purpose?

  3. cleverplugins.com on 23/10/2009 at 07:28

    I don’t think there would be a security issue as such, obviously you need to secure your own login-system, but if you already do that, the data you send to WordPress should be fine.

    You should also note that by maintaining a separate user-login system, you have two databases you need to keep synchronized, making sure to add, modify and delete users in both.

    Although it is clearly your own business, I suggest to take a look at fully using WordPress as your userdatabase. I do that on linklaunder.com (which is not active at the moment, unfortunately), where I use a few plugins to ensure a double-opt-in system where users actively agree to the disclaimer, privacy policy, etc. This is through the use of the plugin “Register Plus”.

    It is very easy to use a bit of php-code in your template files, to use WordPress to process user-level, and provide individual user data to logged in users.

    Just my suggestion, let me know if you need some help, should you choose to go that direction.

    Thank you for visiting, and leaving a comment! ๐Ÿ™‚

  4. Ruth on 16/03/2010 at 04:17

    I am integrating a wordpress blog to my website and have created other tables in my wordpress database with individual user data. Is it possible to provide this information when the user logs in with their wordpress username and password?

    • cleverplugins.com on 16/03/2010 at 05:33

      Hi Ruth

      It sure is. I do not know how you store the data in the other tables, but I suspect you have their userid or login as reference in the other table?

      Then it is “just” a matter of looking up the extra data referencing their $user_id, and display their information.

      I suggest you use the built-in functionality in WordPress to let the users log in, and then have a piece of script similar to:

      <?php
      $user = wp_get_current_user();
      $userid=$user->ID;
      
      //user is logged in, $user->ID will be their ID, etc..
      if ($userid<>'') {
      	$nicename=$user->user_nicename;
      	$registered=$user->user_registered;
      	echo '<h3>Welcome <strong>$nicename</strong></h3>';
      	echo '<p>Registered on: $registered</p>';
      	}
      
      else
      
      	{
      	     echo '<p>You are not logged in.</p>';
               }
      
      ?>
      

      I have above code in a separate page-template in my theme.

      In above code example you can add a lookup for their extra data if they are logged in.

      I hope that it what you were looking for? If not, let me know, and I’ll see what I can do.



    • Ruth on 27/04/2010 at 06:58

      Thank you very much for posting this script, this is exactly what I was looking to do, and was able to incorporate it successfully into my code ๐Ÿ™‚



  5. Marius Patrascu on 23/04/2010 at 05:07

    Hello! this is the only thing close to what I need so thank you very much for using the time to write it!

    I have an free script, me and some friends developed, and I wanna ask you, it it posible to build an external user system based on WordPress use system?

    Let’s say you have /root script and /root/u wordpress.

    Can I loggin user in WordPress and call user data in script? Like session, name, chack if it’s legged ?

    Thank you very much for your time answer this!

  6. Marius Patrascu on 23/04/2010 at 05:08

    I’m very sorry for my english, I hope you understant even with my mistakes.

  7. Sal on 20/05/2010 at 16:28

    Thank you for posting this script it has helped out alot. One question though…

    I am using this dynamically, grabbing the users username from the headers which has been authenticated from a different source. I’m looking for a script that will automatically add the user as a subscriber if they are not already in the DB. Anyone have a script that will accomplish that?

  8. Samuel Anyaele on 30/07/2010 at 21:03

    Thanks a lot for this code, however, I am having difficulties integrating into WordPress 3, the user is never logged in. What do I do?

  9. Peter Teniz on 04/09/2010 at 23:59

    thanks for your great autologin example!
    for login in multisite-wordpress 3.0.1 you need additional information
    such as $current_site and $current_blog to auto login

    cheers
    Peter

    $current_site = array(
    “id” => 1 ,
    “domain” => “domain.net” ,
    “path” => “/” ,
    “blog_id” => 1 ,
    “cookie_domain” => “domain.net” ,
    ) ;
    $current_blog = array(
    “blog_id” => “1” ,
    “site_id” => “1” ,
    “domain” => “blog.domain.net” ,
    “path” => “/” ,
    “registered” => “2010-09-04 23:44:04” ,
    “last_updated” => “2010-09-04 23:46:09” ,
    “public” => “1” ,
    “archived” => “0” ,
    “mature” => “0” ,
    “spam” => “0” ,
    “deleted” => “0” ,
    “lang_id” => “0” ,
    ) ;
    require(‘wp-blog-header.php’);
    $user_login = ‘admin’;
    $user = get_userdatabylogin($user_login);
    $user_id = $user->ID;
    wp_set_current_user($user_id, $user_login);
    wp_set_auth_cookie($user_id);
    do_action(‘wp_login’, $user_login);

    • Lars Koudal on 05/09/2010 at 20:00

      Hi Peter

      Thank you for dropping by and leaving updated code for WordPress 3. Much appreciated! ๐Ÿ™‚



  10. Peter Teniz on 07/09/2010 at 20:57

    Hi Lars
    meanwhile I found, that $current_site and $current_blog are only the half of the truth!
    Both should be objects like:

    class site {
    public $id = 1;
    public $domain = โ€œdomain.netโ€;
    public $path = โ€œ/โ€;
    public $blog_id = 1 ;
    public $cookie_domain = โ€œdomain.netโ€ ;
    }

    $current_site = new site() ;

    that does the trick of autologin in truth and also works for user creation scripts an similar for particular blogs.
    Sorry for dealing with part of the truth

    cheers
    Peter

  11. Dan O'Prey on 14/10/2010 at 21:42

    Thank you so much for this, Lars, it was exactly what I needed. I too was trying to sync WordPress accounts with accounts on another server, so I needed this on a custom registration form.

    Just stopping by to say thanks, keep up the great work!

  12. stesvis on 10/01/2011 at 06:34

    Hi!
    I hoped this would solve my problem, and it partially did, but when i execute this piece of code i get the following errors:
    ———————————————–
    Warning: Cannot modify header information – headers already sent by (output started at /home/…./wp-content/themes/idream/header.php:7) in /home/…./wp-includes/pluggable.php on line 690

    Warning: Cannot modify header information – headers already sent by (output started at /home/…./wp-content/themes/idream/header.php:7) in /home/…./wp-includes/pluggable.php on line 691

    Warning: Cannot modify header information – headers already sent by (output started at /home/…./wp-content/themes/idream/header.php:7) in /home/…./wp-includes/pluggable.php on line 692
    ———————————————–

    does it depend on the theme? i tried 3 or 4 themes and it happened with all of them..

    am i doing something wrong? thanks!

  13. Ola Karlsson on 25/01/2011 at 21:17

    Hi,
    I want to autologin in everybody that click on links (that lead to my site) on a certain URL. So, If a link to my page is published on domain.com the person clicking it should be loged in autoamtically with a certain user.

    If the same link is somewhere else tha one who clicks it shall not be logged in.

    Any suggestions on how to do this? Possible?
    many thanks.
    /Ola

  14. Samuel on 16/02/2011 at 09:15

    I think there are two approaches to doing this, either should work:
    1. include a URL variable on the link coming from the domain you want to autologin from, e.g.

    yourdomain.com/?auto=1
    

    OR
    2. Which is less reliable since not all browsers will provide it, try getting the URL from whence a visitor is coming, in PHP, use:

    if($_SERVER['HTTP_REFERER'] == 'domain.com' ) {
        ...
    }
    

    Then proceed to input the autologin script above

  15. Ivan Novak on 11/05/2011 at 23:55

    Lars, thanks for sharing this work. I’m using it as part of link that allows users of in-network sites to be automatically logged in from site to site.

    Thanks and keep it up ๐Ÿ™‚

  16. bristweb on 22/06/2011 at 17:47

    thanks for this, it definitely got me in the right direction. however, wp_login is depracated now. wp_signon is what should be used:

    http://codex.wordpress.org/Function_Reference/wp_signon

  17. Lars on 23/07/2011 at 09:16

    Thanks,
    Now I have a start point. I need to extract the logged in user as input to a php for add the filter to a database where the user-id tell that user can edit his own row but only view other members.

    Take care / Lars

  18. Thomas Nelson on 14/10/2012 at 20:39

    I am trying to use this auto login code so that I can do a wp_insert_post as well and it doesn't seem to work for me it just brings me to the login page, is this because of updates to WordPress?

Leave a Comment





Cleverplugins.com Newsletter

Articles about how to improve your WordPress website, how to get more traffic and most importantly more customers.

Subscribe

Something went wrong. Please check your entries and try again.