Thursday, December 12, 2013

Login/logout to Drupal remotely in PHP

Previously I explained how to login/logout to Drupal using Java. It's far easier in PHP because of the curl module, which can easily be added to any php installation. Most the http header fields are handled for you so the code is pretty simple. A couple of tricks though: you must set CURLOPT_FOLLOWLOCATION on the connection when reading the logout response or you'll just get a redirect. When logging in that doesn't matter as the cookie is returned immediately. And if you want to store the cookie you can use get_variable, set_variable to store it in the Drupal database. There probably isn't much need for the logout function but I included it anyway for completeness:

Then there is the little question of when the cookie crumbles. Since the above code reads the "expires" string from the initial cookie response it is easy to store the expiration string along with the cookie (so I return an array from remote_login), and then compare the current time with this value whenever you retrieve it. If it has expired it needs to be renewed:

2 comments:

  1. Nice post, but how do you deal with the challenge response fields? As far as i am concerned you may turn it off?

    ReplyDelete
    Replies
    1. Hi Mandi,
      you'll have to be more specific. Which challenge-response mechanism are you referring to? *If* it is possible to automate it you can probably do it via curl, but if it requires human input by e.g. reading a captcha it's not possible. My solution was just for the simple login.

      Delete