Facebook GraphAPI via another webpage php? - php

First: please forgive me - Im a bit of a novice as some of this...
I have a working test site which is running the php facebook SDK to perform some simple graphAPI requests successfully. Namely read a group's feed, which the user is a member of, and process this and display it back on a webpage.
This all works fine, the problem I have encountered is when trying to perform the same request via a php curl POST to another webpage (on the same domain). It seems that the SDK does not carry the expected session to another page when a post request is formed (see "AUTH ERROR2" in code)...this works fine when the following file is included via a "require_once" but not when a curl is made.
I would much rather do a "curl" as Im finding when a "require_once" is done from a page in a different directory level, Im getting php errors of the page not being found - which is expected.
I may just be tackling this problem all wrong...there may be a simpler way to make sure when files are includes, their correct directly level remains intact, or there may be a way to send over the currently authorised facebook sdk session via a curl post. All of which I have tried to no avail, and I would really appreciate any help or advise on this.
Thank you for your time.
//readGroupPosts.inc.php
function readGroupPosts($postVars)
{
//$access_token = $postVars[0];
// ^-- I'm presuming I need this? I have been experimenting appending it to
// the graphAPI request to no success...
$groupID = $postVars[1];
$limit = $postVars[2];
require_once("authFb.inc.php"); //link to the facebookSDK & other stuff
if ($user) {
try {
$groupFeed = $facebook->api("/$groupID/feed?limit=$limit"); //limit=0 returns all;
$groupFeed = $groupFeed['data']; //removes first tier of array for simpler access
$postArray;
for($i=0; $i<count($groupFeed); $i++)
{
$postArray[$i] = array($groupFeed[$i]['from']['name'], $groupFeed[$i]['message'], $groupFeed[$i]['updated_time'], count($groupFeed[$i]['likes']['data']));
}
return $postArray;
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
return "AUTH ERROR1"; //for testing..
}
}
else
{
return "AUTH ERROR2"; //no user is authenticated i.e. $user == null..
}
}

I would much rather do a "curl" as Im finding when a "require_once" is done from a page in a different directory level, Im getting php errors of the page not being found - which is expected.
I may just be tackling this problem all wrong...
Definitively.
Using cURL as a “workaround” just because you’re not able to find your way around your server’s file system is an outrageous idea. Don’t do it. Stop even thinking about it. Now.
there may be a simpler way to make sure when files are includes, their correct directly level remains intact
Yes – for example, to use absolute paths instead of relative ones. Prefixing the path with the value of $_SERVER['DOCUMENT_ROOT'] for example – that way, once you’ve given the path correctly in respect to this “base path”, it does not matter where you’re requiring the file from, because an absolute path is the same no matter from where you look at it.
(And since this is not a Facebook-related problem at all, but just concerns basics of PHP and server-side programming, I’ll edit the tags.)

Related

Laravel - Problem Of How To Tune Strange Behavior With Sending Text Message

I have a very special problem and I don't know how to deal with it.
I have web App in Laravel, when i open index page, I receive text message to my mobile phone.
Problem is, sometimes I receive 2 messages or 3, sometimes 1.
Is there a tool how to debug this strange behavior which is not always the same?
A few words about my code:
user opens the page, and because its first visit Session doesn't have attribute message_sent and SendTextMessage::SendMessage($phoneNumber, $id_message, $smsCode, $newDateFormat); is executed. After that Session has message_sent and can't be sent again, for example if I refresh the page.
SendTextMessage::SendMessage() is Class in Laravel Helpers.
controller code:
public function index($url_attribute, $id_message, Request $request)
{
if(!Session::has('message_sent'))
{
$user = User::where('id_message', $id_message)->first()->toArray();
$phoneNumber = $user['mobile_phone'];
$smsCode = $user['sms_code'];
$newDateFormat = date("d.m.yy", strtotime($smsExpirationTime));
$request->session()->flash('message', 'Text message sended.' );
SendTextMessage::SendMessage($phoneNumber,$id_message, $smsCode, $newDateFormat);
Session::put('message_sent', true);
}
return view('login');
}
SendTextMessage Class:
class SendTextMessage
{
public static function SendMessage($phoneNumber, $id_message, $smsCode, $newDateFormat)
{
$sms = new Connect();
$sms->Create("user","pass",Connect::AUTH_PLAIN);
$sms->Send_SMS($phoneNumber,"Message");
$sms->Logout();
}
}
Many thanks for any tip or help.
UPDATE:
problem is only in Chrome.
Edge and internet explorer are fine.
As this script runs on server-side the browser shouldn't be an issue. Based on your code provided, there is no clear answer to give here.
Please try the following in order to debug your problem:
Log messages at each stage of the script in order to see which part was called how often. That will help you to locate the problem. You can use \Log::error("Message") to do that.
Once you know where the problem might be, try to log "decision" making / mission critical variables to logile as well. E.g. \Log::error($session) so that you can understand why that problem might occur. One reason could be that you have a bad configured session caching or your cookies might be messed up. At some point there is probably a piece of data not the way you expect it to be.
You should maybe try to change the way you use Laravel Session.
You indicated that it was working fine on some browsers, that means your server-side code is correct so far, but there is someting messing with Chrome… From there,
if you take a quick look at the Laravel Session doc, you'll see that Session can be stored in cookies, and I bet that this is your actual setup (check in your .env file the SESSION_DRIVER constant, or in your config/session.php file).
If so, to confirm that this cookies-based session setting is the culprit, you might want to change the Session config to make it browser-independent: any other option than cookies will work, the database or file options might be the easier to setup… And if it works I would strongly encourage you to keep using this no-cookie setting to make your code browser-safe.

