Monday, July 25, 2011

Debugging Titanium xhr requests with php

Authentication for xhr request for Appcelerator Titanium is difficult. During my latest bout with the cross platform mobile app platform I discovered that XHR request header variable names get renamed (aka case changes).

For the auth part of the app being worked on requires sending a Session Key for authorization for every request after the user is logged in. For a good tutorial on how a more basic authorization might work go check out Titanium User Authentication. In any case request headers sent from Titanium are re-cased i.e. "UserAuthKey" becomes "Userauthkey".

To discover this lil gem of a problem after hours of poking I chose to find and use a logging utility to see what was actually being sent.

Below is a quick php POST logging utility from CodeWord with headers added. This logging utility serializes the incoming Post request to a logs directory. It makes it easy to see the variables being passed in and headers.

To use, create a php file called xhrlog.php. Upload to your favorite testing server. Ensure you have a directory called "logs". Then submit your xhr POST requests to MYDOMAIN.com/xhrlog.php from php, html, android, titanium.. wherever and it'll log it for you!

<?php

 
  /*function from http://blog.apokalyptik.com/2008/03/25/logging-post-data/comment-page-1/
Creates a log file of the POST request
*/ 
if ( isset($_POST) && is_array($_POST) && count($_POST) > 0 ) {
  $log_dir = dirname( __FILE__ ) . '/logs/';
  $log_name = "posts-" . $_SERVER['REMOTE_ADDR'] . "-" . date("Y-m-d-H") . ".log";
  $log_entry = gmdate('r') . "\t" .serialize(parseRequestHeaders())."\n ". $_SERVER['REQUEST_URI'] . "\r\n" . serialize($_POST) . "\r\n\r\n";
  $fp=fopen( $log_dir . $log_name, 'a' );
  fputs($fp, $log_entry);
  fclose($fp); }
   
/*
function copied from stackoverflow http://stackoverflow.com/questions/541430/how-do-i-read-any-request-header-in-php

Parses html request headers
*/
  function parseRequestHeaders() {
    $headers = array();
    foreach($_SERVER as $key => $value) {
        if (substr($key, 0, 5) <> 'HTTP_') {
            continue;
        }
        $header = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))));
        $headers[$header] = $value;
    }
    return $headers;
}

?>



Stumble Upon CodePyro

No comments:

Post a Comment