title: Upload a file using an API PUT request
body: <p>I'm building an API in PHP. One of the methods is place.new (PUT request). It expects several string fields, and it also expects an image. However I can't get it working. With a POST request it was easy, but I'm not sure how to do it with a PUT and how to get the data on the server. </p>
  
  <p>thanks for the help!</p>
  
  <h3>Test CURL code</h3>
  
  <pre><code>$curl = curl_init();
  curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2);
  curl_setopt($curl, CURLOPT_HEADER, false);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
  curl_setopt($curl, CURLOPT_URL, $this-&gt;url);
  
  curl_setopt($curl, CURLOPT_PUT, 1);
  curl_setopt($curl, CURLOPT_INFILE, $image);
  curl_setopt($curl, CURLOPT_INFILESIZE, filesize($image));
  
  $this-&gt;result = curl_exec($curl);
  curl_close($curl); 
  </code></pre>
  
  <h3>Server code</h3>
  
  <pre><code>if ( $im_s = file_get_contents('php://input') )
  {
      $image = imagecreatefromstring($im_s);
  
      if ( $image != '' )
      {
          $filename = sha1($title.rand(11111, 99999)).'.jpg';
          $photo_url = $temp_dir . $filename;
          imagejpeg($image, $photo_url);
  
          // upload image
          ...
      }
  }
  </code></pre>
  
  <h1>Solution</h1>
  
  <h3>send</h3>
  
  <pre><code>// Correct: /Users/john/Sites/....
  // Incorrect: http://localhost/...
  $image = fopen($file_on_dir_not_url, "rb");
  
  $curl = curl_init();
  curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2);
  curl_setopt($curl, CURLOPT_HEADER, false);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
  curl_setopt($curl, CURLOPT_URL, $url);
  
  curl_setopt($curl, CURLOPT_PUT, 1);
  curl_setopt($curl, CURLOPT_INFILE, $image);
  curl_setopt($curl, CURLOPT_INFILESIZE, filesize($file_on_dir_not_url));
  
  $result = curl_exec($curl);
  curl_close($curl); 
  </code></pre>
  
  <h3>receive</h3>
  
  <pre><code>/* Added to clarify, per comments */
  $putdata = fopen("php://input", "r");
  
  /* Open a file for writing */
  $fp = fopen($photo_url, "w");
  
  /* Read the data 1 KB at a time
      and write to the file */
  while ($data = fread($putdata, 1024))
  {
      fwrite($fp, $data);
  }
  
  /* Close the streams */
  fclose($fp);
  fclose($putdata);
  </code></pre>