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?

3
  • Did you find a solution for this? I have the exact same problem. I am trying to upload the content of a file which is already in a buffer. I also do not want to write it back to a file in order to upload it as a file. Commented Oct 16, 2012 at 20:28
  • i've the same problem :( Commented Dec 6, 2012 at 14:41
  • I still have no solution for this. Commented Dec 20, 2012 at 7:40

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.