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);
Related
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);
}
}
I am using Jira's API to add an attachment file to a case. My issue is after my code attaches a file, and I go to the JIRA case to confirm, I see two things. First, if it is an image, I can see a thumbnail of the image. If I click it, though, I get an error saying "The requested content cannot be loaded. Please try again." Second, under the thumbnail, instead of showing the name of the file, it has the path that the file was originally uploaded from (id: c:/wamp/www/...." Is there a reason this is happening? Here is my code:
$ch = curl_init();
$header = array(
'Content-Type: multipart/form-data',
'X-Atlassian-Token: no-check'
);
$attachmentPath = $this->get_file_uploads();
//$attachmentPath comes out to be something like:
//c:/wamp/www/mySite/web/system/files/my_folder/DSC_0344_3.JPG
$data = array('file'=>"#". $attachmentPath, 'filename'=>'DSC_0344_3.JPG');
$url= 'https://mysite.atlassian.net/rest/api/2/issue/20612/attachments/';
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS ,$data);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "myusername:mypassword");
$result = curl_exec($ch);
$ch_error = curl_error($ch);
Once the file gets added to Jira, when I log into jira, I can see the thumbnail but the title under the file is something like: c:/wamp/www/mySite/web/system/files/my_folder/DSC_0344_3.JPG instead of the file name.
thanks
You need to use:
$data = array('file'=>"#". $attachmentPath . ';filename=DSC_0344_3.JPG');
It is an issue in PHP cURL <5.5.0 but > 5.2.10, see JIRA API attachment names contain the whole paths of the posted files
When using PHP >= 5.5.0 it is better to switch to the CURLFile approach as also documented in that link.
$cfile = new CURLFile($attachmentPath);
$cfile->setPostFilename('DSC_0344_3.JPG');
$data = array('file'=>$cfile);
For anybody in the future: here's a function i wrote that works on php 7
function attachFileToIssue($issueURL, $attachmentURL) {
// issueURL will be something like this: http://{yourdomainforjira}.com/rest/api/2/issue/{key}/attachments
// $attachmentURL will be real path to file (i.e. C:\hereswheremyfilelives\fileName.jpg) NOTE: Local paths ("./fileName.jpg") does not work!
$ch = curl_init();
$headers = array(
'X-Atlassian-Token: nocheck',
'Content-type: multipart/form-data'
);
$cfile = new CURLFile($attachmentURL);
$cfile->setPostFilename(basename($attachmentURL));
$data = array("file" => $cfile);
curl_setopt_array(
$ch,
array(
CURLOPT_URL => $issueURL,
CURLOPT_VERBOSE => 1,
CURLOPT_POSTFIELDS => $data,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_USERPWD => "{username}:{password}"
)
);
$result = curl_exec($ch);
$ch_error = curl_error($ch);
if ($ch_error)
echo "cURL Error: " . $ch_error;
curl_close($ch);
}
I just want to use "file_get_html" to get content of specific pages, but this content just avaiable for loggin user, is there any way to send cookie to let target site know that the page is accessed by logged in user.
require_once 'simple_html_dom.php';
$opts = array("Cookie: __qca=P0-1170249003-1395413811270"); //__qca=P0-1170249003-1395413811270
$current_url = 'http://abc.xyz';
// But it will be redirect to
$url = 'http://www.blogger.com/blogin.g?blogspotURL=http://abc.xyz'
$context = stream_context_create($opts);
$html = file_get_html($url, FALSE, $context);
echo $html;
I do something like this, but it doesn't work.
How Can I do this with Curl?
Thanks.
$ch = curl_init(); // your curl instance
curl_setopt_array($ch, [CURLOPT_URL => "http://www.blogger.com/blogin.g?blogspotURL=http://abc.xyz", CURLOPT_COOKIE => "__qca=P0-1170249003-1395413811270"], CURLOPT_RETURNTRANSFER => true]);
$result = curl_exec($ch); // request's result
$html = new simple_html_dom(); // create new parser instance
$html->load($result); // load and parse previous result
In this example I used curl_setopt_array() to set the various CURL parameters instead of calling curl_setopt() for each one of them.
CURLOPT_URL sets the target URL, CURLOPT_COOKIE sets the cookies to send, if there are multiple cookies then they must be separated with a semicolon followed by a space, finally the CURLOPT_RETURNTRANSFER tells CURL to return the server's response as a string.
curl_exec() executes the request and returns its result.
Then we create an instance of simple_html_dom and load that previous result into it.
Thank you so much #andre, I spent all evening yesterday to find the solution :
The first we make curl exe to login to google account.
and save cookie to a text file (exam : "/tmp/cookie.txt")
and the next time everything we have to do is only take cookie content in this file to get remote content.
<?php
require_once 'simple_html_dom.php';
// Construct an HTTP POST request
$clientlogin_url = "https://www.google.com/accounts/ClientLogin";
$clientlogin_post = array(
"accountType" => "HOSTED_OR_GOOGLE",
"Email" => "youracc#gmail.com",
"Passwd" => "yourpasswd",
"service" => "blogger",
"source" => "your application name"
);
// Initialize the curl object
$curl = curl_init($clientlogin_url);
// Set some options (some for SHTTP)
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $clientlogin_post);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_COOKIEFILE, "/tmp/cookie.txt");
curl_setopt($curl, CURLOPT_COOKIEJAR, "/tmp/cookie.txt");
// Execute
$response = curl_exec($curl);
echo $response;
// Get the Auth string and save it
preg_match("/Auth=([a-z0-9_\-]+)/i", $response, $matches);
$auth = $matches[1];
echo "The auth string is: " . $auth;
// Include the Auth string in the headers
// Together with the API version being used
$headers = array(
"Authorization: GoogleLogin auth=" . $auth,
"GData-Version: 3.0",
);
$url = 'http://testlink.html';
$curl = curl_init();
// Make the request
curl_setopt($curl, CURLOPT_URL, $url );
//curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, false);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_COOKIEFILE, "/tmp/cookie.txt");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($curl);
curl_close($curl);
$html = new simple_html_dom(); // Create new parser instance
$html->load($response);
foreach($html->find('img') as $img) {
//echo $img->src . '</br>';
}
I'm trying to fetch a file from a server that requires authentication. I have the following PHP code:
//Import categories
$url = "http://$username:$password#www.example.com";
$categoriesXML = file_get_contents($url);
var_dump($url . " > " . $categoriesXML);
return;
The output of this page is merely: string(22) "Authorization Required". I also tried with:
$context = stream_context_create(array('http' => array('header' => "Authorization: Basic " . base64_encode("$username:$password"))));
$url = "http://www.example.com";
$categoriesXML = file_get_contents($url, false, $context);
var_dump($categoriesXML);
return;
I tried with cURL as well with the following code:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
var_dump($output);
return;
The cURL returns a 301 code in the $info and the $output is empty. I'm a PHP/server newbie, what am I doing wrong?
The OP's problem was due to choosing the wrong HTTP auth mechanism. Setting CURLOPT_AUTH to CURLAUTH_BASIC or the more permissive CURLAUTH_ANY proved to solve the problem.
When try to create a new API request with the Windows Azure new Bing based API, Using the code below
$url= 'https://'.$this->m_host.'/Web?Query={keyword}&Adult=%27Off%27&$top=50&$format=Atom';
$url=str_replace('{keyword}', urlencode($this->m_keywords), $url);
// Replace this value with your account key
$accountKey = $this->key;
$WebSearchURL = $url;
$context = stream_context_create(array(
'http' => array(
'proxy' => 'tcp://127.0.0.1:8888',
'request_fulluri' => true,
'header' => "Authorization: Basic " . base64_encode($accountKey . ":" . $accountKey)
)
));
$request = $WebSearchURL;
$response = file_get_contents($request, 0, $context);
print_r($response);
i get following error.
Warning: file_get_contents() [function.file-get-contents]:
Couldn't connect to server in /home/xxxxx on line 43
Warning: file_get_contents(https://api.datamarket.azure.com/
failed to open stream: operation failed in /home/xxxx/ bing_search.php on line 43
Any idea why this fails ? or is it best to use the CURL Library than the file_get_contents() ?
The below code works for me, it is to search news but it will work for web searches too.
Just replace appkey with your one, leave username as it is (i.e. username) since it is ignored by the server
function getBingResult($keyword)
{
$credentials = "username:appkey";
$url= "https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/News?Query=%27{keyword}%27". "&\$format=json";
$url=str_replace('{keyword}', urlencode($keyword), $url);
$ch = curl_init();
$headers = array(
"Authorization: Basic " . base64_encode($credentials)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,5);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($session, CURLOPT_VERBOSE, TRUE);
$rs = curl_exec($ch);
$jsonobj = json_decode($rs);
curl_close($ch);
return $jsonobj;
}
Testing the function:
$bingResult = getBingResult("John");
foreach($bingResult->d->results as $value)
{
echo '<pre>'."URL:". $value->Url.'</pre>';
echo '<pre>'."Title:". $value->Title.'</pre>';
echo '<pre>'."Description:". $value->Description.'</pre>';
echo '<pre>'."Source:". $value->Source.'</pre>';
echo '<pre>'."Date:". $value->Date.'</pre>';
}
Either file_get_contents or CURL will work for the Bing API, you can use what will work on your system and what you are comfortable with.
First I would check your server can connect to the Windows Azure server. Try running a ping and then a wget from the command line to see if it can. Do you go through a proxy? You'll need to set those details in your stream context.
I'm not sure what you have $this->m_host set to, but the new Bing API should be at either:
https://api.datamarket.azure.com/Bing/Search/ or https://api.datamarket.azure.com/Bing/SearchWeb/. The URL https://api.datamarket.azure.com/Web comes back as invalid.
Here is working example of Search API just replace your access key with "XXXX". Even i wasted quite a few hours to get it work using cURL but it was failing cause of "CURLOPT_SSL_VERIFYPEER" on local :(
$process = curl_init('https://api.datamarket.azure.com/Bing/Search/Web?Query=%27xbox%27');
curl_setopt($process, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($process, CURLOPT_USERPWD, "username:XXXX");
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($process, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($process);
# Deliver
return $response;
# Have a great day!
curl_close($process);
1.) You do not need str_replace(). Use the var directly inside the url:
$url= 'https://'.$this->m_host.'/Web?Query='.urlencode($this->m_keywords).'&Adult=%27Off%27&$top=50&$format=Atom';
2.) You defined three different vars with the same value:
$WebSearchURL = $url;
$request = $WebSearchURL;
Use $url only.
3.) base64_encode($accountKey . ":" . $accountKey) can be reduced to base64_encode(":" . $accountKey)
4.) Add Accept-Encoding: gzip to your header to reduce traffic and raise speed.
5.) Your problem should be this line:
'proxy' => 'tcp://127.0.0.1:8888',
Remove it or change it to the correct value.