WordPress / Requests

Requests for PHP is a humble HTTP request library. It simplifies how you interact with other sites and takes away all your worries.
https://requests.ryanmccue.info/
Other
3.57k stars 498 forks source link

Uploading files #664

Open manix opened 2 years ago

manix commented 2 years ago

As I see file uploads are still not possible, even though the fix was suggested some 4 years ago.

Currently I needed to post files and I wasn't in the mood for rewriting stuff in my app, so this is what I came up with:

$hooks = new Requests_Hooks();
$hooks->register('curl.before_send', function ($ch) {
  if (function_exists('curl_file_create')) { // php 5.5+
    $cFile = curl_file_create($_FILES['uploadFile']['tmp_name'], '', $_FILES['uploadFile']['name']);
  } else { // 
    $cFile = '@' . realpath($_FILES['uploadFile']['tmp_name']);
  }
  $_POST['uploadFile'] = $cFile;

  curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST);
});
$resp = Requests::post($url, $headers, [], $options);

Just sharing in case it helps someone.

Close when #313 is ready :)

LukaszJaro commented 1 year ago

Thank you! I have to POST a file to a external API and was wondering how to do this the WP way, I found this https://core.trac.wordpress.org/ticket/35388

But your solution looks cleaner.

Also another similar solution here to /ticket/35388 https://gist.github.com/sirbrillig/6ab49aa6517d203a6560d75d65e0874a