Fatal error: Method name must be a string - php

I'm getting error:
Fatal error: Method name must be a string in C:\xampp\htdocs\index.php on line 15"
LINE 15:
$obj = new $url[0]();
CODE:
<?php
error_reporting(E_ALL ^ E_NOTICE);
$url = $_GET['url'];
$url = explode('/', $url);
if (!file_exists('controllers/' . $url[0] . '.php')) {
$url[0] = 'error'; // error kontroleris
}
require 'controllers/' . $url[0] . '.php';
$obj = new $url[0]();
$obj->$url[1]();
BTW.: Script is not finished yet.

Actually, this syntax:
$urls = array('DOMDocument');
$dom = new $urls[0]('');
var_dump( $dom );
... is valid even in PHP 5.2 (proof). But this line...
$obj->$url[1]();
... is pretty damn able (another proof) to throw exactly the same error as you've shown, as you don't check for url array length anywhere in your code.

$_GET['url'] = 'foo/bar'; // temp set $_GET
$url = $_GET['url'];
$url = explode('/', $url);
if (file_exists('controllers/' . $url[0] . '.php')){
require 'controllers/' . $url[0] . '.php';
}else{
$url[0] = 'error';
}
$obj = new URL;
if(method_exists($obj,$url[0])){ // test that method exists
echo $obj->$url[0](); // or whatever your handling may be
}
class URL{
public function error(){
$return = 'this is for the error handling';
return $return;
}
}

Related

Gigya PHP Sdk - Comment Notifications

