I'm trying, without success, to get some results using Bing's Image search API without HTTP/Request2.php component (as used in the official examples).
I understand that the only two required parameters to make a very primitive call are q which is the query string and the subscription key. The key must be sent using headers. After looking around I found this very simple example to send headers with PHP:
$sURL = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=cats";
$aHTTP = array(
'Ocp-Apim-Subscription-Key' => 'xxxxxxx',
);
$context = stream_context_create($aHTTP);
$contents = file_get_contents($sURL, false, $context);
echo $contents;
But it does not output anything. Would you kindly help me with a very basic example of use of Bing's API?
SOLVED
Thanks to Vadim's hint I changed the way headers are sent and now output is a Json encoded result. (Remember to add your API subscription key.)
$sURL = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=cats";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sURL);
curl_setopt($ch, CURLOPT_TIMEOUT, '1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: multipart/form-data',
'Ocp-Apim-Subscription-Key: xxxxx'
));
$content = curl_exec($ch);
echo $content;
Just another tip. The syntax of query filters and other parameters change form version to version. For example the following work correctly in version 5.0:
To search only for JPEG images of cats and get 30 results use:
q=cats&encodingFormat='jpeg'&count=30
To search only for 'portrait' aspect images with size between 200x200 and 500x500 use:
q=cats&aspect=Tall&size=Medium
Try using cURL
$sURL = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=cats";
$key = "xxxxxxx";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sURL);
curl_setopt($ch, CURLOPT_TIMEOUT, '1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 'ocp-apim-subscription-key:$key');
$content = curl_exec($ch);
echo $content;
Here is my working code..
Replace ******** with your bing subscription key.
$sURL = "https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=microsoft-surface&count=6&mkt=en-US";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: multipart/form-data',
'Ocp-Apim-Subscription-Key: *******************'
));
$contents = curl_exec($ch);
$myContents = json_decode($contents);
if(count($myContents->value) > 0) {
foreach ($myContents->value as $imageContent) {
echo '<pre/>';
print_r($imageContent);
}
}
Related
I have the same problem as here How to get results from Udemy Api with search? which unfortunately doesn't have an answer.
I'm able to retrieved the title etc, from this URL for example, https://www.udemy.com/api-2.0/courses/238934/?fields[course]=#all (you'll see the results in your browser) this URL works as well https://www.udemy.com/api-2.0/search-suggestions?q=java but not this one https://www.udemy.com/api-2.0/courses/?search=java
As mentioned here https://www.udemy.com/developers/affiliate/methods/get-courses-list/
get /api-2.0/courses/?search=java should work?
Here is my code:
$url = "https://www.udemy.com/api-2.0/courses/?search=java";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$c_id = base64_encode('XXX');
$c_sid = base64_encode('XXX');
curl_setopt($ch,CURLOPT_HTTPHEADER,array('X-Udemy-Client-Id: '.$c_id.'','X-Udemy-Client-Secret: '.$c_sid.'',"Authorization: base64 encoded value of client-id:client-secret","Accept: application/json, text/plain, */*"));
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
$result=curl_exec($ch);
curl_close($ch);
$result = json_decode($result);
$title = $result->title;
If someone could please shed some light on this.
Based on ADyson comments, here is the answer (just update the code with your own clientID and clientSecret ID from Udemy):
I've basically updated the CURLOPT_HTTPHEADER:
Code:
$url = "https://www.udemy.com/api-2.0/courses/?search=java";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
//HTTP username.
$clientID = 'XXX';
//HTTP password.
$clientSecret = 'XXX';
//Create the headers array.
$headers = array(
'Content-Type: application/json',
'Authorization: Basic '. base64_encode("$clientID:$clientSecret")
);
//Set the headers that we want our cURL client to use.
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
$result=curl_exec($ch);
// echo curl_getinfo($ch, CURLINFO_HEADER_OUT);
// echo curl_getinfo($ch,CURLINFO_HTTP_CODE);
curl_close($ch);
$json = json_decode($result, true);
// return $result;
foreach($json['results'] as $results) {
$title = $results['title'];
echo $title.'<br>';
}
Results: (Course titles based on this search: https://www.udemy.com/api-2.0/courses/?search=java)
Java Programming Masterclass for Software Developers
Java Programming for Complete Beginners
Java In-Depth: Become a Complete Java Engineer!
The Complete Java Certification Course
Etc.
I have rest API of Nodejs Server, I'm trying to make a POST call to it using PHP.
My php code is:
function post_url($apiRoute,$data) {
$request_url = 'http://test-app.herokuapp.com';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request_url . $apiRoute);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
echo $data ;
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
I have tried calling this function with diff forms of data:
$g = array("_id" => "111");
$postapiresponse = post_url('/CCTRequest/get',json_encode($g));
OR
$postapiresponse = post_url('/CCTRequest/get',json_encode(array("_id" => "111"));
But on server side which Node.js, when I console log req.body I get data like this:
{ '{"_id":"111"}': '' }
How should I pass the data in PHP so I can get proper obj in node.js i.e:
{ '_id': '111' }
See the PHP document:
http://php.net/manual/en/function.curl-setopt.php
CURLOPT_POST:
TRUE to do a regular HTTP POST. This POST is the normal
application/x-www-form-urlencoded kind, most commonly used by HTML forms.
CURLOPT_POSTFIELDS:
If value is an array, the Content-Type header will be set to multipart/form-data.
So you can pass a query string returned by http_build_query() into CURLOPT_POSTFIELDS:
post_url('/CCTRequest/get', http_build_query($g, null, '&'));
and remove curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));. (In fact, the varieble should be $ch, but you typed $curl, so this line doesn't work.)
In the other way, you can replace curl_setopt($ch, CURLOPT_POST, 1); with
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');, it can prevent the data be encoded automaticlly. And then send json_encode() data.
I have solved by using http_build_query($g, null, '&') for making data.
$g = array("_id" => "111");
$g = http_build_query($g, null, '&');
$postapiresponse = post_url('/CCTRequest/get', $g);
You have a typo in the code, which will prevent it setting the header $curl should be $ch:
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
You also need CURLOPT_RETURNTRANSFER uncommented.
function post_url($apiRoute, $data) {
$request_url = 'www.example.com';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $request_url . $apiRoute);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
I'm in the process of testing the new Bing Custom Search using below PHP code. The result is a blank white screen with no errors. Is it because this service is still in beta mode?
<?php
$sURL = "https://api.cognitive.microsoft.com/bingcustomsearch/v5.0/search?q=dogs&customconfig=[mycustomconfigvalue]&responseFilter=Webpages&mkt=en-us&safesearch=Moderate";
$key = "[myPrimaryKey]";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sURL);
curl_setopt($ch, CURLOPT_TIMEOUT, '1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 'ocp-apim-subscription-key:$key');
$content = curl_exec($ch);
echo $content;
?>
When I try to verify if API keys are working for me using Postman, I get an error saying "Could n ot get any response".
However, if I try the same values in https://customsearch.ai under endpoint section, it works perfectly by displaying the response.
Can anyone please let me know I can't run the code using my own PHP code?
Thanks
3 Errors:
1 - CURLOPT_HEADER is different from CURLOPT_HTTPHEADER.
2 - CURLOPT_HTTPHEADER takes an array as argument, not a string.
3 - Variables ($key) only expand inside double quotes.
Try:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sURL);
curl_setopt($ch, CURLOPT_TIMEOUT, 1); # you may want increase this value
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["ocp-apim-subscription-key:$key"]);
$content = curl_exec($ch);
I replied this somewhere. Here is a working php snippet. Just replace YOUR_QUERY, YOUR_KEY, and YOUR_CUSTOMCONFIG.
$endpoint = 'https://api.cognitive.microsoft.com/bingcustomsearch/v7.0/search';
$term = 'YOUR_QUERY';
$headers = "Ocp-Apim-Subscription-Key: YOUR_KEY\r\n";
$options = array ('http' => array (
'header' => $headers,
'method' => 'GET'));
$context = stream_context_create($options);
$result = file_get_contents($url . "?q=" . urlencode($query) . "&customconfig=YOUR_CUSTOMCONFIG&responseFilter=Webpages&mkt=en-us&safesearch=Moderate", false, $context);
I have been working on building an Rest API for the hell of it and I have been testing it out as I go along by using curl from the command line which is very easy for CRUD
I can successfully make these call from the command line
curl -u username:pass -X GET http://api.mysite.com/pet/1
curl -d '{"dog":"tall"}' -u username:pass -X GET http://api.mysite.com/pet
curl -d '{"dog":"short"}' -u username:pass -X POST http://api.mysite.com/pet
curl -d '{"dog":"tall"}' -u username:pass -X PUT http://api.mysite.com/pet/1
The above calls are easy to make from the command line and work fine with my api, but now I want to use PHP to create the curl. As you can see, I pass data as a json string. I have read around and I think I can probably do the POST and include the POST fields, but I have not been able to find out how to pass http body data with GET. Everything I see says you must attached it to the url, but it doesn't look that way on the command line form. Any way, I would love it if someone could write the correct way to do these four operations in PHP here on one page. I would like to see the simplest way to do it with curl and php. I think I need to pass everything through the http body because my php api catching everything with php://input
PUT
$data = array('username'=>'dog','password'=>'tall');
$data_json = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
POST
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
GET
See #Dan H answer
DELETE
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
You can use this small library: https://github.com/ledfusion/php-rest-curl
Making a call is as simple as:
// GET
$result = RestCurl::get($URL, array('id' => 12345678));
// POST
$result = RestCurl::post($URL, array('name' => 'John'));
// PUT
$result = RestCurl::put($URL, array('$set' => array('lastName' => "Smith")));
// DELETE
$result = RestCurl::delete($URL);
And for the $result variable:
$result['status'] is the HTTP response code
$result['data'] an array with the JSON response parsed
$result['header'] a string with the response headers
Hope it helps
For myself, I just encode it in the url and use $_GET on the destination page. Here's a line as an example.
$ch = curl_init();
$this->json->p->method = "whatever";
curl_setopt($ch, CURLOPT_URL, "http://" . $_SERVER['SERVER_NAME'] . $this->json->path . '?json=' . urlencode(json_encode($this->json->p)));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
EDIT: Adding the destination snippet... (EDIT 2 added more above at OPs request)
<?php
if(!isset($_GET['json']))
die("FAILURE");
$json = json_decode($_GET['json']);
$method = $json->method;
...
?>
I was Working with Elastic SQL plugin.
Query is done with GET method using cURL as below:
curl -XGET http://localhost:9200/_sql/_explain -H 'Content-Type: application/json' \
-d 'SELECT city.keyword as city FROM routes group by city.keyword order by city'
I exposed a custom port at public server, doing a reverse proxy with Basic Auth set.
This code, works fine plus Basic Auth Header:
$host = 'http://myhost.com:9200';
$uri = "/_sql/_explain";
$auth = "john:doe";
$data = "SELECT city.keyword as city FROM routes group by city.keyword order by city";
function restCurl($host, $uri, $data = null, $auth = null, $method = 'DELETE'){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host.$uri);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($method == 'POST')
curl_setopt($ch, CURLOPT_POST, 1);
if ($auth)
curl_setopt($ch, CURLOPT_USERPWD, $auth);
if (strlen($data) > 0)
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$resp = curl_exec($ch);
if(!$resp){
$resp = (json_encode(array(array("error" => curl_error($ch), "code" => curl_errno($ch)))));
}
curl_close($ch);
return $resp;
}
$resp = restCurl($host, $uri); //DELETE
$resp = restCurl($host, $uri, $data, $auth, 'GET'); //GET
$resp = restCurl($host, $uri, $data, $auth, 'POST'); //POST
$resp = restCurl($host, $uri, $data, $auth, 'PUT'); //PUT
set one more property curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , false);
Using PHP cURL and Symfony 1.4.2
I'm trying to do a PUT request including data (JSON) to modify an object in my REST web services, but can't catch the data on the server side.
It seems that the content is attached successfully when checking at my logs:
PUT to http://localhost:8080/apiapp_test.php/v1/reports/498 with post body content=%7B%22report%22%3A%7B%22title%22%3A%22The+title+has+been+updated%22%7D%7D
I attached the data like this:
$curl_opts = array(
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => http_build_query(array('content' => $post_data)),
);
And wanted to get the data using something like this
$payload = $request->getPostParameter('content');
It is not working and I've tried many ways to get this data in my actions file.
I've tried the following solutions:
parse_str(file_get_contents("php://input"), $post_vars);
$payload = $post_vars['content'];
// or
$data = $request->getContent(); // $request => sfWebRequest
$payload = $data['content'];
// or
$payload = $request->getPostParameter('content');
// then I'd like to do that
$json_array = json_decode($payload, true);
I just don't know how to get this data in my actions and it's frustrating, I've read many topics here about it but none is working for me.
Additional informations:
I have these setup for my cURL request:
curl_setopt($curl_request, CURLOPT_CUSTOMREQUEST, $http_method);
if ($http_method === sfRequest::PUT) {
curl_setopt($curl_request, CURLOPT_PUT, true);
$content_length = array_key_exists(CURLOPT_POSTFIELDS, $curl_options) ? strlen($curl_options[CURLOPT_POSTFIELDS]) : 0;
$curl_options[CURLOPT_HTTPHEADER][] = 'Content-Length: ' . $content_length;
}
curl_setopt($curl_request, CURLOPT_URL, $url);
curl_setopt($curl_request, CURLOPT_CONNECTTIMEOUT, 4);
curl_setopt($curl_request, CURLOPT_TIMEOUT, 4);
curl_setopt($curl_request, CURLOPT_DNS_CACHE_TIMEOUT, 0);
curl_setopt($curl_request, CURLOPT_NOSIGNAL, true);
curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, true);
In sfWebRequest.php, I've seen this:
case 'PUT':
$this->setMethod(self::PUT);
if ('application/x-www-form-urlencoded' === $this->getContentType())
{
parse_str($this->getContent(), $postParameters);
}
break;
So I tried to set the header's Content-Type to it but it doesn't do anything.
If you have any idea, please help!
According to an other question/answer, I've tested this solution and I got the correct result:
$body = 'the RAW data string I want to send';
/** use a max of 256KB of RAM before going to disk */
$fp = fopen('php://temp/maxmemory:256000', 'w');
if (!$fp) {
die('could not open temp memory data');
}
fwrite($fp, $body);
fseek($fp, 0);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PUT, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_INFILE, $fp); // file pointer
curl_setopt($ch, CURLOPT_INFILESIZE, strlen($body));
$output = curl_exec($ch);
echo $output;
die();
And on the other side, you can retrieve the content using:
$content = $request->getContent();
If you var_dump it, you will retrieve:
the RAW data string I want to send