Search code examples
phpauthenticationtitaniumxmlhttprequestbasic-authentication

$_SERVER['PHP_AUTH_USER'] empty


EDIT: Problem isn't with PHP, I was using cURL wrong. Updated question to show problem I'm having with XHR.

Summary: Can't get username to PHP using XHR:

var xhr = Ti.Network.createHTTPClient();
xhr.timeout = 1000000;
xhr.open("GET","http://myapi.com/test", false, 'user', 'pass');
xhr.send();

And in my PHP script, I'm trying to access the username with this:

<?php print $_SERVER['PHP_AUTH_USER']; ?>

No matter what I try it's always empty.

Is there some PHP setting that I need to configure?

More info: PHP Version 5.2.13, Apache, MAMP


Solution

  • <script src="http://www.webtoolkit.info/djs/webtoolkit.base64.js"></script>
    <script>
    var xhr = Ti.Network.createHTTPClient();
    xhr.timeout = 1000000;
    xhr.onreadystatechange = function() {
        if (xhr.readyState != 4) return;
        alert('Server said: '+xhr.responseText);
    };
    xhr.open('GET', 'http://myapi.com/test', false);
    xhr.setRequestHeader('Authorization', 'Basic ' + Base64.encode('user:pass') );
    xhr.send('');
    </script>
    

    (For the sake of courtesy, you should download webtoolkit.base64.js and serve it from your own server.)

    Keep in mind that you can't do cross-domain requests with XHR; your JavaScript and PHP have to be served from the same domain.