I'm trying to use the Gigya's Comment Notification functionality and I've followed the guidelines at:
http://developers.gigya.com/010_Developer_Guide/18_Plugins/022_Comments_Version_2/Comment_Notifications
I've developed the following code:
<?php
require_once('GSSDK.php');
$event = $_POST['event'];
$eventData = $_POST['eventData'];
$nonce = $_POST['nonce'];
$timestamp = $_POST['timestamp'];
$signature = $_POST['signature'];
$signatureBase = sprintf("%s_%s_%s_%s", $event, $eventData, $nonce, $timestamp);
$expectedSignature = SigUtils::calcSignature(
$signatureBase,
MY_SECRET_KEY);
if($signature !== $expectedSignature) {
header('HTTP/1.0 403 Forbidden');
die();
}
//Some other stuff
exit();
?>
But it never gets to the "//Some other stuff" part.
Always the expected signature differs from the signature provided by the Gigya's server.
What am I doing wrong?
Try the following code instead:
<?php
static function calcSignature($baseString,$key)
{
$baseString = utf8_encode($baseString);
$rawHmac = hash_hmac("sha1", utf8_encode($baseString), base64_decode($key), true);
$sig = base64_encode($rawHmac);
return $sig;
}
function checkSignature()
{
$event = $_POST["event"];
$eventData = $_POST["eventData"];
$nonce = $_POST["nonce"];
$timestamp = $_POST["timestamp"];
$signature = $_POST["signature"];
$signatureBase = $event . "_" . $eventData . "_" . $nonce . "_" . $timestamp;
$secret = "[your gigya secret key]";
$expectedSignature = calcSignature($signatureBase, $secret);
// Now compare the expectedSignature value to the signature value returned in the callback
if ($signature !== $expectedSignature)
{
header('HTTP/1.0 403 Forbidden');
die();
}
}
checkSignature();
//Some other stuff
exit();
?>
This code removes the dependency on GigyaSDK just to check the signature. The method provided is the same method that the GigyaSDK uses, but the advantage here is that this is a much smaller memory footprint since the entire GigyaSDK does not need to be loaded.
Additionally, I'm not sure if it was intentional, but your comparison has the code:
if(!$signature !== $expectedSignature) {
Instead of:
if ($signature !== $expectedSignature) {
I'm not quite sure what the purpose of the extraneous logical-NOT operator on $signature is supposed to accomplish, but it seems like this would cause unexpected behavior.

Getting error during Salesforce integration in PHP

I'm getting this error " Ooop! Error: Element {}item invalid at this location " at the time of calling Salesforce web service in PHP.
Bellow are my approaches:
require_once('salesforceAPI/soapclient/SforceEnterpriseClient.php');
require_once('salesforceAPI/soapclient/SforceHeaderOptions.php');
$sfdc = new SforceEnterpriseClient();
$SoapClient = $sfdc->createConnection('enterprise.wsdl.xml');
$loginResult = false;
$loginResult = $sfdc->login(USER, PASSWORD . SECURITY_KEY);
$parsedURL = parse_url($sfdc->getLocation());
define("_SFDC_SERVER_", substr($parsedURL['host'], 0, strpos($parsedURL['host'], '.')));
define("_WS_NAME_", 'salesforceAPI/Ctest');
define("_WS_WSDL_", _WS_NAME_ . '.xml');
define("_WS_ENDPOINT_", 'https://' . _SFDC_SERVER_ . '.salesforce.com/services/wsdl/class/' . _WS_NAME_);
define("_WS_NAMESPACE_", 'http://soap.sforce.com/schemas/class/' . _WS_NAME_);
$client = new SoapClient(_WS_WSDL_);
$sforce_header = new SoapHeader(_WS_NAMESPACE_, "SessionHeader", array("sessionId" => $sfdc->getSessionId()));
$client->__setSoapHeaders(array($sforce_header));
$method = $client->__getFunctions();
$wsParams = array('accName' => 'dasarathi');
$client->cInsert($wsParams);
I have no clue for solution.
It was a file path issue. Below is the rectification:
define("_WS_NAME_", 'salesforceAPI/Ctest');
// there is no such path http://soap.sforce.com/schemas/class/slesforceAPI/Ctest
define("_WS_NAMESPACE_", 'http://soap.sforce.com/schemas/class/' . _WS_NAME_);
I just redeclared the WS_NAME constant:
define("_WS_NAME_", 'Ctest');

how to handle expired access token in facebook

I found following code from here, it is supposed to work and it has 2 errors.
First one is : Trying to get property of non-object on line 38, which starts from
if ($decoded_response->error)
Second error is Trying to get property of non-object on line 54 which starts from
echo("success" . $decoded_response->name);
So following code is my full code that gets access token.
<html>
<head></head>
<body>
<?php
require_once('src/facebook.php');
include_once('src/base_facebook.php');
$app_id = "413030352142786";
$app_secret = "518852750047ba579316a19d81c1e115";
$my_url = "134061970136571";
// known valid access token stored in a database
$access_token = "CAAF3ph9rwcIBAD5GrDLZBI6TFKlSb4jccEmIorCVjtfIeKIq7FjGKntMI5qnZCaNlXL8qy2g0gbjof3sRJYmgoDckG5ZBWpZBHjgZAn1e3sHTyxDdWwcCaZAiCylP5ayoWIMZBZCgNBL71I3myFYoDUYNZB4dH0xKJjAZD";
#$code = $_REQUEST["code"];
// If we get a code, it means that we have re-authed the user
//and can get a valid access_token.
if (isset($code)) {
$token_url="https://graph.facebook.com/oauth/access_token?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret
. "&code=" . $code . "&display=popup";
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
}
// Attempt to query the graph:
$graph_url = "https://graph.facebook.com/me?"
. "access_token=" . $access_token;
$response = curl_get_file_contents($graph_url);
$decoded_response = json_decode($response);
//Check for errors
if ($decoded_response->error) {
// check to see if this is an oAuth error:
if ($decoded_response->error->type== "OAuthException") {
// Retrieving a valid access token.
$dialog_url= "https://www.facebook.com/dialog/oauth?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode($my_url);
echo("<script> top.location.href='" . $dialog_url
. "'</script>");
}
else {
echo "other error has happened";
}
}
else {
// success
echo("success" . $decoded_response->name);
echo($access_token);
}
// note this wrapper function exists in order to circumvent PHP’s
//strict obeying of HTTP error codes. In this case, Facebook
//returns error code 400 which PHP obeys and wipes out
//the response.
function curl_get_file_contents($URL) {
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, $URL);
$contents = curl_exec($c);
$err = curl_getinfo($c,CURLINFO_HTTP_CODE);
curl_close($c);
if ($contents) return $contents;
else return FALSE;
}
?>
</body>
</html>
Thank you for your reply !!!

Alexa api in php

This is their sample I don't know how to get it working.
http://aws.amazon.com/code/AWIS/402
It keeps showing: Usage: $argv[0] ACCESS_KEY_ID SECRET_ACCESS_KEY site\n
It is not working, when you fill in:
$urlInfo = new UrlInfo("myaccessKeyId", "mysecretAccessKey", "stackoverflow.com");
How do I fix this issue?
public function UrlInfo($accessKeyId, $secretAccessKey, $site) {
$this->accessKeyId = $accessKeyId;
$this->secretAccessKey = $secretAccessKey;
$this->site = $site;
}
/**
* Get site info from AWIS.
*/
public function getUrlInfo() {
$queryParams = $this->buildQueryParams();
$sig = $this->generateSignature($queryParams);
$url = 'http://' . self::$ServiceHost . '/?' . $queryParams .
'&Signature=' . $sig;
$ret = self::makeRequest($url);
echo "\nResults for " . $this->site .":\n\n";
self::parseResponse($ret);
}
The script is meant to be run from the command line like so:
php urlinfo.php ACCESS_KEY_ID SECRET_ACCESS_KEY site
It's in the readme. If you just want to use the class, you should take out the stuff after line 122 in the php file.

PHP If file_get_contents fails, do this instead

I have a function to translate the current text string using the Free Bing translator API. I just want to make sure if anything fails or something happens with the Application ID or I go over on requests, I don't want a big error to show.
The code I have right now is:
$translate_feed = file_get_contents('http://api.microsofttranslator.com/v2/Http.svc/Translate?appId=' . BING_APPID . '&text=' . urlencode($text) . '&from=en&to=' . $to_lan . '');
$translate = simplexml_load_string($translate_feed);
return $translate[0];
What I want to happen is if anything fails, so if I add in another character to the URL to make it invalid then I want it to just return $text so at least something shows.
Thanks!
Have you tried failing it on purpose to see what happens?
If it's an exception, just catch it and handle it...
try{
//enter code to catch
}catch(Exception $ex){
//Process the exception
}
If there is an error outputted by the function, just # to hide the error and handle the incorrect output of $translate_feed or $translate manually.
You can try failing it on purpose by simply passing an invalid URI to file_get_contents and then forcefully feed non XML or invalid XML to simplexml_load_string to see what happens.
$translate_feed = file_get_contents('http://api.microsofttranslator.com/v2/Http.svc/Translate?appId=' . BING_APPID . '&text=' . urlencode($text) . '&from=en&to=' . $to_lan . '');
if ( $translate_feed === false )
{
echo "failed";
}
You can do like this
if(#file_get_contents("yourFilePath.txt")){
echo "success";
}
/*
It's a modified file_get_contents()
get_contents(filename, use_include_path, context, offset, maxlen)
*/
function get_contents($url, $u = false, $c = null, $o = null) {
$headers = get_headers($url);
$status = substr($headers[0], 9, 3);
if ($status == '200') {
return file_get_contents($url, $u, $c, $o);
}
return false;
}
echo get_contents('https://example.com/');
there is $http_response_header variable is being created in local scope that we can use it to check headers returned from server. Here is my implementation:
public function getData($url)
{
try {
$response = #file_get_contents($url);
if (isset($http_response_header)) {
if (!in_array('HTTP/1.1 200 OK', $http_response_header) &&
!in_array('HTTP/1.0 200 OK', $http_response_header)) {
throw new \Exception('Server did not return success header!');
}
}
return $response;
} catch (\Exception $ex) {
throw new TransportException($ex->getMessage(), $ex->getCode(), $ex);
}
}
if( !$translate_feed) return "Failed";
$translate_feed = file_get_contents('http://api.microsofttranslator.com/v2/Http.svc/Translate?appId=' . BING_APPID . '&text=' . urlencode($text) . '&from=en&to=' . $to_lan . '');
$result=$text;
if ($translate_feed) {
$translate = simplexml_load_string($translate_feed);
if (is_array($translate)) $result=$translate[0];
}
return $result;

Categories