facebook php access token - php

I have all of the files (facebook.php, base_facebook.php, index.php) in the same directory. My server(s) are Apache, and both support php.
My code:
<html>
<body>
<?php
try
{
echo("STARTING<br>");
require("facebook.php");
}
catch(Exception $e)
{
echo("ERROR1: $e");
}
try
{
$facebook = new Facebook("***","###");
}
catch(Exception $e)
{
echo("ERROR2: $e");
}
$token = $facebook->getAccessToken();
echo("Access token: ".$token."<br>");
My text output is as follows:
STARTING
ERROR1: Object id #1before create fb instance
Fatal error: Class 'Facebook' not found in /(FILE PATH)/index.php on line 16
Note: line 16 is: $facebook = new Facebook("***","###");
The first catch statement is printing: Object Id #1. Then it does my next print statement. Then it returns Fatal Error that is not caught. What am I missing here?
Why can the server not get the correct access token?

You failed to require the facebook.php, hence the ERROR1: Object id #1 - you're trying to echo out the exception error object. Try
catch ($e) {
die($e->getMessage());
}
instead.
You should not catch that kind of error. if a require fails, the only useful solution is to abort execution, because you've not gotten what you REQUIRED to continue execution.
Basically you've implemented a PHPized version of visual basic's on error resume next, with all the nasty stupidity that goes with it.

You should put the code before the header is sent :
Go here for further information : https://developers.facebook.com/docs/reference/php/
Basically, put this on very on top of your code :
<?php
require_once("facebook.php");
$config = array();
$config[‘appId’] = 'YOUR_APP_ID';
$config[‘secret’] = 'YOUR_APP_SECRET';
$config[‘fileUpload’] = false; // optional
$facebook = new Facebook($config);
?>
Then load your HTML (In MVC style will be better for maintenance ;-)

Related

PHP OAuth errors handling

