Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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,
)
);
@cleissonbarbosa
Copy link

cleissonbarbosa commented Aug 23, 2021

Nice job! tks for sharing

@nphp101
Copy link

nphp101 commented Sep 3, 2021

thanks for sharing

@RoyKoeleman
Copy link

RoyKoeleman commented Sep 15, 2021

Thanks so much for this!

@CamiloARC
Copy link

CamiloARC commented Sep 15, 2021

Thanks

@DamichiXL
Copy link

DamichiXL commented Mar 11, 2022

Thanks. It helped me

@delacruzdesign
Copy link

delacruzdesign commented Apr 7, 2022

Funciona perfecto! Gracias!

@JoachimPiq
Copy link

JoachimPiq commented Apr 21, 2022

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

tamara-m commented Jun 11, 2022

Helped me too

@julian-stark
Copy link

julian-stark commented Sep 28, 2022

Great, thanks

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