Posting file via wp_remote_post

发布于 2019-11-26  533 次阅读


提醒:本文最后更新于 1590 天前,文中所描述的信息可能已发生改变,请谨慎使用!
你似乎正在查看一篇很久远的文章。
为了你这样的访客,我特地保留了我的历史博文。不要笑话过去的我,用温柔的目光看下去吧。

For several reasons I don't want to use curl, and I have known that WordPress has methods for HTTP request, so I choose wp_remote_post(), which allows you to send an HTTP post request, and return an array. Here's the code example:

<?php
$upload_url = "URL_YOUR_UPLOAD_FILE_TO";
$local_file = "PATH/TO/FILE";
$filename = basename($local_file);
$name = $local_file;  //name of Form Control
$Boundary = wp_generate_password();  //split signal, see: https://www.ietf.org/rfc/rfc1867.txt
$bits = file_get_contents($local_file);

$args = array(
    "headers" => "Content-Type: multipart/form-data; boundary=$Boundary\r\n\r\nAuthorization: Basic $client_id\r\n\r\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97",
    "body" => "--$Boundary\r\nContent-Disposition: form-data; name=\"$name\"; filename=\"$filename\"\r\n\r\n$bits\r\n\r\n--$Boundary--"
);

$response = wp_remote_post($upload_url, $args);
if (!is_wp_error($response)) {
    $reply = $response["body"];  //the remote server's reply
    var_dump($reply);
}
?>

reference: https://www.jianshu.com/p/29e38bcc8a1d



恭喜,你成功屏蔽了广告 *这是一则由 Google AdSense 自动推荐的广告,不代表本站立场