I am using an OAuth library to connect to Etsy shop API. Code looks like this:
foreach ($transactions as $transactionSingle) {
try {
$oauth = new OAuth('xxx', 'xxx',
OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
$oauth->setToken($access_token, $access_token_secret);
$data = $oauth->fetch("https://openapi.etsy.com/v2/users/".$transactionSingle['buyer_id']."/profile", null, OAUTH_HTTP_METHOD_GET);
$json = $oauth->getLastResponse();
$results = json_decode($json, true);
} catch (OAuthException $e) {
return null;
}
}
Now the problem is that I run this code multiple times on foreach and if this URL is wrong and it fails to get any data - the whole function stops and doesn't continue anymore. It works perfectly until an old user ID is passed to URL and $oauth->fetch just reuturns message :
Invalid auth/bad request (got a 404, expected HTTP/1.1 20X or a
redirect)
Any ideas how to continue to run the function despite any errors?
The problem was in error cathing itself. Needed backslash on
catch (\OAuthException $e) {
}
Now the code catches the errors and continues if no code is provided inside catch.

Memory Usage on Fatal Error, should I Try Catch every line?

What happens exactly on a PHP fatal error regarding memory usage and object destruction? Does memory automatically get freed on a fatal error?
I really would like to know more about the subject, and couldn't find it in the PHP manual.
Should I worry about Try{}catch{} my functions so I can destruct my objects in the catch{} or does it happen automatically ? Is it instant ?
Added Example:
$objectOne = new stdClass();
$objectOne->statement = "Hello";
$objectTwo = new stdClass();
randomFunctionThatShouldCauseAnError();
$objectTwo->statement = "Error before this";
In the above axample, will $objectOne be freed automatically on the error caused by randomFunctionThatShouldCauseAnError ? or I should do the following:
$objectOne = new stdClass();
$objectOne->statement = "Hello";
$objectTwo = new stdClass();
try{
randomFunctionThatShouldCauseAnError();
}catch (Error $e){
$objectOne = null;
$objectTwo = null;
}
$objectTwo->statement = "Error before this";
Sorry for the spam of questions, but I've been struggling with this for a while now, and I would like to know how to handle memory in case of a fatal error in my code.
Thanks a lot!
Should I worry about Try{}catch{} my functions so I can destruct my objects in the catch{} or does it happen automatically ? Is it instant ?
You should catch the exceptions if you want to keep the code running, otherwise you can easily have unexpected behavior from your program.
If you do not catch an exception, a fatal error can be thrown and stop your code execution and, consequently, the OS will dump anything from memory.
Also you should take care not to expose sensitive information (i.e. An PDOException can throw your SQL password to user's screen).
Try this:
<?php
class Test {
public $param;
public function canThrowAnError() {
$this->param = "Changed right before the exception";
if (true) {
throw new \Exception("Message", 10023);
}
}
}
And then
$test = new Test();
$test->param = "Yay, it works still...";
try {
$test->canThrowAnError();
} catch (\Exception $e) {
// Do something. Log, inform the user..
}
echo $test-param;
If you catch the exception the code will go on and everything will be as right before the exception. The following will result in:
"Changed right before the exception"
You should treat the error accordingly so you don't have unexpected behavior.

PHP PEAR error Class 'XML_Serializer' not found?

I need to turn an array into an XML file.
I have the following code:
<?php
$nouser = 'There is no user with that ID in the database.';
try {
$handler = new PDO('sqlite:Ebsco.db');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$name = '';
if (isset ($_POST['postname'])) {
$name = $_POST['postname'];
};
$query = $handler->query('SELEcT * FROM Users WHERE ID='.$name);
$User = $query->fetch(PDO::FETCH_ASSOC);
if ($User) {
$Serializer = &new XML_Serializer();
$XML = $Serializer->serialize($User);
print_r($XML);
print_r($Serializer);
}
else {
echo $nouser;
}
}
catch (PDOException $e) {
echo $nouser;
die();
}
?>
The code works fine for retrieving the array and passing it back to the html as an array, but I am having issues with the PEAR XML_SERIALIZER.
I have downloaded the files and placed them in the php/pear/xml folder (except for "package" which I left in the main pear folder, as I have no idea what it is meant to do), and checked the phpinfo() to make sure the include_path leads to php/pear.
However, when I add the XML_SERIALIZER, I get the following error:
Fatal error: Class 'XML_Serializer' not found in...
I am new to PEAR so I'm not sure if I installed everything correctly (other than putting the files in the library, is there anything else I need to do?), or if this is caused by another issue.
Thanx
You need to include the file manually, there is no autoloading with PEAR1 packages except you do that yourself.
require_once 'XML/Serializer.php';

Soundcloud API Check if a user is following another user

I'm trying to figure out if a user is following another user on Soundcloud using the Soundcloud API and php.
So far I came across a solution which would either return an object (user) or a 404 error:
$test = json_decode($client->get('/users/{id1}/followers/{id2}'));
I've tried it multiple times with different user IDs but I always receive a the following error message:
'Services_Soundcloud_Invalid_Http_Response_Code_Exception' with message 'The requested URL responded with HTTP code 404.'
I know that this is supposed to be the error message which informs me that user2 is not following user1. However I've tried this snippet with ids where I know a reciprocal following exists for sure.
Any suggestions on how this can be solved?
Update (21.05.15):
I've read through some of the Soundcloud documentation and cam across a code snippet:
<?php
require_once 'Services/Soundcloud.php';
// create a client object with access token
$client = new Services_Soundcloud('YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET');
$client->setAccessToken('YOUR_ACCESS_TOKEN');
// Follow user with ID 3207
$client->put('/me/followings/3207');
// Unfollow the same user
$client->delete('/me/followings/3207');
// check the status of the relationship
try {
$client->get('/me/followings/3207');
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
if ($e->getHttpCode() == '404')
print "You are not following user 3207\n";
}
?>
This is pretty much what I was referring to. However if I open a php page with this script the result is always one of three cases:
You are not following user 3207 (expected output)
No output (I'm following the user)
Uncaught exception 'Services_Soundcloud_Invalid_Http_Response_Code_Exception' with message 'The requested URL responded with HTTP code 404.'
The third option is either referring to $client->put or $client->delete
Here is how i would do this:
<?php
require_once 'Services/Soundcloud.php';
$client = new Services_Soundcloud(
'xxxxxxxxxxxxxxxxxxx160', 'xxxxxxxxxxxxxxxxxx34dd1 ');
$userid = 1672444;
$followerid = 383228;
$yesno = '';
try {
$response = json_decode($client->get('users/'.$userid.'/followers'), true);
$yesno = IdInArray($response, $followerid);
echo $yesno;
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
function IdInArray($response, $followerid){
echo $followerid.'<br/>';
for($i = 0; $i < count($response); ++$i) {
if($response[$i]['id'] == $followerid){
return 'yolo';
}
else{
return 'nolo';
}
}
}
?>

Using additional data in php exceptions

I have php code that execute python cgi and I want to pass python trace (returned from cgi) as extra data to php exception how can I do this and how can I get that value from catch(Exception e) { (It should check if that extra value exesit or not).
I have code like this:
$response = json_decode(curl_exec($ch));
if (isset($response->error)) {
// how to send $response->trace with exception.
throw new Exception($response->error);
}
return $response->result;
and I use json-rpc library that should return that data to the user:
} catch (Exception $e) {
//catch all exeption from user code
$msg = $e->getMessage();
echo response(null, $id, array("code"=>200, "message"=>$msg));
}
Do I need to write new type of exception or can I do this with normal Exception? I would like to send everything that was thrown in "data" =>
You need to extend Exception class:
<?php
class ResponseException extends Exception
{
private $_data = '';
public function __construct($message, $data)
{
$this->_data = $data;
parent::__construct($message);
}
public function getData()
{
return $this->_data;
}
}
When throwing:
<?php
...
throw new ResponseException($response->error, $someData);
...
And when catching:
catch(ResponseException $e) {
...
$data = $e->getData();
...
}
Dynamic Property (not recommended)
Please note that this will cause deprecation error in PHP 8.2 and will stop working in PHP 9 according to one of the PHP RFC https://wiki.php.net/rfc/deprecate_dynamic_properties
As the OP asking about doing this task without extending Exception class, you can totally skip ResponseException class declaration. I really not recommend do it this way, unless you've got really strong reason (see this topic for more details: https://softwareengineering.stackexchange.com/questions/186439/is-declaring-fields-on-classes-actually-harmful-in-php)
In throwing section:
...
$e = new Exception('Exception message');
$e->data = $customData; // we're creating object property on the fly
throw $e;
...
and when catching:
catch(Exception $e) {
$data = $e->data; // Access data property
}
September 2018 edit:
As some of readers found this answer useful, I have added a link to another Stack Overflow question which explains the downsides of using dynamically declared properties.
Currently, your code converts the response text directly into an object without any intermediate step. Instead, you could always just keep the serialized (via JSON) text it and append it to the end of the Exception message.
$responseText = curl_exec($ch);
$response = json_decode($responseText);
if (isset($response->error)) {
throw new Exception('Error when fetching resource. Response:'.$responseText);
}
return $response->result;
Then you could just recover everything after "Response:" in your error log and optionally de-serialize it or just read it.
As an aside, I would also not count on the server sending JSON, you should verify that the response text was actually parseable as JSON and return a separate error for that if it isn't.

Categories