Microsoft Cognitive Services Bing WebSearch API v5.0 - php

I am having some issues with the new Bing search API from Microsoft Azure (cognitive services). Here is my code below, what I am trying to do is call on the API from my form that I have made and simple show results but I am having some trouble doing so, can someone look at my code and see if there are any issues? The error I keep on getting is that I haven't defined the $q variable but I have as you will see in the code. Thanks for the help, appreciate it!
PHP:
<?php
$accountKey = 'account_key';
$url = 'https://api.cognitive.microsoft.com/bing/v5.0/search?q='.$q.'&count=10&offset=0&mkt=en-us&safesearch=Moderate';
$q = urlencode($_POST['q']);
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Ocp-Apim-Subscription-Key: $accountKey"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents($url, false, $context);
$jsonobj = json_decode($file);
echo $file;
?>
HTML:
<form method="post" action="">
<input name="q" type="text" autocomplete="off" autofocus>
<input type="submit" name="Search" hidden>
</form>
</body>
</html>

Place $q = urlencode($_POST['q']); below $accountKey
For example:
<?php
$accountKey = 'account_key';
$q = urlencode($_POST['q']);
$url = 'https://api.cognitive.microsoft.com/bing/v5.0/search?q='.$q.'&count=10&offset=0&mkt=en-us&safesearch=Moderate';
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Ocp-Apim-Subscription-Key: $accountKey"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents($url, false, $context);
$jsonobj = json_decode($file);
echo $file;
?>
You have called the variable before declare.

I have generate a code snippet for you, for your further question:
also how would I make it so when I refresh the page it takes me back to the search and doesn't call on the API again?
well since it's just plain JSON right now, would there we any way to style the results and make them more like a more conventional search engine like Google?
Please consider following code:
<html>
<body>
<form method="get" action="">
<input name="q" type="text" autocomplete="off" value="<?=$_GET['q']?>" autofocus>
<input type="submit" hidden>
</form>
</body>
</html>
<?php
$accountKey = '<accountKey>';
$q = #urlencode($_GET['q']);
if($q){
$url = 'https://api.cognitive.microsoft.com/bing/v5.0/search?q='.$q.'&count=10&offset=0&mkt=en-us&safesearch=Moderate';
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Ocp-Apim-Subscription-Key: $accountKey"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents($url, false, $context);
$jsonobj = json_decode($file);
echo ('<ul ID="resultList">');
foreach ($jsonobj->webPages->value as $value) {
echo ('<li class="resultlistitem">'.$value->name.'');
if(property_exists($value,'image')){
echo ('<img src="' . $value->image->contentUrl . '"></li>');
}
}
echo ("</ul>");
}
?>

The new cognitive API requires an account key and a subscription key. You will continue to experience errors until both are included.

Related

fetching imgur cURL to json_decode php upload form

i'm trying to use imgur as a uploading backend - i guess it secure my website if there's upload picture (is it right?) so
i went with this way :
<?php
$client_id = 'xxxxx';
$file = file_get_contents($_FILES["imgupload"]["tmp_name"]);
$url = 'https://api.imgur.com/3/image.json';
$headers = array("Authorization: Client-ID $client_id");
$pvars = array('image' => base64_encode($file));
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL=> $url,
CURLOPT_TIMEOUT => 30,
CURLOPT_POST => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $pvars
));
if ($error = curl_error($curl)) {
die('cURL error:'.$error);
}
$json_returned = curl_exec($curl); // blank response
echo "Result: " . $json_returned ;
curl_close ($curl);
?>
HTML form
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="imgupload" /><br>
<input type="submit" value="Upload to Imgur" />
</form>
when i click on submit the result is fine as i guess ^^
Result: {"data":{"id":"TvFtE29","title":null,"description":null,"datetime":1585015712,"type":"image\/png","animated":false,"width":900,"height":940,"size":48902,"views":0,"bandwidth":0,"vote":null,"favorite":false,"nsfw":null,"section":null,"account_url":null,"account_id":0,"is_ad":false,"in_most_viral":false,"has_sound":false,"tags":[],"ad_type":0,"ad_url":"","edited":"0","in_gallery":false,"deletehash":"Z9xFH8mrSH8lRDB","name":"","link":"https:\/\/i.imgur.com\/TvFtE29.png"},"success":true,"status":200}
but my problem i want to collect the https://i.imgur.com/TvFtE29.png into specific variable like $uploaded = 'https://i.imgur.com/TvFtE29.png'; to added into my database -> user pic
i went with json_decode but it's not completed with me in the right way, if someone can help with this issue 🌹
thanks.
json_decode worked fine here:
$json_returned = json_decode($json_returned, true);
$uploaded = $json_returned['data']['link'];

Custom API and cunsuming in php?

