this is my code
<?php
require_once('asana.php');
$asana = new Asana(array('apiKey' => 'XXXXXXXX')); // API Key
$userinfo=$asana->getUserInfo();
if ($asana->responseCode != '200' || is_null($userinfo)) {
echo 'Error while trying to connect to Asana, response code: ' . $asana->responseCode;
return;
}
$resultJson = json_decode($userinfo);
foreach ($resultJson->data as $user) {
echo $user->name . ' (id ' . $user->id . ')' . PHP_EOL;
}
?>
In asana.php
public function getUserInfo($userId = null, array $opts = array()) {
$options = http_build_query($opts);
if (is_null($userId)) {
$userId = 'me';
}
return $this->askAsana($this->userUrl . '/' . $userId . '?' . $options);
}
And I got error like this: Notice: Trying to get property of non-object in C:\wamp\www\pngtest\index.php on line 15
What is the problem? Thanks in advance
$resultJson = json_decode($userinfo);
foreach ($resultJson->data as $user) {
}
You're trying to access $resultJson->data before you know if $resultJson is a valid object or not.
Note that json_decode returns:
NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
It is possible (likely) that $resultJson is NULL, because it was given invalid JSON data. You should echo $userinfo and determine if it is what you expect.
Related
I'm a beginner in using laravel. For my webapp I want to use the Google API PageSpeed. When visiting /pagespeed, it gives me this error: ErrorException (E_NOTICE)
Undefined property: stdClass::$ruleScore
Also I'm not sure if i made a correct return. I just want to show the meassured data on the /pagespeed page.
Couldn't really find an answer for my problem, I hope you can help.
I used the pagespeed.php code from https://gist.github.com/typhonius/6259822/revisions and put this in my PagespeedController:
public function pageSpeed(){
$url = 'https://www.facebook.com';
$key = 'my API key';
// View https://developers.google.com/speed/docs/insights/v1/getting_started#before_starting to get a key
$data = json_decode(file_get_contents("https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url=$url&key=$key"));
$dat = $data->formattedResults->ruleResults;
foreach($dat as $d) {
$name = $d->localizedRuleName;
$score = $d->ruleScore;
print "\nTest: " . $name . "\n";
print "Score: " . $score . "\n";
if ($score != 100) {
if (isset($d->urlBlocks[0]->header->args)) {
$advice_header = replace_placeholders($d->urlBlocks[0]->header->format, $d->urlBlocks[0]->header->args);
}
else {
$advice_header = $d->urlBlocks[0]->header->format;
}
print "Advice: " . $advice_header . "\n";
foreach ($d->urlBlocks[0]->urls as $url) {
$advice = replace_placeholders($url->result->format, $url->result->args);
print $advice . "\n";
}
}
};
function replace_placeholders($format, $args) {
$i = 1;
foreach ($args as $arg) {
$format = str_replace("\$" . $i, "$arg->value", $format);
$i++;
}
return view('pagespeed')->with('format');
}
This is in my views folder: pagespeed.blade.php:
#extends('layouts.app')
#section('content')
<h1>Page Speed</h1>
#endsection
This is my Route in web.php:
Route::get('/pagespeed', 'PagespeedController#pageSpeed');
Change this
$score = $d->ruleScore;
to
$score = $d->score;
Notice: Trying to get property of non-object in /home/....................../modules/webox/webox.php on line 354
Notice: Trying to get property of non-object in /home/......................./webox/webox.php on line 393
Warning: Invalid argument supplied for foreach() in /home/......................../webox/webox.php on line 393
The code: 346-414
346 class WeboxClass{
347 public $total_count = 0;
public $json;
public function __construct($json = "") {
if(strlen($json) == 0){
$json = $this->downloadAutomatakAndReturn();
}
$this->json = json_decode($json);
354 $this->total_count = $this->json->total_count;}
public function downloadAutomatakAndReturn(){
$tmp_dir = ini_get('upload_tmp_dir') ? ini_get('upload_tmp_dir') : (is_callable('sys_get_temp_dir') ? sys_get_temp_dir() : '');
if (!is_file($tmp_dir.'/validboltlista.json') || filemtime($tmp_dir.'/validboltlista.json')+86400<time()) {
$jsonData=file_get_contents('https://api-hu.easypack24.net/v4/machines?type=0');
file_put_contents($tmp_dir.'/validboltlista.json', $jsonData, LOCK_EX);
}else{
$jsonData=file_get_contents($tmp_dir.'/validboltlista.json');
}
return $jsonData;
}
function getAllAutomataAsOptions($selectedAutomata){
$result = "";
$automatak = array();
foreach($this->getAutomatakByTelepules("") as $automata){
/* #var $automata WeboxItem */
$cim = $automata->getAddress_city() . " " . $automata->getAddress_post_code() . ", " . $automata->getAddress_street() . " " . $automata->getAddress_building_no();
$automatak[$automata->getId()] = array(
'text' => $cim . " (" . $automata->getId() . ")",
'id' => $automata->getId(),
'map' => $automata->getMinimap(),
'info' => $automata->getLocation_description()
);
}
sort($automatak);
foreach($automatak as $s){
$selected = (strlen($selectedAutomata) > 1 && $s['id'] == $selectedAutomata ? "selected='selected'" : "");
$result .= "<option value='".$s['id']."' data-map='".$s['map']."' data-info='".$s['info']."' ".$selected.">".$s['text']."</option>\n";
}
return $result;
}
function getAutomatakByTelepules($telepules){
$result = array();
393 foreach($this->json->_embedded->machines as $id => $json){
if($json->address->city == $telepules || strlen($telepules) == 0){
$result[$id] = new WeboxItem($json);
}
}
return $result;
}
function getAutomataByID($id){
foreach($this->json->_embedded->machines as $id => $json){
if($json->id == $id){
return #new WeboxItem($json);
}
}
return null;
}
function getTotalCount() {
return $this->total_count;
}
}
The code is correct.
The problem is with the server. I have installed to another server the prestashop and installed the webox plugin. There is working.
But the problem not with the php.ini file and htaccess file. I have copied all file from one server to another server but not solved the problem.
Summ: The code is correct.
I'm building a HMAC API and I have issues testing the hashing with Paw.
On Paw I have this payload:
GET:/hello/world:"":9a6e30f2016370b6f2dcfb6880501d7f2305d69bout
and a custom HMAC-SHA256 variable (actually function like this that sets it in the X-Hash header.
X-Hash: 4Cq2yehWumDcUk1dYyfhm6qWjJVBkOCB8o12f5l0WGE=
In my PHP API I have the same thing:
GET:/hello/world:"":9a6e30f2016370b6f2dcfb6880501d7f2305d69bout
and used:
hash_hmac('sha256', $this->getPayload(), '9a6e30f2016370b6f2dcfb6880501d7f2305d69bout', false);
So when comparing the hashes:
Paw: 4Cq2yehWumDcUk1dYyfhm6qWjJVBkOCB8o12f5l0WGE=
PHP: 6961b9d1f6e986c49d963cbebd691fa68dfa59b4ce3b7f05320c2d43eae3c7c3
They are very different. Any idea why is that?
Update
Paw Code:
function evaluate(context){
var loc = getLocation(context.getCurrentRequest().url);
var payload = "";
payload += context.getCurrentRequest().method + ':';
payload += loc.pathname + ':';
payload += JSON.stringify(context.getCurrentRequest().body) + ':';
payload += "9a6e30f2016370b6f2dcfb6880501d7f2305d69bout"; // Private key
return payload;
};
function getLocation(href) {
var match = href.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)(\/[^?#]*)(\?[^#]*|)(#.*|)$/);
return match && {
protocol: match[1],
host: match[2],
hostname: match[3],
port: match[4],
pathname: match[5],
search: match[6],
hash: match[7]
}
}
PHP Code (with lots of comments):
if (strpos(strtoupper($authHeader), 'HMAC') !== 0) {
echo 'out';
throw new HttpForbiddenException();
}
else {
$hmacSignature = $app->request->headers()->get('X-Hash');
$publicKey = $app->request->headers()->get('X-Public');
if ( empty($hmacSignature) || empty($publicKey) ) {
echo 'out2';
throw new HttpForbiddenException();
}
else {
$this->hmacManager->setPublicKey($publicKey);
print '$publickey = ' . $publicKey . '<br>';
// Validate if base64_encoded or not
if( base64_decode($hmacSignature, true) !== FALSE ) {
$binaryString = base64_decode($hmacSignature);
$hmacSignature = bin2hex($binaryString);
print 'decoding ' . '<br>';
}
$this->hmacManager->setHmacSignature($hmacSignature);
print '$hmacSignature = ' . $hmacSignature . '<br>';
$this->hmacManager->setRequestMethod($app->request->getMethod());
print 'method = ' . $app->request->getMethod() . '<br>';
$this->hmacManager->setRequestResourceUri($app->request->getResourceUri());
print 'uri = ' . $app->request->getResourceUri() . '<br>';
$requestBody = $app->request()->getBody();
if (Utils::isJson($requestBody)) {
$requestBody = json_decode($requestBody);
}
$this->hmacManager->setRequestBody(json_encode($requestBody));
print 'body = ' . json_encode($requestBody) . '<br>';
print 'private key = ' . $this->hmacManager->getPrivateKey() . '<br>';
$payload = '';
$payload .= $this->hmacManager->getRequestMethod() . ":";
$payload .= $this->hmacManager->getRequestResourceUri() . ":";
$payload .= $this->hmacManager->getRequestBody() . ":";
$payload .= $this->hmacManager->getPrivateKey();
print 'PHP payload [' . $payload . ']';
$this->hmacManager->setPayload($payload);
$hmacValue = $this->hmacManager->generateHmac();
$isValid = $this->hmacManager->isValid($this->hmacManager->generateHmac(), $hmacSignature);
if ($isValid !== true) {
echo 'out3';
throw new HttpForbiddenException();
}
}
}
generateHmac from another class:
public function generateHmac()
{
print 'Generating HMAC' . '<br>';
$algorithm = $this->getAlgorithm();
print 'algo ' . $algorithm . '<br>';
$privateKey = $this->getPrivateKey();
print 'privk ' . $privateKey . '<br>';
if (empty($algorithm)) {
throw new \RuntimeException('Algorithm must be set and not empty');
} elseif (empty($privateKey)) {
throw new \RuntimeException('Private key must be set and not empty');
}
print 'payload ' . $this->getPayload() . '<br>';
$hash = hash_hmac($this->getAlgorithm(), $this->getPayload(), $this->getPrivateKey(), false);
print 'php hasj: ' . $hash . '<br>';
return $hash;
}
Finally, here's the output statements:
$publickey = 95f97b93560f951b4cae46c86d03d9b1a81d4ae8
decoding
$hmacSignature = e02ab6c9e856ba60dc524d5d6327e19baa968c954190e081f28d767f99745861
method = GET
uri = /hello/world
body = ""
private key = 9a6e30f2016370b6f2dcfb6880501d7f2305d69bout
PHP payload [GET:/hello/world:"":9a6e30f2016370b6f2dcfb6880501d7f2305d69bout]
Generating HMAC
algo sha256
privk 9a6e30f2016370b6f2dcfb6880501d7f2305d69bout
payload GET:/hello/world:"":9a6e30f2016370b6f2dcfb6880501d7f2305d69bout
php hash: 6961b9d1f6e986c49d963cbebd691fa68dfa59b4ce3b7f05320c2d43eae3c7c3
Hope it helps!
The paw hash is base64 encoded while the PHP one is in hexadecimal. So decode the paw hash first:
$binary = base64_decode($pawHash);
$hex = bin2hex($binary);
And then compare this to your own hash.
We've just added new Base 64 to Hex conversion dynamic values, this should solve your problem.
Wrap your HMAC signature dynamic value inside the new Base 64 to Hex one, and you'll get a valid hexadecimal signature:
You can install this new dynamic value here: Base 64 to Hex Dynamic Value
This is my code: I want to update the User information and risk factors.
public function getUserById($id)
{
$user = $this->_xml->xpath('//user[#id="' . $id . '"]');
return $user[0];
}
public function updateUser($post)
{
$user = $this->_xml->xpath('//user[#id="' . $post['id'] . '"]');
$user[0]->name= $post["name"];
$user[0]->date_of_birth= $post["date_of_birth"];
$user[0]->sex= $post["sex"];
$user[0]->age= $post["age"];
$this->_xml->asXML($this->path);
}
public function updateFactors($post)
{
$user = $this->_xml->xpath('//user[#id="' . $post['id'] . '"]');
//$user=new stdClass();
$user[0]->alcohol= $post["alcohol"]; // error here!
$user[0]->percentage= $post["percentage"];
$this->_xml->asXML($this->path);
}
if ($param == "edit") {
$id = $arr[1];
$user = $process->getUserById($id);
include 'myuser2.php';
if ($param == "update") {
$post = $_POST;
$process->updateUser($post);
include 'mylistar.php';
$process->listUsers();
}
if ($param == "editfactors") {
$id = $arr[1];
$user = $process->getUserById($id);
include'factors.php';
}
if($param == "updatefactors"){
$post = $_POST;
$process->updateFactors($post);
include 'mylistar.php';
$process->listUsers();
}
So, the "update", "edit", the updateUser function is working... But the Factors part is not! The code is pretty much the same and I donĀ“t know what I'm doing wrong... Seems logic to me.
Error : Creating default object from empty value (in line
$user[0]->alcohol= $post["alcohol"]; )
I've searched and tried $user=new stdClass(); but it doesn't work:
Error: Cannot use object of type stdClass as array
Can you help? :/
i am inserting some data to an salesforce object named as Application__c from php using Soapclient. After connection successfull, i have written following code
$applications = array();
$updateFields = array();
if($_POST['savingsAccountBankName'] != ''){
$updateFields['savings_account_bank_name__c']= $_POST['savingsAccountBankName'];
}
if($_POST['AutoMake'] != ''){
$updateFields['Auto_make__c']= $_POST['AutoMake'];
}
if($_POST['AutoLicense'] != ''){
$updateFields['Auto_license__c']= $_POST['AutoLicense'];
}
$sObject = new sObject();
$sObject->type = 'Application__c';
$sObject->fields = $updateFields;
array_push($applications, $sObject);
try {
$results = $sforceClient->create($applications,'Application__c');
foreach ($results as $result)
{
$errMessage = $result->errors->message;
echo $errMessage;
}
} catch (Exception $e) {
echo 'Salesforce Upsert Error. Please try again later.';
echo '<pre>';
print_r($e);
echo '</pre>';
}
i am getting error "Trying to get property of non-object" at line "$errMessage = $result->errors->message;". What is the problem?
thanks
Be aware that $result is an array..
Try this :
if (!isset($result[0]->success) || ($result[0]->success!=1)) {
$strErrCode = isset($result[0]->errors[0]->statusCode)?
$result[0]->errors[0]->statusCode:'CANNOT_INSERT';
$strErrMsg = isset($result[0]->errors[0]->message)?
$result[0]->errors[0]->message:'Error Trying to insert';
$arrResult = array(
'errorCode' => $strErrCode,
'errorMsg' => $strErrMsg,
'id' => '',
);
error_log( 'Error Trying to insert - [' . $strErrMsg . '] - [' . $strErrCode . ']');
}
if (isset($result[0]->success) && ($result[0]->success==1)) {
$arrResult = array(
'errorCode' => 'SUCCESS_INSERT',
'errorMsg' => 'Insert Success',
'id' => isset($result[0]->id)?$result[0]->id:'1',
);
error_log( 'Success insert - [' . (isset($result[0]->id)?$result[0]->id:'1') . ']');
}
This means that whatever $results contains, it is not an object. Try doing a var_dump() on the variable $results and see what is actually in there. Then you can properly reference it.