title: Microsoft Dynamics CRM and PHP/JSON
body: <p>I have to implement form on a webpage, that sends data to Microsoft Dynamics CRM when submited. The data needs to be saved to a certain lead.</p>
  
  <p>I have created simple PHP script that uses curl to communicate with CRM server but I always get <code>401</code> status code that indicates authorization has failed.</p>
  
  <pre><code>define('MS_CRM_URL', 'https://______.crm.dynamics.com/');
  define('MS_CRM_USER', 'user@domain.com');
  define('MS_CRM_PASS', 'password');
  $method = '/api/data/v8.0/accounts?$select=name&amp;$top=3';
  
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, MS_CRM_URL . $method);
  curl_setopt($ch, CURLOPT_USERPWD, MS_CRM_USER .':'. MS_CRM_PASS);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, array(
  
  ));
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array(
      'Accept' =&gt; 'application/json',
      'OData-MaxVersion' =&gt; '4.0',
      'OData-Version' =&gt; '4.0',
      'Content-Type' =&gt; 'application/json',
  ));
  
  $server_output = curl_exec($ch);
  $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  
  curl_close($ch);
  
  $json = array();
  if ((int)$status_code === 200) {
      $json = json_decode($server_output);
  }
  
  echo '&lt;pre&gt;';
  var_dump($status_code);
  var_dump($json);
  echo '&lt;/pre&gt;';
  </code></pre>
  
  <p>The <code>$method</code> var contents are taken from an example that I've found somewhere on Microsoft documentation site. The documentation was not very helpful to me.</p>