PHP getting remote url image file size doesn't wait for content-length header to be set

I know this question has been asked millions of times, but please actually take the time to understand my problem before marking as duplicate or closing.
So I am using the following code. For some reason it gets all of the correct header information the first time I run the code EXCEPT for content-length. The second time I run the code it actually gets it correctly. I am retrieving the images from Facebook API if that changes anything.
function remote_filesize($url) {
$data = get_headers($url, 1);
if(isset($data['Content-Length'])) {
return (int) $data['Content-Length'];
}
else {
return -1;
}
}
Edit
Gotta love when you get downvoted with no explanation. Personally I think it should be required to provide a reason.
Anyway, this is still an issue, but in case anyone googling this needs a solution for getting the remote filesize, I would suggest using this awesome snippet from the PHP docs http://php.net/manual/en/function.filesize.php#114952
Sounds like a server caching issue.
So you may have to issue a full GET request instead of just a HEAD request.
Also, maybe check different casing -- 'content-length:' -- lowercase.

Using the Flickr API how can I get back the absolute path to an image?

Ok, this is not only how to get the URL to an image, it is a little more than that and I proceed to explain trying to be as clear as possible, I might point out that I am a totally newbie on this, I am a PHP Junior programmer and this is my first time using Flickr at all:
I have PHP website online, I have done all what is related to Key, Secret, Token and that. So basically I have a public image uploader that works fine. You could go into my website pick a picture and upload them to my Flickr account.
Now, they PHP for doing that is basically this one:
$apiKey = "(my API Key)";
$apiSecret = "(my API Secret)";
$permissions = "write";
$token = "(my Token)";
$f = new phpFlickr($apiKey, $apiSecret, true);
$f->setToken($token);
$f->sync_upload($path, $title);
return $f;
The phpFlickr object comes in the Flickr API, and $f in this case gives me back an array with the picture ID and some other data.
How can I get an absoulte path to the just uploaded picture in the form www.flickr.com/something/myPicture.jpg in order to build a HTML tag?
Probably what $f gives me is not enough. Any light over this would be great!
Hope it was clear.
Before I start writing, take a look at these links. They might have what you're looking for:
http://www.flickr.com/services/api/misc.urls.html
http://www.flickr.com/services/api/flickr.photos.getInfo.html
If you're trying to build an absolute path to a photo, you have to build the entire path based on the information that you get from a successful API call which is going to be located in $f. Looking at the first link I posted, there are a few ways to build an absolute path for a picture given that you have all of the information needed. The first method is to build the photo source URL, which comes in this format:
http://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}.jpg
or
http://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}_[mstzb].jpg
or
http://farm{farm-id}.staticflickr.com/{server-id}/{id}_{o-secret}_o.(jpg|gif|png)
The information required to build these links can be found in a successful call to the photos.getInfo API call that I posted above. Building the absolute path is as simple as just combining all of the variables together:
(I haven't touched PHP in a while, bear with me)
my $link = 'http://farm' . $farmid . '.staticflickr.com/' . $serverid . '/' . $id . '_' . $secret . '.jpg';
The second method is to build the webpage URL. This can either be grabbed directly from the photos.getinfo API call, or built manually given that you have the user-id and/or photo-id. If you have the required information, building the link is almost the same as the way I did it above. Check out the first link I posted for the actual URLs you need to build.
One last thing I should mention is that you should make sure that your API calls are working. I spent so much wasted time back when I was first learning how to use API's because I never checked the output of what the API calls were returning or my authentication was incorrect. Doing a vardump($f) (or something similar) and seeing what the calls are returning might help you visualize what needs to be done to get the information you need.
Ok, I just found how. In case anyone is interested:
$f = new phpFlickr($apiKey, $apiSecret, true);
$f->photos_getInfo(PHOTO_ID);
That gives you back an array with all what you need to complete the URL.

sending message out of a sandbox to a custom application

I got an application which uses flash for it's interfaces, and I want to extract information from this application, and parse/use it in my own application (which processes the data, stores the essentials in a mysqldb and so on).
The .swf files are written in AS2 and can be modded quite easily.
So my goal is to send information (really just information. Being able to send numbers (of a at least decent size) would enable me to implement my own protocol of encoding and partitioning) by any means, I am certainly not picky about the means.
Here is my current approach (not my own idea, credits to koreanrandom.org. I merely use their source to learn):
use DokanLib to mount a virtual filesystem (and implement the getFileInformation-handler)
use LoadVars inside the AS2-Environment with parameters like "../.logger/#encoded_information"
since getFileInformation gets the accessed filename as a parameter, I can decode it, put several ones back together (if they had to be splitted, windows does not seem to like filenames with several hundred characters length) and use the decoded data
However, my application causes bluescreens quite often (dont ask why. i got no clue, the bluescreen messages are always different) and the devs at koreanrandom.org dont like being asked too many questions, so i came to ask here for other means to pass information from a sandboxed flash-environment to a prepared listener.
I started thinking about weird stuff (ok, abusing a virtual filesystem & filenames as a means of transport for information might be weird too - but it is still a great idea imo) like provoking certain windows-functions to be called and work with global hooks, but i didnt grasp a serious plan yet.
The "usual" methods like accessing webservers via methods like this dont appear to work:
var target_mc = createEmptyMovieClip("target_mc", this.getNextHighestDepth());
loadVariables("http://127.0.0.1/Tools/indata.php", "target_mc", "GET");
(indata.php would have created a file, if it was accessed, but it didnt.)
XMLSocket doesnt work either, i tried the following code sample (using netcat -l on port 12345):
Logger.add("begin");
var theSocket:XMLSocket = new XMLSocket();
theSocket.onConnect = function(myStatus) {
if (myStatus) {
Logger.add("XMLSocket sucessfully connected")
} else {
Logger.add("XMLSocket NO CONNECTION");
}
};
theSocket.connect("127.0.0.1", 12345);
var myXML:XML = new XML();
var mySend = myXML.createElement("thenode");
mySend.attributes.myData = "someData";
myXML.appendChild(mySend);
theSocket.send(myXML);
Logger.add("socket sent");
doesnt work at all either, the output of the logger was just begin and socket sent
Annotation: the logger was created by the guys from koreanrandom.org and relies on their dokan implementation, which never caused a bluescreen for me. cant spot my mistake in my implementation though, so i started to look for other means of solving my problem.
EDIT: what the hell is wrong with your "quality messages system"? appearently it didnt like me using the tags "escaping" and/or "information".
hmm, hard to say, try sendAndLoad instead of loadVariables
example:
var result_lv:LoadVars = new LoadVars();
var send_lv:LoadVars = new LoadVars();
send_lv.variable1=value1;
send_lv.variable2=value2;
f=this;//zachytka
result_lv.onLoad = function(success:Boolean) {
if (success) {
trace("ok");
} else {
trace("error");
}
};
send_lv.sendAndLoad("http://127.0.0.1/Tools/indata.php", result_lv, "GET"); //you may also use POST
this should work. the reason it's not working may also be flash security settings. try either moving the stuff to a real server or open up the flash settings manager (there's an alternative online version too) and add the 127.0.0.1 to trusted domains and/or testing file location to the trusted locations (i use C:*)

