Skip to content

Instantly share code, notes, and snippets.

@UmeshSingla
Created November 2, 2014 09:05
Show Gist options
  • Save UmeshSingla/40b5f7b0fb7e0ade0438 to your computer and use it in GitHub Desktop.
Save UmeshSingla/40b5f7b0fb7e0ade0438 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' =&gt; 'value'
);
$boundary = wp_generate_password( 24 );
$headers = array(
'content-type' =&gt; 'multipart/form-data; boundary=' . $boundary
);
$payload = '';
// First, add the standard POST fields:
foreach ( $post_fields as $name =&gt; $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' =&gt; $headers,
'body' =&gt; $payload,
)
);
?>
@Tamilselvand
Copy link

Hello,

We got the following error

{"code":"INVALID_DATA","details":{},"message":"the request does not contain any file","status":"error"}

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