wordpress rest api 授权
Posted
技术标签:
【中文标题】wordpress rest api 授权【英文标题】:wordpress rest api Authorization 【发布时间】:2019-01-16 01:11:32 【问题描述】:您好,我使用此代码通过 api 在 wordpress 中上传图片
我的代码:
<?php
$file = $_FILES["RESULT_FileUpload-6"]["tmp_name"];
$url = 'http://tst.com/wp-json/wp/v2/media/';
$ch = curl_init();
$username = 'username';
$password = '123456';
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $file );
curl_setopt( $ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Disposition: form-data; filename="'.$_FILES["RESULT_FileUpload-6"]["name"].'"',
'Authorization: Basic ' . base64_encode( $username . ':' . $password ),
] );
$result = curl_exec( $ch );
curl_close( $ch );
print_r( json_decode( $result ) );
?>
但当我使用此代码时显示错误 401“rest_cannot_create”
我使用正确的用户名和密码(wordpress 管理面板的用户名和密码)
Authorization rest api wordpress 还有其他方法吗??
【问题讨论】:
【参考方案1】:尝试将其添加到 htaccess 文件中:
RewriteRule ^index\.php$ - [E=HTTP_AUTHORIZATION:%HTTP:Authorization,L]
【讨论】:
【参考方案2】:我必须上传 pdf 文件。这将帮助您将任何文件上传到自定义目录
public function uploadFiles(WP_REST_Request $request)
if(checkloggedinuser())
if ( ($request->get_file_params('file')))
$upload_dir = wp_upload_dir();
$user_id = checkloggedinuser();
$timestamp = time();
if ( ! empty( $upload_dir['basedir'] ) )
$user_dirname = $upload_dir['basedir'].'/customize-files';
if ( ! file_exists( $user_dirname ) )
wp_mkdir_p( $user_dirname );
$filename_maker = $user_id.'_'.$timestamp.'_'.$_FILES['file']['name'];
$filename = wp_unique_filename( $user_dirname, $filename_maker );
// return $filename_maker;
$check = move_uploaded_file($_FILES['file']['tmp_name'], $user_dirname .'/'. $filename);
// save into database $upload_dir['baseurl'].'/product-images/'.$filename;
if($check)
$path = $upload_dir['baseurl'].'/customize-files/'.$filename_maker;
return array(
'success' => true,
'responsecode' => 200,
"message" => "File Uploaded Successfully",
"data" => [
"path" => $path,
],
);
else
return array(
'success' => false,
'responsecode' => 403,
"message" => "Please Provide File",
"data" => [],
);
else
return array(
'success' => false,
'responsecode' => 403,
"message" => "Please Logged In to get Data",
"data" => [],
);
【讨论】:
以上是关于wordpress rest api 授权的主要内容,如果未能解决你的问题,请参考以下文章
wp rest api 授权方法步骤(使用JWT Authentication插件)
[CVE-2017-5487] WordPress <=4.7.1 REST API 内容注入漏洞分析与复现