Posting file via wp_remote_post

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

提醒:本文最后更新于 892 天前,文中所描述的信息可能已发生改变,请谨慎使用!

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:

$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:
$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


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