I want to write Web services(REST) and Consuming using Curl in php.
$books = array(
"java"=>"222",
"php"=>"333",
"c"=>"111",
"AngularJS"=>"111"
);
If you want to build your API in PHP check Slim Framework
It is a good framework and has a great documentation. I suggest you to use existing solutions because building your API from scratch needs a lot of time and expertise
Also Swagger is a good tool to define/design your rest endpoints.
To create the API - do the following:
<?php
$books = array(
"java"=>"222",
"php"=>"333",
"c"=>"111",
"AngularJS"=>"111"
);
return json_encode($books);
To use the returned value - you would do the opposite:
$books = json_decode($books_json);
First define URL END point for API and client url.
ex:API: http://www.customapi.com/java
Client URI: http://www.clientcustomapi.com/
API Snippet:
index.php
header("Content-Type: application/json;charset=utf-8");
include('functions.php');
//process client request
if(!empty($_GET['name'])){
$name = $_GET['name'];
$price = get_price($name);
if(empty($price)){
//book not found
deliveryResponse(200,"Book not found",NULL);
}else{
//response book price
deliveryResponse(200,"Book found",$price);
}
}else{
//invalid request
deliveryResponse(400,"invalid Request",NULL);
}
function.php
function get_price($find){
$books = array(
"java"=>"222",
"php"=>"333",
"c"=>"111"
);
foreach ($books as $book => $price) {
# code...
if($book==$find){
return $price;
break;
}
}
}
function deliveryResponse($status,$status_message,$data){
header("HTTP/1.1 $status $status_message");
$response['status'] = $status;
$response['status_message'] = $status_message;
$response['data'] = $data;
$json_response = json_encode($response);
echo $json_response;
}
Client Snippet:
<!DOCTYPE html>
<html>
<head>
<title>Book Price</title>
</head>
<body>
<form method="post" action="" name="bookprice">
<label>Book Name:</label><input type="text" name="book" id="book">
<input type="submit" value="submit" name="submit">
</form>
</body>
</html>
<?php
if (isset($_POST['submit'])) {
//simple Request
$name = $_POST['book'];
//resource address
$url ="http://www.customapi.com/$name";
//send request to resource
$client = curl_init($url);
curl_setopt($client,CURLOPT_RETURNTRANSFER, 1);
//get response from resource
$response = curl_exec($client);
$result = json_decode($response);
if($result->data !=null){
echo $result->data;
}else{
echo"No record found";
}
}
?>

Testing recaptcha on localhost

