Skip to content

Instantly share code, notes, and snippets.

@sirbrillig
Forked from UmeshSingla/functions.php
Last active January 24, 2024 15:46
Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save sirbrillig/6ab49aa6517d203a6560d75d65e0874a to your computer and use it in GitHub Desktop.
Save sirbrillig/6ab49aa6517d203a6560d75d65e0874a to your computer and use it in GitHub Desktop.
Post file using wp_remote_post in WordPress
<?php
$local_file = 'file_path'; //path to a local file on your server
$post_fields = array(
'name' => 'value',
);
$boundary = wp_generate_password( 24 );
$headers = array(
'content-type' => 'multipart/form-data; boundary=' . $boundary,
);
$payload = '';
// First, add the standard POST fields:
foreach ( $post_fields as $name => $value ) {
$payload .= '--' . $boundary;
$payload .= "\r\n";
$payload .= 'Content-Disposition: form-data; name="' . $name .
'"' . "\r\n\r\n";
$payload .= $value;
$payload .= "\r\n";
}
// Upload the file
if ( $local_file ) {
$payload .= '--' . $boundary;
$payload .= "\r\n";
$payload .= 'Content-Disposition: form-data; name="' . 'upload' .
'"; filename="' . basename( $local_file ) . '"' . "\r\n";
// $payload .= 'Content-Type: image/jpeg' . "\r\n";
$payload .= "\r\n";
$payload .= file_get_contents( $local_file );
$payload .= "\r\n";
}
$payload .= '--' . $boundary . '--';
$response = wp_remote_post( $req,
array(
'headers' => $headers,
'body' => $payload,
)
);
@RoyKoeleman
Copy link

Thanks so much for this!

@CamiloARC
Copy link

Thanks

@DamichiXL
Copy link

Thanks. It helped me

@delacruzdesign
Copy link

Funciona perfecto! Gracias!

@JoachimPiq
Copy link

Thanks, helped me a lot.
In case this ever happens to anyone, the API I send the file to returns a 415 error when there is a special character in the boundary.Just set the 2nd parameter of wp_generate_password to false to avoid this.

@tamara-m
Copy link

Helped me too

@julian-stark
Copy link

Great, thanks

@iljamm
Copy link

iljamm commented Dec 9, 2022

Kudos! worked brill.

@ejperez
Copy link

ejperez commented Apr 3, 2023

Works like a charm!

@hirayGui
Copy link

hirayGui commented Jan 2, 2024

dude, you're a lifesaver. thanks a lot!!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment