title: Do a CURL post using PHP?
body: <p>I have the following curl command that works perfectly from the windows command line:</p>
  
  <pre><code>curl -v -H "Accept: application/json" -H "Content-type: application/json" -X PUT -d   "{\"name\":\"Name\",\"password\":\"1234\",\"email\":\"somebuy@bla.com\"}"   http://localhost:8080/users
  </code></pre>
  
  <p>So the jSon for this post is:</p>
  
  <pre><code>{\"name\":\"Name\",\"password\":\"1234\",\"email\":\"somebuy@bla.com\"}
  </code></pre>
  
  <p>I try to execute it using the following PHP Code:</p>
  
  <pre><code>$ch = curl_init(); // initialize curl handle
  $user_agent = $_SERVER['HTTP_USER_AGENT']; 
  curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
  curl_setopt($ch, CURLOPT_URL, $url); // set url to post to
  curl_setopt($ch, CURLOPT_FAILONERROR, 1); // Fail on errors
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // allow redirects
  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
  curl_setopt($ch, CURLOPT_PORT, $port); //Set the port number
  curl_setopt($ch, CURLOPT_TIMEOUT, 5); // times out after 5s
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  if (!empty($request)) {
    curl_setopt($ch, CURLOPT_POST, true);   
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($request)); // add POST fields
  }
  
  if($port==443) {
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  }
  
  $data = curl_exec($ch); // if($data === false) echo 'Curl error: ' . curl_error($ch);
  $error = curl_errno($ch);
  curl_close($ch);
  
  if ($error) {
    $error_codes = $this-&gt;_get_curl_error_codes();
    echo
      'Sorry, but we are currently not able to connect to the database. Error code '.$error.': '.$error_codes[$error];
    die();
  }
  </code></pre>
  
  <p>I use this code as follows:</p>
  
  <pre><code>$url = 'http://localhost/users';
  $port = 8080;
  $request = array();
  $request['name']        = 'Name';
  $request['password']    = '1234';
  $request['email']       = 'somebuy@bla.com';
  </code></pre>
  
  <p>Json is created like so:</p>
  
  <pre><code>curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($request)); // add POST fields
  </code></pre>
  
  <p>My problem is that if I run it from the command line, it works, but if I run it using the code above, it doesn't work. Any ideas why?</p>