Posted By

benjaminpearson on 11/19/09


Tagged

curl http php


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

alejandromb
summerblue
StrawMan


PHP HTTP POST images & files


 / Published in: PHP
 

The following are instructions to "re-post" files that have been already been POSTed to your php script. This can help if you want to have a form (with file upload) that POSTs its data to your own script where the text elements can be handled and then the script POSTs the file for processing/storage on another system.

Basically the key is that you only POST the $_FILES['tmp_name'] with an "@" symbol prepended.

Spent a good hour trying to figure this out. Thanks to gordon who posted on 08-Sep-2004 10:08 at http://theserverpages.com/php/manual/en/ref.curl.php

  1. <?php
  2. $url = ''; // the url of the file processing script (ie, http://example.com/upload)
  3.  
  4. // Iterate through each file, check it has been stored in a tmp location, then post to another url
  5. foreach ($_FILES as $file) {
  6. // tmp_name will look something like this /private/var/tmp/phpRDJDT92
  7. if ($file['tmp_name'] > '') {
  8. $params['file'] = '@'.$file['tmp_name']; // Its this @ symbol thats the key.
  9. $response = post($url, $params);
  10. }
  11. }
  12.  
  13. function post($url, $params = array()) {
  14. try {
  15. $response = http_post($url, $params);
  16. return $response;
  17. } catch (Exception $e) {
  18. return null;
  19. }
  20. }
  21.  
  22. // More REST methods available at http://snipplr.com/view/19781/php-rest/
  23. // Nothing special about this cURL POST. You dont have to set any special headers for file uploading.
  24. function http_post($url, $data) {
  25. $c = curl_init();
  26. curl_setopt($c, CURLOPT_URL, $url);
  27. curl_setopt($c, CURLOPT_POST, 1);
  28. curl_setopt($c, CURLOPT_SSL_VERIFYPEER, true);
  29. curl_setopt($c, CURLOPT_POSTFIELDS, $data);
  30. curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
  31. $output = curl_exec($c);
  32. curl_close($c);
  33. return $output;
  34. }
  35. ?>

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: CDRates on February 8, 2010

been looking for this everywhere

You need to login to post a comment.