I've been trying to test recaptcha on localhost (xampp with php 5.3); the code below (taken from this answer) works on my remote host and returns 'success':'true', but on localhost { "success": false, "error-codes": [ "missing-input-response" ] } is returned. However, if I change the POST request to a GET request (essentially toggle the comment of the 2 $result = lines), then I get a successful call.
Why does this happen?! Although I'm happy that it works on my actual site, I'd like to understand why GET works but POST doesn't on localhost
<html><head></head><body><script src='https://www.google.com/recaptcha/api.js' async defer>
if(isset($_POST['g-recaptcha-response'])) {
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array('secret' => 'my_secret_key',
'response' => $_POST['g-recaptcha-response']);
$options = array(
'http' => array(
'method' => "POST",
'header' => "Content-type: application/x-www-form-urlencoded" . PHP_EOL,
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
//$result = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=my_secretkey&response=' . $_POST['g-recaptcha-response']);
$result = file_get_contents($url, false, $context);
echo $result;
}
?>
<form method="post" action='recaptchatest.php'>
<input id="test" name="test" />
<div style="left:100px;" class="g-recaptcha" data-sitekey="my_key"></div>
<input type="submit" value="Send" id="submit" class="buttons" />
</form>
</body></html>
For completeness, the output of http_build_query($data) is a correctly formed query string (secret=<my key>&response=<response>) and the output of stream_context_create($options) is Resource id #3

Using imgur api v3 to upload images with php

I'm trying to write a very simple test to upload an image to imgur and then redirect to the imgur page once it's done. (haven't gotten to that point yet)
I've looked all around these forums and tried so many different codes posted here, as well as cobbled some together from various posts. Finally, I've stopped getting errors in the php.
But.. in every code I've seen, it displays the image once it's done. Using that exact same code, my image does not appear, all I get is a page with Result: and nothing more. Does anyone have any idea what could be the problem?
<html>
<body>
<form action="upload_img.php" method="post" enctype="multipart/form-data">
<input type="file" name="imgupload" /><br>
<input type="submit" value="Upload to Imgur" />
</form>
</body>
</html>
and the php file:
<?php
$client_id = '$clientIDHERE';
$file = file_get_contents($_FILES["imgupload"]["tmp_name"]);
$url = 'https://api.imgur.com/3/image.json';
$headers = array("Authorization: Client-ID $client_id");
$pvars = array('image' => base64_encode($file));
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL=> $url,
CURLOPT_TIMEOUT => 30,
CURLOPT_POST => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $pvars
));
$json_returned = curl_exec($curl); // blank response
echo "Result: " . $json_returned ;
curl_close ($curl);
?>
Before you close the $curl handle you should check for errors:
if ($error = curl_error($curl)) {
die('cURL error:'.$error);
}

Tableau get ticket with PHP

please can you assist. I'm trying to get a ticket from the tableau server via PHP. Currently my ISP and my Server IP address is listed as trusted IPs on the tableau servers. If I use javascript on my remote server then I get the ticket but for some reason I cannot get any result with PHP and have tried a range of php code snippets. If I can get any one of them to work I will do the splits with joy.
NB: In the javascript version I need to enter the target_site which is the same as the username otherwise I don't get a result. Also note the :8000 port on the end of the url.
This is the working html/javascript version (returns a valid ticket, eg 128018285):
<script type="text/javascript">
function submitForm(){document.getElementById('form1').action = document.getElementById('server').value + "/trusted";}
</script>
<form method="POST" id="form1" onSubmit="submitForm()">
<table class="style1">
<tr>
<td class="style2">
Username:</td>
<td>
<input type="text" name="username" value="" /></td>
</tr>
<tr>
<td class="style2">
Server: </td>
<td>
<input type="text" id="server" name="server" value="http://" /></td>
</tr>
<tr>
<td class="style2">
Client IP (optional):</td>
<td>
<input type="text" id="client_ip" name="client_ip" value="" /></td>
</tr>
<tr>
<td class="style2">
Site: (leave blank for Default site, else NameOfSite if using sites)</td>
<td>
<input type="text" id="target_site" name="target_site" value="" /></td>
</tr>
<tr>
<td class="style2">
<input type="submit" name="submittable" value="Go" /></td>
<td>
</td>
</tr>
</table>
</form>
Here is my code, snippet 1 using file_get_contents
$remote_addr = $_SERVER['REMOTE+ADDR'];
$params = array(
'username' => 'myusername',
'client_ip' => $remote_addr,
'target_site' => 'myusername'
);
$context = stream_context_create($params);
$ticket = file_get_contents('http://mysite.com:8000/trusted', false, $context);
if ($ticket > 0) {
return $ticket;
}
else
return 0;
Another code snippet using curl
$server = 'myserver.com:8000';
$url = 'http://'.$server.'/trusted';
$fields_string ='target_site=myusername&username=myusername';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept-Encoding: gzip'));
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
return curl_exec($ch);
curl_close($ch);
Another code snippet using fopen
$url = 'http://myserver.com:8000/trusted';
$data = array ('username' => 'myusername','target_site' => 'myusername', 'format' => 'txt');
$data = http_build_query($data);
$params = array('http' => array(
'method' => 'POST',
'content' => $data,
'header' => 'Content-type: application/x-www-form-urlencoded' . "\r\n"
.'Accept-Encoding:' . "\r\n"
));
if($optional_headers != null)
{
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$fp = #fopen($url, 'rb', false, $ctx);
if (!$fp)
{
throw new Exception("Problem with $url, $php_errormsg");
}
$response='';
while (!feof($fp))
{
$response = $response.fgets($fp);
}
if ($response === false)
{
throw new Exception("Problem reading data from $url, $php_errormsg");
}
fclose($fp);
return $response;
Many Many Thanks in advance...
Tableau has sample PHP which works (it's running on my machine as I type). Have you tried it?
This post actually refers to the same sample code and extends it just a touch so it can be called by way of JS:
Generate tableau trusted ticket using AJAX
The sample code in question can be found in:
C:\Program Files (x86)\Tableau\Tableau Server\8.0\extras\embedding\php
It looks fairly similar to yours, but POSTs using http_post_fields()
<?php
// Returns a trusted URL for a view on a server for the
// given user. For example, if the URL of the view is:
// http://tabserver/views/MyWorkbook/MyView
//
// Then:
// $server = "tabserver";
// $view_url = "views/MyWorkbook/MyView";
//
function get_trusted_url($user,$server,$view_url) {
$params = ':embed=yes&:toolbar=yes';
$ticket = get_trusted_ticket($server, $user, $_SERVER['REMOTE_ADDR']);
if($ticket > 0) {
return "http://$server/trusted/$ticket/$view_url?$params";
}
else
return 0;
}
// Note that this function requires the pecl_http extension.
// See: http://pecl.php.net/package/pecl_http
// the client_ip parameter isn't necessary to send in the POST unless you have
// wgserver.extended_trusted_ip_checking enabled (it's disabled by default)
Function get_trusted_ticket($wgserver, $user, $remote_addr) {
$params = array(
'username' => $user,
'client_ip' => $remote_addr
);
return http_parse_message(http_post_fields("http://$wgserver/trusted", $params))->body;
}
?>
Sorry, seems that my web host was blocking port 8000, which is why the code was not working.
For reference, this was the most concise piece of code that did the trick, change the variables for your own, myusername, mytargetsite, http://example.com/trusted
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => 'username=myusername&target_site=mytargetsite'
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/trusted', false, $context);
if ($result === false) {
throw new Exception("Problem reading data from $url, $php_errormsg");
}
else echo $result;
With your suggestion, I used cURL request and I have solved your problem with cURL request as following:
function get_trusted_ticket($wgserver, $user, $remote_addr) {
$server = $wgserver;
$url = 'http://'.$server.'/trusted';
$fields_string ='target_site=$remote_addr&username=$user';
$ch = curl_init($url);
$data = array('username' => $user, 'client_ip' => $remote_addr);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
return curl_exec($ch);
curl_close($ch);
}

Categories