Custom API and cunsuming in php? - 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";
}
}
?>

Related

what should i do for get all http links in cURL

I created a program in php using CURL, in which i can take data of any site and can display it in the browser. Another part of the program is that the data can be saved in the file using file handling and after saving this data, I can find all the http links within the body tag of the saved file. My code is showing all the sites in the browser which I took, but I can not find all http links
Kindly help me out this problem.
PHP Code:
<!DOCTYPE html>
<html>
<head>
<title>Display links using Curl</title>
</head>
<body>
<?php
$GetData = curl_init();
$url = "http://www.ucertify.com/";
curl_setopt($GetData, CURLOPT_URL, $url);
curl_setopt($GetData, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($GetData);
curl_close($GetData);
$file=fopen("content.txt","w");
fputs($file,$data);
fclose($file);
echo $data;
function links() {
$file_content = file_get_contents("http://www.ucertify.com/");
$dom_obj = new DOMDocument();
#$dom_obj->loadHTML($file_content);
$xpath = new DOMXPath($dom_obj);
$links_href = $xpath->evaluate("/html/body//a");
for ($i = 0; $i<$links_href->length; $i++) {
$href = $links_href->item($i);
$url = $href->getAttribute("href");
if(strstr($url,"#")||strstr($url,"javascript:void(0)")||$url=="javascript:;"||$url=="javascript:"){}
else {
echo "<div>".$url."<div/>";
}
}
}
echo links();
?>
</body>
</html>
You can use regex like this
preg_match("/<body[^>]*>(.*?)<\/body>/is", $file_data, $body_content);
preg_match_all("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$body_content[1],$matches);
foreach($matches[0] as $d) {
echo $d."<br>";
}

Microsoft Cognitive Services Bing WebSearch API v5.0

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.

Get latitude and longitude from zip code using PHP

I have a PHP page containing the following code to get latitude and longitude from a user input postal code.
But when I tried to echo the latitude and longitude, nothing is shown.
<?php
function getLnt($zip){
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($zip)."&sensor=false";
$result_string = file_get_contents($url);
$result = json_decode($result_string, true);
return $result['results'][0]['geometry']['location'];
}
getLnt("750341");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<?php
$val = getLnt('90001');
echo "Latitude: ".$val['lat']."<br>";
echo "Longitude: ".$val['lng']."<br>";
?>
</body>
</html>
Please add key parameter in api request. Key value you need to replace with google API key.
$url = "https://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($postal_code)."&sensor=false&key=googleapi";
$result_string = file_get_contents($url);
$result = json_decode($result_string, true);
if(!empty($result['results'])){
$zipLat = $result['results'][0]['geometry']['location']['lat'];
$ziplng = $result['results'][0]['geometry']['location']['lng'];
}
I've tested your code and it works perfectly, my guess is that you've exceeded your daily quota for the Google Places API Web Service.
A quick solution is to apply for a key at:
https://console.developers.google.com/
I think your problem is on API call must be on HTTP So change http to https
<?php
function getLnt($zip){
$url = "https://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($zip)."&sensor=false";
$result_string = file_get_contents($url);
$result = json_decode($result_string, true);
return $result['results'][0]['geometry']['location'];
}
getLnt("750341");
?>
Not sure when but in 2019, we can use components in instead of address to get more accurary result.
eg: country is US and postal code is 41000
$url = "https://maps.googleapis.com/maps/api/geocode/json?components=" . urlencode('country:US|postal_code:41000') . "&key=YOUR_API_KEY";
function getLnt($zip){
$url = "https://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($zip)."&sensor=false&key=YOUR_KEY";
$result_string = file_get_contents($url);
$result = json_decode($result_string, true);
return $result['results'][0]['geometry']['location'];
}
print_r(getLnt("462021"));

ReCAPTCHA always incorrect

I have a page with a recaptcha in it, and it had been running without any problem for two months. But now, since a few days, it has been acting weird. I have tried many several times, but the captcha is simply not working, the verification part.
Here is the code
$captcharesponse = test_input($_POST["g-recaptcha-response"]);
$status = captcha($captcharesponse);
...
function captcha($t){
$captcharesponse = $t;
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($curl, CURLOPT_POSTFIELDS, 'secret=7...PRIVATE_KEY...S&response=' . $captcharesponse);
$result = json_decode(curl_exec($curl), true);
curl_close($curl);
if($result['success'] == false){
error_log(date("Y-M-d, D h:i:s A") . " : Result = " . $result['success'] . ", and error = " . $result['error-codes']);
}
return $result['success'];
}
And no matter what, even if I am not even entering the captcha, still the page is taking too long, and hence nothing is working. Please not that other things are simply skipped if the captcha is wrong, so there is no way that other things are causing the delay.
Thanks in advance
PS. I am not using any kind or library or anything, and it did use to work some time back without any problem.
The 'test_input()' code:
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
The problem has been resolved,
Apparently it was a problem on reCAPTCHA's end. The above provided code is now working flawlessly, and all slow-performance problems have been resolved as well.
Thank you all.
PS. Others can use this code if the want.
I'd say to use the recaptcha library, available at:
https://github.com/google/recaptcha
First of all, download the files, most important is recaptchalib.php (you can download all files clicking the download zip button at right).
Then unzip it to your folder and use it like the example unzipped along (example-recaptcha.php):
<?php
require_once "recaptchalib.php";
// Register API keys at https://www.google.com/recaptcha/admin
$siteKey = "YOURSITEKEY";
$secret = "YOURSECRET";
$lang = "en";
$resp = null; // The response from reCAPTCHA
$error = null; // The error code from reCAPTCHA, if any
$reCaptcha = new ReCaptcha($secret);
if ($_POST["g-recaptcha-response"]) { // Was there a reCAPTCHA response?
$resp = $reCaptcha->verifyResponse(
$_SERVER["REMOTE_ADDR"],
$_POST["g-recaptcha-response"]
);
}
?>
<html>
<head><title>reCAPTCHA Example</title></head>
<body>
<?php
if ($resp != null && $resp->success) {
echo "You got it!";
}
?>
<form action="" method="post">
<div class="g-recaptcha" data-sitekey="<?php echo $siteKey;?>"></div>
<script type="text/javascript"
src="https://www.google.com/recaptcha/api.js?hl=<?php echo $lang;?>">
</script>
<br/>
<input type="submit" value="test recaptcha" />
</form>
</body>
</html>

PHP - Redirect and send data via POST

I have an online gateway which requires an HTML form to be submitted with hidden fields. I need to do this via a PHP script without any HTML forms (I have the data for the hidden fields in a DB)
To do this sending data via GET:
header('Location: http://www.provider.com/process.jsp?id=12345&name=John');
And to do this sending data via POST?
You can't do this using PHP.
As others have said, you could use cURL - but then the PHP code becomes the client rather than the browser.
If you must use POST, then the only way to do it would be to generate the populated form using PHP and use the window.onload hook to call javascript to submit the form.
here is the workaround sample.
function redirect_post($url, array $data)
{
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function closethisasap() {
document.forms["redirectpost"].submit();
}
</script>
</head>
<body onload="closethisasap();">
<form name="redirectpost" method="post" action="<? echo $url; ?>">
<?php
if ( !is_null($data) ) {
foreach ($data as $k => $v) {
echo '<input type="hidden" name="' . $k . '" value="' . $v . '"> ';
}
}
?>
</form>
</body>
</html>
<?php
exit;
}
A better and neater solution would be to use $_SESSION:
Using the session:
$_SESSION['POST'] = $_POST;
and for the redirect header request use:
header('Location: http://www.provider.com/process.jsp?id=12345&name=John', true, 307;)
307 is the http_response_code you can use for the redirection request with submitted POST values.
Another solution if you would like to avoid a curl call and have the browser redirect like normal and mimic a POST call:
save the post and do a temporary redirect:
function post_redirect($url) {
$_SESSION['post_data'] = $_POST;
header('Location: ' . $url);
}
Then always check for the session variable post_data:
if (isset($_SESSION['post_data'])) {
$_POST = $_SESSION['post_data'];
$_SERVER['REQUEST_METHOD'] = 'POST';
unset($_SESSION['post_data']);
}
There will be some missing components such as the apache_request_headers() will not show a POST Content header, etc..
It would involve the cURL PHP extension.
$ch = curl_init('http://www.provider.com/process.jsp');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "id=12345&name=John");
curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1); // RETURN THE CONTENTS OF THE CALL
$resp = curl_exec($ch);
/**
* Redirect with POST data.
*
* #param string $url URL.
* #param array $post_data POST data. Example: array('foo' => 'var', 'id' => 123)
* #param array $headers Optional. Extra headers to send.
*/
public function redirect_post($url, array $data, array $headers = null) {
$params = array(
'http' => array(
'method' => 'POST',
'content' => http_build_query($data)
)
);
if (!is_null($headers)) {
$params['http']['header'] = '';
foreach ($headers as $k => $v) {
$params['http']['header'] .= "$k: $v\n";
}
}
$ctx = stream_context_create($params);
$fp = #fopen($url, 'rb', false, $ctx);
if ($fp) {
echo #stream_get_contents($fp);
die();
} else {
// Error
throw new Exception("Error loading '$url', $php_errormsg");
}
}
Use curl for this. Google for "curl php post" and you'll find this: http://www.askapache.com/htaccess/sending-post-form-data-with-php-curl.html.
Note that you could also use an array for the CURLOPT_POSTFIELDS option. From php.net docs:
The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with # and use the full path. This can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data.
Your going to need CURL for that task I'm afraid. Nice easy way to do it here: http://davidwalsh.name/execute-http-post-php-curl
Hope that helps
Alternatively, setting a session variable before the redirect and test it in the destination url, can solve this problem for me.
You have to open a socket to the site with fsockopen and simulate a HTTP-Post-Request.
Google will show you many snippets how to simulate the request.
I used the following code to capture POST data that was submitted from form.php and then concatenate it onto a URL to send it BACK to the form for validation corrections. Works like a charm, and in effect converts POST data into GET data.
foreach($_POST as $key => $value) {
$urlArray[] = $key."=".$value;
}
$urlString = implode("&", $urlArray);
echo "Please <a href='form.php?".$urlString."'>go back</a>";
An old post but here is how I handled it. Using newms87's method:
if($action == "redemption")
{
if($redemptionId != "")
{
$results = json_decode($rewards->redeemPoints($redemptionId));
if($results->success == true)
{
$redirectLocation = $GLOBALS['BASE_URL'] . 'rewards.phtml?a=redemptionComplete';
// put results in session and redirect back to same page passing an action paraameter
$_SESSION['post_data'] = json_encode($results);
header("Location:" . $redirectLocation);
exit();
}
}
}
elseif($action == "redemptionComplete")
{
// if data is in session pull it and unset it.
if(isset($_SESSION['post_data']))
{
$results = json_decode($_SESSION['post_data']);
unset($_SESSION['post_data']);
}
// if you got here, you completed the redemption and reloaded the confirmation page. So redirect back to rewards.phtml page.
else
{
$redirectLocation = $GLOBALS['BASE_URL'] . 'rewards.phtml';
header("Location:" . $redirectLocation);
}
}
Yes, you can do this in PHP e.g. in
Silex or Symfony3
using subrequest
$postParams = array(
'email' => $request->get('email'),
'agree_terms' => $request->get('agree_terms'),
);
$subRequest = Request::create('/register', 'POST', $postParams);
return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST, false);
A workaround wich works perfectly :
In the source page,, start opening a session and assign as many values as you might want.
Then do the relocation with "header" :
<!DOCTYPE html>
<html>
<head>
<?php
session_start();
$_SESSION['val1'] = val1;
...
$_SESSION['valn'] = valn;
header('Location: http//Page-to-redirect-to');
?>
</head>
</html>
And then, in the targe page :
<!DOCTYPE html>
<?php
session_start();
?>
<html>
...
<body>
<?php
if (isset($_SESSION['val1']) && ... && isset($_SESSION['valn'])) {
YOUR CODE HERE based on $_SESSION['val1']...$_SESSION['valn'] values
}
?>
</body>
</html>
No need of Javascript nor JQuery..
Good luck !

Categories