Upload an image in wordpress using REST API - php

Using rest api i can create a post, get blog category etc. but i cannot upload an image i am referring
https://github.com/WP-API/client-php/blob/master/library/WPAPI/Media.php
and
http://wp-api.org/#entities_media-meta_width
and my code is
$data = array('file'=>$filePath,'is_image'=>true);
print_r($data);
$headers = array('Content-Type' => 'application/octet-stream');
$response = $this->api->post(WPAPI::ROUTE_MEDIA, $headers, $data);
they talk about [$data in $response = $this->api->post(WPAPI::ROUTE_MEDIA, $headers, $data);]
what are the key value pairs used in $data?

Finally, I fixed it myself:
specify the file path
put necessary headers
send post request
Here is the code:
$filePath = 'URL of image'; //right click your fav img and copy url.
$imageData = #file_get_contents($filePath); //get image content
$headers = array('Content-Type' => 'application/json; charset= UTF-8',
'Content-Disposition' => 'attachment; filename='.basename($filepath)');
$response = $this->api->post('/wp-json/media', $headers, $imageData);
print_r($response);
Check the WordPress Media Gallery.
Enjoy!

try this.
1 open chrome browser.
2 install apps (https://chrome.google.com/webstore/search/rest%20client?utm_source=chrome-ntp-icon)
3 open this apps and use
Screenshort

Related

How to set referer Header in Guzzle and get CDN Content

I want to scrape a website and am using guzzle 7.4 and Symfony Dom Crawler
I successfully retrieved the HTML data But the website is using CDN to host some resources and they are not loading because the header is not sent to get those resources
below is code retrieving html
<?php
require "vendor/autoload.php";
use Symfony\Component\DomCrawler\Crawler;
// Url
$url = 'scrapingdomain.com';
$headers = [
'referer' => 'examplescrapingdomain.com'
];
$client = new \GuzzleHttp\Client([
'headers' => $headers
]);
// go get the data from url
$response = $client->request('GET', $url);
$html = ''.$response->getBody();
$crawler = new Crawler($html);
echo $html;
?>
If I access the CDN directly and set referer header I get a response of 200
Below Code
<?php
require "vendor/autoload.php";
use Symfony\Component\DomCrawler\Crawler;
// Url
$url = 'examplecdnresource.com/Images.png';
$headers = [
'referer' => 'examplescrapingdomain.com'
];
$client = new \GuzzleHttp\Client([
'headers' => $headers
]);
// go get the data from url
$response = $client->request('GET', $url);
$html = ''.$response->getBody();
$crawler = new Crawler($html);
echo $html;
?>
I want to get the scrapdomain.com get resources and download the cdn hosted images that it has
All I needed to do to get the CDN hosted content inside the scraped html is use file_get_content function and set referer stream to download the data no inside guzzle as i was getting css and image files

How to Send File(pdf) from Local Computer to API Whatsapp (Chat-API)

Greatings,
Today i Want to Make some task to upload some pdf file using Chat-API whatsapp.
the task maybe I will Run on windows shell, but now I test it on PHP file.
I using the documentation like this
$to = 'myPhone';
$url = 'https://chat-apiurl?andtokenhere';
$imageLocation = 'http://localhost/chat-api/file.pdf';
$data = [
'phone'=> $to,
'body' =>$imageLocation,
'filename'=>"filepdf.jpg",
'caption'=>'test',
];
$send = json_encode($data);
$options = stream_context_create(['http' => [
'method' => 'POST',
'header' => 'Content-type: application/json',
'content' => $send,
]
]);
// Send a request
$result = file_get_contents($url, false, $options);
echo $result;
?>
if i change the file to online url that's work fine, but when using local file I got the error on result like that
{"error":"Unsupported file type"}
I Have try to convert my file to base 64 but that's return error like this
{"sent":false,"message":"Message was not sent: empty body. Please provide message text in body parameter in JSON POST."}
and that's the way i convert to base64
$getExtension = explode(".",$imageLocation);
$base64 = 'data:image/'.$getExtension[1].';base64,'.file_get_contents($imageLocation);
can anyone help me to send the local file? or maybe have other way to do that. or other API?
Thankyou so much
I know the question was posted a long time ago, but I'll leave the answer in case anyone is looking for a solution.
$base64='data:image/'.$getExtension[1].';base64,'.file_get_contents($imageLocation);
for:
$base64='data:image/'.$getExtension[1].';base64,'.base64_encode(file_get_contents($imageLocation));

"Invalid content-type specified" when uploading file to Apigility

I'm a building a RPC API using Zend Framework 2 and Apigility by Zend Framework. For testing, I use the chrome extension Postman REST-Client.
I can do POST requests without problems when I use Postman.
But my code doesn't work.
$client = new \Zend\Http\Client();
$client->setUri($uri)
->setMethod('POST')
->setParameterPost(
array(
'file' => '/home/user/Downloads/file.csv'
)
);
$headers = new \Zend\Http\Headers();
$headers->addHeaders(array(
'Accept' => 'application/json;',
));
$client->setHeaders($headers);
$client->setStream();
$response = $client->send();
$file = '/home/user/Downloads/file.csv';
$file2 = '/home/user/Downloads/file2.csv';
copy($response->getStreamName(), $file);
$fp = fopen($file2, "w");
stream_copy_to_stream($response->getStream(), $fp);
$client->setStream($file);
$responce = $client->send();
echo $responce->getBody();
I tried to pass other headers Content-Type, but it leads to Fatal error.
What do I need to pass the headers to make it work?
You have to set your Content-Type header to multipart/form-data. The Postman add-on you are using in Chrome does this automatically for file uploads.
So set your headers like this:
$headers->addHeaders(array(
'Accept' => 'application/json',
'Content-Type' => 'multipart/form-data'
));
If that doesn't work please be more specific about the fatal error you get.

PHP Upload Image from URL to Facebook [duplicate]

I'm trying to upload www hosted (e.g. http://www.google.se/intl/en_com/images/srpr/logo1w.png) files to a facebook album.
Creating an album works just fine, but I don't seem to uploading any photos. I'm using the facebook php-sdk ( http://github.com/facebook/php-sdk/ ) and the examples I already tried are:
Upload Photo To Album with Facebook's Graph API
How can I upload photos to album using Facebook Graph API
I'm guessing CURL uploads perhaps only can manage locally stored files and not web hosted ones.
Here's my code:
/*
Try 1:
$data = array();
$data['message'] = $attachment->post_title;
$data['file'] = $attachment->guid;
try {
$photo = $facebook->api('/' . $album['id'] . '/photos?access_token=' . $session['access_token'], 'post', $data);
} catch (FacebookApiException $e) {
error_log($e);
}
*/
// Try 2:
//upload photo
$file = $attachment->guid;
$args = array(
'message' => 'Photo from application',
);
$args[basename($file)] = '#' . realpath(file_get_contents($file));
$ch = curl_init();
$url = 'https://graph.facebook.com/' . $album['id'] . '/photos?access_token=' . $session['access_token'];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
$data = curl_exec($ch);
//returns the photo id
print_r(json_decode($data,true));
...where attachment->guid contains the photo url.
I'm pretty much stuck right now...
i think the problem is here:
$args[basename($file)] = '#' . realpath(file_get_contents($file));
since you want to post a picture from another source (right?), you should save it temporarily on your own host.
i also needed to do something like this, and since i had to process the image, i used the following way:
$im = #imagecreatefrompng('http://www.google.se/intl/en_com/images/srpr/logo1w.png');
imagejpeg($im, 'imgs/temp/temp.jpg', 85);
$args['image'] = '#' . realpath('imgs/temp/temp.jpg');
the rest looks fine though
I'll suggest to use the Facebook php SDK, it will be easier and the code will work with future updates of the APIs:
Using the Graph API php sdk:
$fbk = new Facebook(/* conf */);
$fbk->setFileUploadSupport(true);
//If you are executing this in a script, and not in a web page with the user logged in:
$fbk->setAccessToken(/* access token from other sources */);
//To add to an album:
$fbk->api("/$albumId/photos", "POST",
array('source' => '#'. realpath($myPhoto), 'message' => "Nice photo"));
//To upload a photo directly (the album will be created automatically):
$fbk->api("/me/photos", "POST",
array('source' => '#'. realpath($myPhoto), 'message' => "Nice photo"));
Using cURL directly:
If your really want to use cURL, your code is almost correct, but the error is in the $args array:
$args = array(
'message' => 'Photo from application',
'source' => file_get_contents($file)
);
Since the key for the photo data is source, see the Facebook Doc
Note on the # in cURL:
Also notice that the # in cUrl means that the parameter will be replaced with the actual bytes of the file that follows the #, so it isn't required if you already put in the source parameter the actual bytes.
I'm guessing CURL uploads perhaps only can manage locally stored files and not web hosted ones.
No, that’s not the case.
But you need to give the full, publicly reachable HTTP URL to the image, without an # in front – and you have to use the parameter name url for this value.
https://developers.facebook.com/docs/reference/api/photo/:
You can also publish a photo by providing a url param with the photo's URL.

PHP - Upload a web hosted photo to facebook album via Graph API

I'm trying to upload www hosted (e.g. http://www.google.se/intl/en_com/images/srpr/logo1w.png) files to a facebook album.
Creating an album works just fine, but I don't seem to uploading any photos. I'm using the facebook php-sdk ( http://github.com/facebook/php-sdk/ ) and the examples I already tried are:
Upload Photo To Album with Facebook's Graph API
How can I upload photos to album using Facebook Graph API
I'm guessing CURL uploads perhaps only can manage locally stored files and not web hosted ones.
Here's my code:
/*
Try 1:
$data = array();
$data['message'] = $attachment->post_title;
$data['file'] = $attachment->guid;
try {
$photo = $facebook->api('/' . $album['id'] . '/photos?access_token=' . $session['access_token'], 'post', $data);
} catch (FacebookApiException $e) {
error_log($e);
}
*/
// Try 2:
//upload photo
$file = $attachment->guid;
$args = array(
'message' => 'Photo from application',
);
$args[basename($file)] = '#' . realpath(file_get_contents($file));
$ch = curl_init();
$url = 'https://graph.facebook.com/' . $album['id'] . '/photos?access_token=' . $session['access_token'];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
$data = curl_exec($ch);
//returns the photo id
print_r(json_decode($data,true));
...where attachment->guid contains the photo url.
I'm pretty much stuck right now...
i think the problem is here:
$args[basename($file)] = '#' . realpath(file_get_contents($file));
since you want to post a picture from another source (right?), you should save it temporarily on your own host.
i also needed to do something like this, and since i had to process the image, i used the following way:
$im = #imagecreatefrompng('http://www.google.se/intl/en_com/images/srpr/logo1w.png');
imagejpeg($im, 'imgs/temp/temp.jpg', 85);
$args['image'] = '#' . realpath('imgs/temp/temp.jpg');
the rest looks fine though
I'll suggest to use the Facebook php SDK, it will be easier and the code will work with future updates of the APIs:
Using the Graph API php sdk:
$fbk = new Facebook(/* conf */);
$fbk->setFileUploadSupport(true);
//If you are executing this in a script, and not in a web page with the user logged in:
$fbk->setAccessToken(/* access token from other sources */);
//To add to an album:
$fbk->api("/$albumId/photos", "POST",
array('source' => '#'. realpath($myPhoto), 'message' => "Nice photo"));
//To upload a photo directly (the album will be created automatically):
$fbk->api("/me/photos", "POST",
array('source' => '#'. realpath($myPhoto), 'message' => "Nice photo"));
Using cURL directly:
If your really want to use cURL, your code is almost correct, but the error is in the $args array:
$args = array(
'message' => 'Photo from application',
'source' => file_get_contents($file)
);
Since the key for the photo data is source, see the Facebook Doc
Note on the # in cURL:
Also notice that the # in cUrl means that the parameter will be replaced with the actual bytes of the file that follows the #, so it isn't required if you already put in the source parameter the actual bytes.
I'm guessing CURL uploads perhaps only can manage locally stored files and not web hosted ones.
No, that’s not the case.
But you need to give the full, publicly reachable HTTP URL to the image, without an # in front – and you have to use the parameter name url for this value.
https://developers.facebook.com/docs/reference/api/photo/:
You can also publish a photo by providing a url param with the photo's URL.

Categories