how to upload media-image or featured-image in wordpress using rest api.
I've created new post using WordPress REST API, and now I am uploading Image to my Wordpress Site using REST API but i am unable to achieve it due to error "No data Supplied" kindly please Check Screenshot
which is the best way to create new post in WordPress with Featured Image, right now in my mind
Upload Media File to WordPress Site and Get Media ID
Create New Post with Media ID
you almost right, just lack media(image) raw binary data.
for python, using code:
import requests
toUploadImagePath = "/xxx/xxx.jpg"
mediaImageBytes = open(toUploadImagePath, 'rb').read()
# b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\.....'
uploadImageFilename = "661b943654f54bd4b2711264eb275e1b.jpg"
curHeaders = {
"Authorization": "Bearer xxx.yyy.zzz-xxx-yyy-zzz",
"Content-Type": "image/jpeg",
"Accept": "application/json",
'Content-Disposition': "attachment; filename=%s" % uploadImageFilename,
}
resp = requests.post(
"https://www.crifan.com/wp-json/wp/v2/media",
headers=curHeaders,
data=mediaBytes,
)
full code can refer my lib: crifanWordpress.py
and my Chinese post: 【已解决】用Python通过WordPress的REST API上传图片
(will publish in short future)
Using the REST API to upload a file to WordPress is quite simple. All you need is to send the file in a POST-Request to the wp/v2/media route.
UPDATED added data response true
$file = file_get_contents( 'test.jpg' );
$url = 'http://example.com/wp-json/wp/v2/media/';
$ch = curl_init();
$username = 'admin';
$password = 'password';
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $file );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt( $ch, CURLOPT_HTTPHEADER, [
'Content-Disposition: form-data; filename="example.jpg"',
'Authorization: Basic ' . base64_encode( $username . ':' . $password ),
] );
$result = curl_exec( $ch );
curl_close( $ch );
print_r( json_decode( $result ) );
MORE https://gist.github.com/ahmadawais/0ccb8a32ea795ffac4adfae84797c19a
Related
I would like to get the instance metadata (like AZ) for the current EC2, using AWS SDK.
I was able to find an alternative solution, but it is not using the SDK just a file_get_contents
How is it possible with the SDK?
The solution proposed by JasonQ-AWS is useful to get information about all instances and applications in your account. However, it does not tell you what information describes the instance that is really executed by the current process.
For that you have to use IMDSv2 which requires two CURL commands, the first one to get a TOKEN and the second one to get the actual metadata of the current instance.
In PHP the code can therefore be :
$ch = curl_init();
// get a valid TOKEN
$headers = array (
'X-aws-ec2-metadata-token-ttl-seconds: 10' );
$url = "http://169.254.169.254/latest/api/token";
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, "PUT" );
curl_setopt( $ch, CURLOPT_URL, $url );
$token = curl_exec( $ch );
echo "<p> TOKEN :" . $token;
// then get metadata of the current instance
$headers = array (
'X-aws-ec2-metadata-token: '.$token );
$url = "http://169.254.169.254/latest/dynamic/instance-identity/document";
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, "GET" );
$result = curl_exec( $ch );
echo "<p> RESULT :" . $result;
All you have to do is to extract the desired information. You can also ask for a unique information, such as the instance id with a more specific url like :
$url = "http://169.254.169.254/latest/meta-data/instance-id";
By current EC2 instance, are you referring to PHP code running on an EC2, and you would like to inject that metadata into some variables for use?
Or do you mean you have an object created with the PHP SDK such as with something like:
$ec2Client = new Aws\Ec2\Ec2Client([
'region' => 'us-east-1',
'version' => 'latest'
]);
If you mean the second way, you can access that data through describeInstances like this:
$result = $ec2Client->describeInstances();
echo "Instances: \n";
foreach ($result['Reservations'] as $reservation) {
foreach ($reservation['Instances'] as $instance) {
echo "InstanceId: {$instance['InstanceId']} - {$instance['State']['Name']} \n";
echo "Availability Zone: {$instance['Placement']['AvailabilityZone']} \n";
}
echo "\n";
}
You can also filter by adding parameters to the method call such as by type or instanceId.
If you're just running PHP code on the EC2 instance and you want that info, you can check out this page for some options: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-data-retrieval.html
I don't think this is possible at all. IMDSv2 info like AZ, instance-id, instance-type, etc is readable via https://169.254.169.254 and if you look into the source code for the SDK, it only pulls temporary credentials via IMDSv2 (https://github.com/aws/aws-sdk-php/search?q=169.254)
and does not allow arbitrary IMDSv2 queries.
Unless I'm missing something, you need to pull this data yourself or use some 3rd-party library which does that for you in PHP.
I am new to Livecode and I have tried couple of things to convert this php http post request code to Livecode but not working. Will need it either with cURL or without cURL.
$receive_momo_request = array(
'CustomerName' => 'Customer Name',
'CustomerMsisdn'=> '054XXXX',
'CustomerEmail'=> 'customer#gmail.com',
'Channel'=> 'mtn-gh',
'Amount'=> 0.8,
'PrimaryCallbackUrl'=> 'http://requestb.in/1minotz1',
'Description'=> 'T Shirt',
);
//API Keys
$clientId = 'xxxxxxx';
$clientSecret = 'xxxxxxx';
$basic_auth_key = 'Basic ' . base64_encode($clientId . ':' . $clientSecret);
$request_url = 'https://api.hubtel.com/v1/merchantaccount/merchants/HMXXXXXXX/receive/mobilemoney';
$receive_momo_request = json_encode($receive_momo_request);
$ch = curl_init($request_url);
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $receive_momo_request);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
'Authorization: '.$basic_auth_key,
'Cache-Control: no-cache',
'Content-Type: application/json',
));
$result = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
if($err){
echo $err;
}else{
echo $result;
}
This is what I have done so far may be am missing something.
on mouseUp
global gFirstName, gLastName
put gFirstName & " " & gLastName into lFullName
put lFullName into tArray[ "CustomerName"]
put "gPhoneNumber" into tArray["CustomerMsisdn"]
put "gEmail" into tArray["CustomerEmail"]
put "airtel-gh" into tArray["Channel"]
put "0.01" into tArray["Amount"]
put "http://requestb.in/1minotz1" into tArray["PrimaryCallbackUrl"]
put "FBMC Mobile" into tArray["Description"]
put true into tArray ["FeesOnCustomer"]
put ArrayToJSON(tArray) into receive_momo_request
put "ABCD" into clientId
put "1234" into clientSecret
set the httpHeaders to "Content-type: application/json" && "Authorization: Basic " && base64Encode("clientId:clientSecret") && "Cache-Control: no-cache"
post receive_momo_request to url "https://api.hubtel.com/v1/merchantaccount/merchants/HMXXXXXXX/receive/mobilemoney"
end mouseUp
Your LiveCode code looks good on first glance. I would try two things:
First, URLencode the data you are posting before you post it.
put ArrayToJSON(tArray) into receive_momo_request
put urlEncode(receive_momo_request) into receive_momo_request
Second, after the post command, check the itvariable to see what data was returned by the web server. You can also check the result to see if an error occurred.
post receive_momo_request to url "https://api.hubtel.com/v1/merchantaccount/merchants/HMXXXXXXX/receive/mobilemoney"
put it into tServerFeedback
answer the result
This should at least tell you what is happening after you issue the post command.
I am having trouble getting Google Cloud Messaging for Android working.
I have had it working before but it decides to stop working after the first couple of times.
In order to get it working again I have to delete my API key and recreate it.
I am using PHP with a SERVER API key with a IP whitelist of ::/0 (All IPv6 apparently)
Note: My android app requests a device message key each time the app is opened (Usually returns the same message key)
The Error I get is: Unauthorized Error 401
When I got to the following url to check my app message id i get 'invalid token'.
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=APA91bHuQEWGsvlRUhlSztNpqLVOZQGZPiGFHjQw2plcF-z8t29zvNNgNoDiRe-CbY9Fb-XcPQAFqJvy4HBfWTrTPPpzcY3pd5vX38WGalOsZ5iDiJeglpafLTC7eFkN4UA9JPKWZ4lqNiGLoH3w8W_GpFAFW5F-kLLzcbrPxwSFqyfUpmM8-14
The PHP code I am using is:
$data = array( 'message' => 'Hello World!222!' );
$ids = array('APA91bHuQEWGsvlRUhlSztNpqLVOZQGZPiGFHjQw2plcF-z8t29zvNNgNoDiRe-CbY9Fb-XcPQAFqJvy4HBfWTrTPPpzcY3pd5vX38WGalOsZ5iDiJeglpafLTC7eFkN4UA9JPKWZ4lqNiGLoH3w8W_GpFAFW5F-kLLzcbrPxwSFqyfUpmM8-14');
$apiKey = 'AIzaSyATkp_UTZh....'; //obviously the complete key is used...
$url = 'https://android.googleapis.com/gcm/send';
$post = array('registration_ids' => $ids, 'data' => $data);
$headers = array( 'Authorization: key=' . $apiKey, 'Content-Type: application/json');
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $post ) );
$result = curl_exec( $ch );
if ( curl_errno( $ch ) )
{
echo 'GCM error: ' . curl_error( $ch );
}
curl_close( $ch );
echo $result;
Thanks for any help given.
EDIT: It seems to work since I unregistered my device and reregistered it with GCM. I am not sure if this is a permanent fix but it works for now.
Writing an application that proxies a file upload. I'm using CURL to post the file but having a few problems. Posting to the script is ok, its posting from the script to the next server which is the problem. I keep getting this error from the server:
"the request was rejected because no multipart boundary was found"
here is my code:
$post = $_POST;
// allow for file upload proxying
if( !empty( $_FILES ) ){
// add to post data
foreach( $_FILES as $name => $upload ){
$post[ $name ] = '#' . $upload[ 'tmp_name' ] . ';type=image/png';
}
}
// init curl
$ch = curl_init( $url );
// configure options
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
// post data
if( !empty( $post ) ){
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $post );
// for file uploads, multi-part
curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
'Content-type: multipart/form-data;'
) );
}
// execute and get return value
$return = trim( curl_exec( $ch ) );
// cleanup
curl_close( $ch );
unset( $ch );
Everything I've read online suggests that this should work and also that setting the header content type is unnecessary, but when I remove the content type I get this error:
"the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is null"
any ideas? thanks in advance
Not sure exactly what the problem was, but I was working locally when I posted this. Moved the code onto a live server and the problem disappeared...
I want users to post an image on a facebook page via a form on a website.
When they have logged in via facebook on this website, they can select an image from their computer.
Once they have selected the image, I want it to be posted to the users wall, and in an album of the page where I'm one of the administrators.
I have created an app for this, but we can't seem to find a way to get the app to post on this facebook-page.
Do we need to set any permissions on this page or app?
To upload images to a facebook page of which you're an admin you need to do the following:
1.) Create a facebook application (the usual way), make sure you specify the Canvas URL
2.) Navigate to the url below logged in as the admin of the page, and give the permissions (user_photos,manage_pages,offline_access,publish_stream)
https://www.facebook.com/dialog/oauth?
client_id=<application_id>
&redirect_uri=<canvas_url>
&response_type=token
&scope=user_photos,manage_pages,offline_access,publish_stream
3.) When you give the application the required permissions you'll be redirected to canvas_url#access_token=*access_token*, for example
http://example.com/#access_token=awe12
4.) Then navigate to
https://graph.facebook.com/me/accounts?access_token=<access_token>
(use the access token from #3). This will list the pages you administer; write down the access_token for the page(s) to which you want to upload the image
I'm not 100% sure but I believe that using graph api you can upload images only to albums created via graph api; i.e. you need to first create an album via graph api. Here's sample code using curl:
$uri = sprintf(
'https://graph.facebook.com/%1$s/albums?access_token=%2$s',
$page_id,
$access_token
);
$post_fields = array(
'name' => trim( $album_name )
);
$curl = curl_init( $uri );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $curl, CURLOPT_POST, TRUE );
curl_setopt( $curl, CURLOPT_POSTFIELDS, $post_fields );
$raw_data = curl_exec( $curl );
curl_close( $curl );
$data = json_decode( $raw_data, $assoc = TRUE );
The $data above will contain the album id, which you'll need to upload a photo:
// prepare the curl post fields
$batch = sprintf(
'[{"method":"POST", "relative_url":"%1$s/photos", "attached_files":"file1"}]',
$album_id
);
$post_fields = array(
'batch' => $batch,
'access_token' => $access_token,
'file1' => '#' . $image_abs_path
);
$uri = 'https://graph.facebook.com';
$curl = curl_init( $uri );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $curl, CURLOPT_POST, TRUE );
curl_setopt( $curl, CURLOPT_POSTFIELDS, $post_fields );
$raw_data = curl_exec( $curl );
curl_close( $curl );
$data = json_decode( $raw_data, $assoc = TRUE );