PHP post request with file_get_contents and http authentication

Categories: 

Tags: 

Simple and clean

// Target
$url = 'https://target.domain.com';
$path = '/webservice/postExample.php';
 
// Apache authentication 
$httpUsername = 'apacheUser';
$httpPassword = 'apachePass';
 
// Data to POST
$dataPOST = '&id=XXX&name=XXX';
 
$opts = array('http' =>
  array(
    'method'  => 'POST',
    'header'  => "Content-Type: text/html\r\n".
      "Authorization: Basic ".base64_encode("$httpUsername:$httpPassword")."\r\n",
    'content' => $dataPOST,
    'timeout' => 60
  )
);
 
$context  = stream_context_create($opts);
$result = file_get_contents($url . $path, false, $context, -1, 40000);
 
var_dump(json_decode($result));