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:

$user_login = 'admin'; 
$user = get_userdatabylogin($user_login);
$user_id = $user->ID; 
wp_set_current_user($user_id, $user_login);
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.