Posting and executing a string as PHP?

I'm building an application that's self-hosted, and I'd like to have some form of licensing to minimize fraudulent downloads/distribution.
Of course, I'm well aware that being self-hosted someone could simply rip out all license features from the source-code, but the con's of using a compiler like Zend Guard or ionCube far outweigh the pro's in my opinion - nonetheless I'd like to have some basic form of license security.
What I originally had in mind to do was: user logs in with license on app -> app posts license to my server -> server sends a response via a HTTP GET request -> app evaluates response, and if license is valid sets a value in a session variable (A), if invalid returns to login screen with an error.
The problem with this is, the evaluation of response/session setting is readily available in a application file, so if the user knows a little PHP and checks in on that source code, they'll realize all they'll need to do is set a session themselves with a particular $_SESSION['_valid_license'] value, and they'll be good to go.
What I was considering doing to make it a little less easy was (if possible) to post PHP back as a response, and then have the application file execute it, for example:
My original code:
$response = $_GET['response'];
if($response == "fjdkuf9") {
start_session();
$_SESSION['_valid_license'] = "YES";
header("Location:" . $rp . "/admin/");
} else {
header("Location:" . $rp . "/login/?err=1");
}
My new concept:
$response = $_POST['response'];
str_replace("\", "", $response);
With the following being posted as response:
start_session();
\$_SESSION[\'_valid_license\'] = \"YES\";
header(\"Location:\" . \$rp . \"/admin/\");
Would that execute $response as actual PHP code after str_replace()? If possible, this would be great, as it would mean evaluation would be done on my server rather than within the self-hosted app itself.
Your second solution is just as insecure as the first. here's what I would do:
Your application POSTS to your server a serial number or some other identifying information.
Your server validates the serial number against the user's account or whatever and returns a unique response.
If that response is successful, you allow the user to continue. Obviously you'd want to implement some sort of caching mechanism here so you're not having to hit you server on every page view.
Putting the responsibility of validation on your server instead of self-hosted code is much more secure. You would need to encrypt the data that is sent BTW so that someone couldn't simply emulate the success response, but you get the idea.

Categories