1

I tried to send a post request using this PHP code but throw me 401 Unauthorized error:

$username = 'MyDomain\testuser';
$password = '123456';
$url = 'http://10.20.30.40:8080/TargetPage.aspx';

$data = array(
         'username' => $username,
         'password' => $password, 
         'postdata' => 'InputParameter1=Test1&InputParameter2=Test2'
);

$options = array(    
    'http' => array
            (
                'method'  => 'POST',
                'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                'content' => http_build_query($data)   
            )           
);

$context  = stream_context_create($options);    
$result = file_get_contents($url, false, $context);

1 Answer 1

0

You're not doing proper basic auth. You have to build the authenticate header yourself:

$options = array(
    'http' => array(
        'header' => 'Authorization: Basic ' . base64_encode("$username:$password")
    )
);

You can't just shove a username/password elements into the array and expect it to work. PHP doesn't know you're building a stream to HTTP basic auth... you have to provide EVERYTHING yourself.

2
  • I have edit the header like you said, but I still get the same error msg? Sep 6, 2013 at 21:22
  • I have change IIS Authentication to 'Basic Authentication" and you code work like a charm. Thanks. Sep 11, 2013 at 5:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.