views:

2283

answers:

2

The API, I'm trying to implement requires the upload of XML file, containing the commands. The straightforward way to do this is to generate the content of the file, write it on the file system and upload it with curl to the web server.

What I'm trying to accomplish is to skip the writing part by using php's temp protocol handler. The sample code follows:

<?php
  $fp = fopen("php://temp", "r+");

  $request = 'some xml here';
  fwrite($fp, $request);

  rewind($fp);

  $input_stat = fstat($fp);
  $size = $input_stat['size'];

  $url = "http://example.com/script.php";
  $ch = curl_init();

  $filename = $_POST[cert_file] ;
  $data['file'] = "@xml.xml";

  curl_setopt($ch,CURLOPT_URL,$url);
  curl_setopt($ch,CURLOPT_POST,1);
  curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
  curl_setopt($ch,CURLOPT_INFILESIZE,$size);
  curl_setopt($ch,CURLOPT_INFILE,$fp);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
  $result = curl_exec($ch);
  $error = curl_error($ch);

  echo 'result:'.$result."\n";
  echo 'error:'.$error."\n";

  curl_close($ch);
?>

Unfortunately this doesn't work. Tcpdump shows that no request is being send. Update: The result I get is:

result:

error:failed creating formpost data

Does anyone has a clue, how to upload text as file on the fly with PHP?

+1  A: 

After the call to fwrite, add a call to rewind($fp). After the fwrite, the file pointer is at the end of the temp stream. If you call rewind it resets it to the beginning. Here's a quick proof from a PHP session:

php > $fp = fopen("php://temp", "r+");
php > fputs($fp, "<xml>some xml</xml>\n");
php > echo stream_get_contents($fp);
php > rewind($fp);
php > echo stream_get_contents($fp);
<xml>some xml</xml>
php > exit

After the first echo stream_get_contents, nothing was echoed. After the rewind, the second echo of stream_get_contents showed the XML.

Justin Poliey
+1  A: 

Possibly it's because, after writing to $fp the file handle's pointer is pointing at the end of the file. Have you tried rewinding it first?

fseek($fp, 0, SEEK_SET);
Curt Sampson