I am trying to access the BandPage API using this script which I found on Github. I have very little experience with PHP so can't really figure out what is wrong with this. This is the script:
<?php
function bandpageToken($client_id,$shared_secret) {
if($_COOKIE['bp_access_token']) {
$access_token = $_COOKIE['bp_access_token'];
} else {
//set POST variables
$url = 'https://api-read.bandpage.com/token';
$fields = array(
'client_id' => $client_id,
'grant_type' => "client_credentials"
);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($ch,CURLOPT_USERPWD, $client_id . ':' . $shared_secret);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//execute post
$result = curl_exec($ch);
$obj = json_decode($result);
setcookie("bp_access_token", $obj->access_token, time()+$obj->expires_in-10);
$access_token = $obj->access_token;
//close connection
curl_close($ch);
}
return $access_token;
}
$app_id = 'MyIdIsHere';
$client_id = 'clientIdIsHere';
$shared_secret = 'sharedSecerecIsHere';
$access_token = bandpageToken($client_id,$shared_secret);
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Bandpage Connect</title>
<script type='text/javascript'>;(function(){var e="sdk-js.bandpage.com",t="/embedscript/connect";window._rm_lightningjs||function(e){function n(n,r){var i="1";return r&&(r+=(/\?/.test(r)?"&":"?")+"lv="+i),e[n]||function(){var i=window,s=document,o=n,u=s.location.protocol,a="load",f=0;(function(){function l(){n.P(a),n.w=1,e[o]("_load")}e[o]=function(){function a(){return a.id=s,e[o].apply(a,arguments)}var t=arguments,r=this,s=++f,u=r&&r!=i?r.id||0:0;return(n.s=n.s||[]).push([s,u,t]),a.then=function(e,t,r){var i=n.fh[s]=n.fh[s]||[],o=n.eh[s]=n.eh[s]||[],u=n.ph[s]=n.ph[s]||[];return e&&i.push(e),t&&o.push(t),r&&u.push(r),a},a};var n=e[o]._={};n.fh={},n.eh={},n.ph={},n.l=r?r.replace(/^\/\//,(u=="https:"?u:"http:")+"//"):r,n.p={0:+(new Date)},n.P=function(e){n.p[e]=new Date-n.p[0]},n.w&&l(),i.addEventListener?i.addEventListener(a,l,!1):i.attachEvent("on"+a,l),n.l&&function(){function e(){return["<",r,' onload="var d=',p,";d.getElementsByTagName('head')[0].",u,"(d.",a,"('script')).",f,"='",n.l,"'\">"].join("")}var r="body",i=s[r];if(!i)return setTimeout(arguments.callee,100);n.P(1);var u="appendChild",a="createElement",f="src",l=s[a]("div"),c=l[u](s[a]("div")),h=s[a]("iframe"),p="document",d="domain",v,m="contentWindow";l.style.display="none",i.insertBefore(l,i.firstChild).id=t+"-"+o,h.frameBorder="0",h.id=t+"-frame-"+o,/MSIE[ ]+6/.test(navigator.userAgent)&&(h[f]="javascript:false"),h.allowTransparency="true",c[u](h);try{h[m][p].open()}catch(g){n[d]=s[d],v="javascript:var d="+p+".open();d.domain='"+s.domain+"';",h[f]=v+"void(0);"}try{var y=h[m][p];y.write(e()),y.close()}catch(b){h[f]=v+'d.write("'+e().replace(/"/g,String.fromCharCode(92)+'"')+'");d.close();'}n.P(2)}()})()}(),e[n].lv=i,e[n]}var t="_rm_lightningjs",r=window[t]=n(t);r.require=n,r.modules=e}({}),function(n){if(n.bandpage)return;var r=_rm_lightningjs.require("$rm","//"+e+t),i=function(){},s=function(t){t.done||(t.done=i),t.fail||(t.fail=i);var n=r("load",t);n.then(t.done,t.fail);var s={done:function(e){return n.then(e,i),s},fail:function(e){return n.then(i,e),s}};return s},o=null;n.bandpage={load:s,ready:function(e){o.then(e,i)}},o=r("bootstrap",n.bandpage,window)}(window)})(this);</script>
<script type="text/javascript">
bandpage.load({
"done" : function() {
var connection = bandpage.sdk.connect({
appId : "<?=$app_id?>",
access_token : "<?=$access_token?>",
container : $('.btn-container').get(0),
allow_reconnect : false
});
connection.on("bpconnect.complete", function(bands){
console.log("User has authed bands!");
console.log(bands);
});
connection.on("bpconnect.cancel", function(){
console.log("User clicked the cancel button and connect window is closed");
});
},
"fail" : function() {
console.log("Failed to initialize sdk");
}
});
</script>
<style>
.btn-container {
top: 50%;
position: absolute;
left: 50%;
margin: -22px 0 0 -117px;
}
</style>
</head>
<body>
<div class='btn-container'></div>
</body>
</html>
and the error seems to be with the bp_access_token, errors below.
Notice: Undefined index: bp_access_token in C:\wamp\www\Testing\index.php on line 5
Notice: Trying to get property of non-object in C:\wamp\www\Testing\index.php on line 33
Notice: Trying to get property of non-object in C:\wamp\www\Testing\index.php on line 34
Do I need to declare bp_access_token somewhere or am I missing something else?
The script hasn't been written very well. On line 5, an array access is made in the cookies array without first checking it exists. The author may have display_errors turned off, but not everyone does.
This:
if($_COOKIE['bp_access_token']) {
would be better expressed as:
if(isset($_COOKIE['bp_access_token']) && $_COOKIE['bp_access_token']) {
That will fix your first notice. As for the other two, you are making object accesses on null values in these lines:
setcookie("bp_access_token", $obj->access_token, time()+$obj->expires_in-10);
$access_token = $obj->access_token;
My guess would be that your authentication to BandPage has failed, and you don't have a valid response object to work with. Double-check the values of these in the script, which must be supplied by you:
$app_id
$client_id
$shared_secret
You can probably get these from a control panel somewhere in your BandPage account screen.
add error_reporting(E_ALL ^ E_NOTICE);
just after <?php tag.
if your script is working perfectly but warning/notices are showing, you can add
error_reporting(0);
keep in mind to comment out this line as soon as you face some problem with this script next time.
Related
eBay is making changes to their APIs, shutting down the finding API at the end of the year. I'm using a very simple application on my WordPress site that displays products based on a specific query I hard code. I am able to replicate my page using the Browse API, but I'm really struggling with the Oauth part of things. From what I understand, the Browse get requests only require an application access token (not a user access token). I'm just still struggling to get my head around all of this. I'm trying to add a function that generates an auth token, but it's not working and I don't think I'm calling the function correctly...so looking for help on a few things here. Most importantly--can i do it this way? And am i entering the variables correctly and how exactly do i call the Oauth function?
<?php
/* Template Name: XXXX */
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
function getOAuthCreds() {
$endpoint = 'https://api.ebay.com/identity/v1/oauth2/token';
$request = "grant_type=client_credentials";
$request .= "scope=https://api.ebay.com/oauth/api_scope";
$session = curl_init($endpoint);
curl_setopt($session, CURLOPT_POST, true);
curl_setopt($session, CURLOPT_POSTFIELDS, $request);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
$headers = [
'Content-Type: application/json',
'Authorization = Bearer CODE HERE// I'm using the auth code generated from the application access token (not sure if thats' right?
];
curl_setopt($session, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($session);
curl_close($session);
return $response;
}
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.ebay.com/buy/browse/v1/item_summary/search?q=iphone&sort=-",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Content-Type:application/json",
"Authorization:" getOAuthCreds(),///am i calling this correctly?
"X-EBAY-C-MARKETPLACE-ID:EBAY_US",
"X-EBAY-C-ENDUSERCTX:affiliateCampaignId=xx,affiliateReferenceId=xx",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
//print_r($response);
if ($err) {
if ($debug) echo "cURL Error #:" . $err;
else echo "Oops, something went wrong. Please try again later.";
} else {
//Create an array of objects from the JSON returned by the API
$jsondata = json_decode($response);
$resp = $jsondata->itemSummaries;
//Create a simple grid style for the listings
$pageCSS = "<style>
.netflix-wrapper{
display:grid;
grid-template-columns: 200px 200px 200px;
}
.show-wrapper{padding:10px;}
</style>";
//Create the WordPress page content HTML
$pageHTML="<h2>test</h2>";
$pageHTML.="<div class='test-wrapper'>";
//Loop through the API results
foreach($resp as $item) {
//Put each show into an html structure
// Note: if your theme uses bootstrap use responsive classes here
$pageHTML.="<div class='show-wrapper'>";
//Not all items have a 'poster', so in that case use the img field
$pic = $item->image->imageUrl;
$itemID = $item->legacyItemId;
$link = 'https://www.ebay.com/itm/'.$itemID.'?mkrid=ss-0&siteid=0&mkcid=1&campid=ss&toolid=ss&mkevt=1&customId=ss';
$title = $item->title;
$price = $item->price->value;
$bids = $item->bidCount;
if(empty($bids)){
$bids = 0;
}
// For each SearchResultItem node, build a link and append it to $results
$results .= "<div class=\"item\"><div class=\"ui small image\"><img height=\"200px\" width=\"130px\" src=\"$pic\"></div><div class=\"content\"><div class=\"header\">$title</div><div class=\"meta\" style=\"margin-top:1.1em\"><span class=\"price\"><button class=\"ui teal button\">watch watchers</button></span><div class=\"extra\"><button class=\"ui button\"><b>Current Bids:</b> $bids </button></div><div class=\"extra\"><button class=\"ui orange button\">Current Price: $$price</button></div><div class=\"description\"></div></div></div></div>";
//Show the image first to keep the top edge of the grid level
$pageHTML.="<img style='max-width:166px;float:left;' src='".$pic."' />";
$pageHTML.="<h3>".$item->title."</h3>";
// $pageHTML.="<span>added to netflix ".$showObj->titledate."</span>";
// $pageHTML.="<div style='float:left;'>".$showObj->synopsis."</div>";
$pageHTML.="</div>";
}
$pageHTML.="</div>";
}
?>
<?php get_header(); ?>
<!-- Build the HTML page with values from the call response -->
<html>
<head>
<div class="wrp cnt"><div class="spr"></div>
<section class="bSe fullWidth">
<article><div class="awr lnd">
<title>Most Watched <?php echo $query; ?> on eBay</title>
<style type="text/css">body { font-family: arial,sans-serif;} </style>
<link
rel="stylesheet"
href="//cdn.jsdelivr.net/npm/semantic-ui#2.4.2/dist/semantic.min.css"
/>
</head>
<body>
For reference:
https://developer.ebay.com/api-docs/static/oauth-client-credentials-grant.html
I do not know much about php but gathered from your code there are a few things that are not right.
1. The headers section
In function getOAuthCreds()
Headers should be:
Content-Type = application/x-www-form-urlencoded
Authorization = Basic [B64-encoded_oauth_credentials]
Content-Type = application/x-www-form-urlencoded header. eBay wants you to POST to its server so you will need this. Not sure if curl would automatically add to the header.
Authorization header. From eBay reference above, the header will use Basic authentication scheme. Then followed by the Base64 encoding of your "client_id":"client_secret".
[B64-encoded_oauth_credentials] = Base64Encode(client_id:client_secret)
Sample:
Authorization = Basic Y2xpZW50X2lkOmNsaWVudF9zZWNyZXQ=
In case you are not sure where to get "client_id" and "client_secret". Visit this page.
https://developer.ebay.com/api-docs/static/creating-edp-account.html
If everything is correct, you will receive the following response from eBay
Sample:
{
"access_token": "v^1.1#i^1#p^1#r^0#I^3#f^0#t^H4s ... wu67e3xAhskz4DAAA",
"expires_in": 7200,
"token_type": "Application Access Token"
}
The access_token from the response will be valid for 7200 seconds. Cache and reuse it as the previous comment mentioned. When it is expired, get a new access_token.
2. When calling Browse API
You will use the access_token in the Authorization header (in Browse API call) as follow.
Sample:
Authorization: Bearer v^1.1#i^1#p^1#r^0#I^3#f^0#t^H4s ... wu67e3xAhskz4DAAA
I make an api using Linkedin for website. After created all files, my application run fine but the only that has problem is when I try to allow the website, gives me this errors:
my purpose is to access in this page:
My code has error in this line:
init.php
<?php
SESSION_start();
$client_id="xxxxxxxxxxxxxx";
$client_secret="xxxxxxxxxxxxxxxx";
$redirect_uri="http://localhost/gmail-connect.php/callback.php";
$csrf_token = "random_int(1111111, 9999999)";
$scopes="r_basicprofile%20r_emailaddress";
function curl($url, $parameters)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
curl_setopt($ch, CURLOPT_POST, 1);
$header =[];
$header[] = "Content-type:applicationx-www-form-urlencoded";
$result = curl_exec($ch);
return $result;
}
function getCallback()
{
$client_id="xxxxxxxxxxxxxx";
$client_secret="jxxxxxxxxxxxxxxxx";
$redirect_uri="http://localhost/gmail-connect.php/callback.php";
$csrf_token ="random_int(1111111, 9999999)";
$scopes="r_basicprofile%20r_emailaddress";
}
if(isset($_REQUEST['code'])) {
$code = $_REQUEST['code'];
$url = "https://www.linkedin.com/oauth/v2/accessToken";
$params = [
'client_id' => $client_id,
'client_secret' => $client_secret,
'redirect_uri' => $redirect_uri,
'code' => $code,
'grant_type' => 'authorization_code',
];
$accessToken = curl($url, http_build_query($params));
$accessToken = json_decode($accessToken)->access_Token;
$URL="https://api.linkedin.com/v1/people/~:(id,firstName,lastName,pictureUrls::(original),headline,publicProfileUrl,location,industry,positions,email-address)?format=json&oauth2_access_token=" .$accessToken;
$user = file_get_contents($url, false);
return(json_decode($user));
}
?>
Callback.php:
<?php
require_once "init.php";
$user = getCallback();
$_SESSION['user'] = $user;
header("location: landing.php");
?>
And this is the landing page:
<?php
require "init.php";
if(!isset($_SESSION['user'])) {
$user = 0;
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>profile</title>
</head>
<body style="margin-top:200px; text-align:center;">
<div>
<h1>successful</h1>
<h1>here is describing your details info</h1>
<label style="font-weight:600">First Name</label><br>
<label><?php echo $user['firstName'] ?></label><br><br>
<label style="font-weight:600">Last Name</label><br>
<label><?php echo $user['lastName'] ?></label><br><br>
<label style="font-weight:600">Email address</label><br>
<label><?php echo $user['emailaddress'] ?></label><br><br>
<label style="font-weight:600">Headline</label><br>
<label><?php echo $user['headline'] ?></label><br><br>
<label style="font-weight:600">Industry</label><br>
<label><?php echo $user['industry'] ?></label><br><br>
<button>Log out</button>
</div>
</body>
</html>
the x it is for secure reason, I have put $client_secret="", $client_id="".
In this project I want to see my profile completed with details on landing page and not empty as it's show here for example in first name to be writen a name and ect.
how to fix those errors,thanks
The first error (Undefined property) is because the HTTP request didn't get a valid response ($accessToken) in:
$accessToken = curl();
This could be because the URL requested is invalid. You can:
Check if $params array is correctly set. Call print_r($params) or print_r(http_build_query($params)) before calling curl to check it.
Check if the curl() call has the right parameters (url and parameters) it could be better to use only a full url ($url . "?" . http_build_query($params)) if the request is using GET, but
The accessToken API must be requested as POST request (not GET), so make sure your cUrl call sends a POST request (See: https://developer.linkedin.com/docs/oauth2#)
The second error is related to the first one, because the access token is empty, you get a HTTP 400 error (bad request). So if you fix the first step the second could be fine.
try this code before $accessToken :
$context = stream_context_create(
array('http' =>
array('method' => 'POST',
)
)
);
return true;
this make solute the error message
I am going to pull my hair out. Can anyone please help me get this to work I am sure it's something stupid.. I have got all the PHP errors to go away, but I can not get images to show up. Code below...
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="jquery.fancybox-1.3.4.css" type="text/css">
<script type='text/javascript' src='jquery.min.js'></script>
<script type='text/javascript' src='jquery.fancybox-1.3.4.pack.js'></script>
<script type="text/javascript">
$(function() {
$("a.group").fancybox({
'nextEffect' : 'fade',
'prevEffect' : 'fade',
'overlayOpacity' : 0.8,
'overlayColor' : '#000000',
'arrows' : false,
});
});
</script>
<?php
// Supply a user id and an access token
$userid = "1d458ab0c149424c812e664c32b48149";
$accessToken = "c195717e379f48c68df451cc3d60524a";
// Gets our data
function fetchData($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
// Pulls and parses data.
$result = fetchData("https://api.instagram.com/v1/users/{$userid}/media/recent/?access_token={$accessToken}");
$result = json_decode($result);
?>
<?php if(!empty($result->data)): ?>
<?php foreach ($result->data as $post){ ?>
<!-- Renders images. #Options (thumbnail,low_resoulution, high_resolution) -->
<a class="group" rel="group1" href="<?= $post->images->standard_resolution->url ?>"><img src="<?= $post->images->thumbnail->url ?>"></a>
<?php } ?>
<?php endif ?>
</html>
What you need is to add some checks at various points to find out what is coming back from Instagram and handle any issues. While debugging, sticking var_dump() all over the place can be helpful to see where issues lie.
Here is an example of your PHP section with some additional checks:
<?php
// Supply a user id and an access token
$userid = "USER ID";
$accessToken = "ACCESS TOKEN";
// Gets our data
function fetchData($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
// Check a response was returned
if ($info['http_code'] == '404') {
echo ('Error: HTTP 404 returned, bad request');
die();
}
curl_close($ch);
return $result;
}
// Pulls and parses data.
$result = fetchData("https://api.instagram.com/v1/users/{$userid}/?access_token={$accessToken}");
$result = json_decode($result);
// Check the json_decode succeeded
if (empty($result)) {
echo "Error: JSON not returned from API";
die();
}
// Check no error was returned from Instagram
if ($result->meta->code != 200) {
echo "Error: ".$result->meta->error_message;
die();
}
?>
If you plan on doing a lot of work with the Instagram API, you may want to look at a library to do most of the heavy lifting. This one appears to be the most popular at present.
I'm trying to setup gitkit in my website, but can't get past this one single line of code. No matter what I do, file_get_contents keeps returning empty.
I've already set my php.ini : always_populate_raw_post_data = On
My environment is PHP 5.3.3, Apache 2.2.6, localhost.
Here's some code.
In my index.php, I call the google API and try to login with gmail account, in other words, federated login.
(this is from the Google API Console)
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/googleapis/0.0.4/googleapis.min.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/jsapi"></script>
<script type="text/javascript">
google.load("identitytoolkit", "1", {packages: ["ac"], language:"en"});
</script>
<script type="text/javascript">
$(function() {
window.google.identitytoolkit.setConfig({
developerKey: "HERE_GOES_MY_DEVELOPER_KEY",
companyName: "Valentinos Pizzaria",
callbackUrl: "http://localhost/valentinos/callback.php",
realm: "",
userStatusUrl: "http://localhost/valentinos/userstatus.php",
loginUrl: "http://localhost/valentinos/login.php",
signupUrl: "http://localhost/valentinos/register.php",
homeUrl: "http://localhost/valentinos/index.php",
logoutUrl: "http://localhost/valentinos/logout.php",
idps: ["Gmail", "Yahoo"],
tryFederatedFirst: true,
useCachedUserStatus: false,
useContextParam: true
});
$("#navbar").accountChooser();
});
</script>
I get the IDP response, log in, and am asked for permissions. Upon returning to my callback page, in which I used the code sample provided by Google (which is below), this one line of code doesn't seem to be returning correctly.
Am I doing anything stupid at all?
Any help will be appreciated.
Here's whole callback.php so far (there's no HTML whatsoever, for now):
session_start();
$url = EasyRpService::getCurrentUrl();
#$postData = #file_get_contents('php://input');
$postData = file_get_contents('php://input');
$result = EasyRpService::verify($url, $postData);
// Turn on for debugging.
// var_dump($result);
class EasyRpService {
// Replace $YOUR_DEVELOPER_KEY
private static $SERVER_URL = 'https://www.googleapis.com/rpc?key=HERE_GOES_MY_DEVELOPER_KEY';
public static function getCurrentUrl() {
$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
$url .= $_SERVER['SERVER_NAME'];
if ($_SERVER['SERVER_PORT'] != '80') {
$url .= ':'. $_SERVER['SERVER_PORT'];
}
$url .= $_SERVER['REQUEST_URI'];
return $url;
}
private static function post($postData) {
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => EasyRpService::$SERVER_URL,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPHEADER => array('Content-Type: application/json'),
CURLOPT_POSTFIELDS => json_encode($postData)));
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($http_code == '200' && !empty($response)) {
return json_decode($response, true);
}
return NULL;
}
public static function verify($continueUri, $response) {
$request = array();
$request['method'] = 'identitytoolkit.relyingparty.verifyAssertion';
$request['apiVersion'] = 'v1';
$request['params'] = array();
$request['params']['requestUri'] = $continueUri;
$request['params']['postBody'] = $response;
$result = EasyRpService::post($request);
if (!empty($result['result'])) {
return $result['result'];
}
return NULL;
}
} # End Class EasyRpService
Before anyone asks, I do replace HERE_GOES_MY_DEVELOPER_KEY with my Developer Key...
Once again, any help will be much appreciated.
C ya.
Did you try using $_POST ? php://input don't work for enctype="multipart/form-data". May be you are getting response as multipart/form-data in this case $_POST[0] should work.
HTTP POST data is usually populated in $_POST, php://input will usually contain PUT data.
Can anyone help me with this error? Been looking it at for a while but haven't been able to get it to work. Wrote this a while ago and felt like it worked when I last left it, but I haven't been able to run it when I revisited it. Thanks for all the help.
Notice: Trying to get property of non-object in /Applications/MAMP/htdocs/search/views/layouts/search.php on line 46
Warning: Invalid argument supplied for foreach() in /Applications/MAMP/htdocs/search/views/layouts/search.php on line 46
Line 46 is the foreach line 4th from the last line of code.
<?php
include($_SERVER['DOCUMENT_ROOT'].'/'.'search/scripts/JSON.php');
include($_SERVER['DOCUMENT_ROOT'].'/'.'search/scripts/search_fns.php');
$searchquery = urlencode(isset($_GET['search']) ? $_GET['search'] : "news");
// Google Search API
$url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
. "q="
. $searchquery
."&key=ABQIAAAAYIeqEnf9yNjBzcHJK7yDdhSklBzi76D_F0lniPI7JR27aK7eCBSU-xpNs1axVS45y_PX_7_ibsScUA&userip=USERS-IP-ADDRESS&rsz=filtered_cse";
// sendRequest
// note how referer is set manually
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, "http://localhost");
$body = curl_exec($ch);
curl_close($ch);
// process the JSON string
$json = new Services_JSON;
$json = $json->decode($body);
$formattedresults = "";
$rating = "";
$search = $searchquery;
?>
<style type="text/css">
td img {display: block;}
</style>
<div id="main">
<?php
foreach($json->responseData->results as $searchresult)
{
if($searchresult->GsearchResultClass == 'GwebSearch')
{
Probably it returned an empty response.
Before using foreach it's useful to test the variable using is_object($json->responseData). I would also check if the property 'results' exist with property_exists($json, 'results')