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);
lostphilosopher
  • 4,361
  • 4
  • 28
  • 39
J - C Sharper
  • 1,567
  • 7
  • 23
  • 36

1 Answers1

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.

Marc B
  • 356,200
  • 43
  • 426
  • 500