Search code examples
phppostcredentials

I tried to call a post request using PHP code, but I got 401 Unauthorized error.


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);

Solution

  • 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.