Authentication error trying to upload image using WordPress 5.8.1 API
-
I have setup basic authentication using the plugin WP Basic Authentication and confirmed it’s working properly.
The code for getting all the images from the site using the API
<?php $login = base64_encode("Username:Password"); $url = 'https://mysite.org.il/wp-json/wp/v2/media'; $ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, $url ); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_VERBOSE, true); curl_setopt( $ch, CURLOPT_HTTPHEADER, [ 'Authorization: Basic ' . $login, ] ); $result = curl_exec( $ch ); curl_close( $ch ); print_r( json_decode( $result ) ); ?>
Posting using the following code returns the error
stdClass Object ( [code] => rest_cannot_create [message] => Sorry, you are not allowed to create posts as this user. [data] => stdClass Object ( [status] => 401 ) )
The user is the only user defined in the site so it's the admin.
This is the upload code
<?php $filename = "IMG_0965.jpg"; $login = base64_encode("Username:Password"); $file = file_get_contents( $filename ); $mime = mime_content_type( $filename ); $url = 'https://mysite.org.il/wp-json/wp/v2/media'; $ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, $url ); curl_setopt( $ch, CURLOPT_POST, 1 ); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt( $ch, CURLOPT_POSTFIELDS, $file ); curl_setopt($ch, CURLOPT_VERBOSE, true); curl_setopt( $ch, CURLOPT_HTTPHEADER, [ 'Content-Type: '.$mime, 'Content-Disposition: attachment; filename="'.$filename.'"', 'Authorization: Basic ' . $login, ] ); $result = curl_exec( $ch ); curl_close( $ch ); print_r( json_decode( $result ) ); ?>
Any help with understanding the problem and how to fix this will be much appreciated.
- The topic ‘Authentication error trying to upload image using WordPress 5.8.1 API’ is closed to new replies.