Facebook PHP-SDK + jQuery AJAX - facebook

Im creating a Facebook app using PHP-SDK.
In order to find a user's uid I do:
index.php file
$user_id = $facebook->getUser();
if($user_id == 0) // not logged in user
{
// do stuff to log in user and get the current user id
}
Inside index.php file I have the following jQuery code:
var get_url =
'do_stuff.php?id=' + <?php echo $user_id; ?> + '&field1=' + field1 + '&field2='+ field2;
$.get(get_url, function(data) {
alert("data: " + data);
});
do_stuff.php inserts data on my MySQL database based on field1 and field2. I want to be sure that the data inserted are really from user with $user_id. And not just somebody who did a fake request like:
http://myapp.com/do_stuff.php?id=fake_user_id&field1=...&field2=...
So, I added the $user_id = $facebook->getUser(); at do_stuff.php but instead of returning the current user id (which is visible at index.php), it returns 0 which means no user is logged in. Why is this?
How I can fix it? So I will be sure that the data inserted on my MySQL database are from a real user and not a fake one?

This is because as far as do_stuff.php is concerned, no one is logged in. You probably need to look at capturing the access token and using that in do_stuff.php.

Related

how to auto login after submitting sign up form in php?

i am using php mysqli coding,i create sign up form and login form both are working separately but now i want to provide login after sign up successfully.
this is my sign up code:
{
# insert data into mysql database
$sql = "INSERT INTO `users` (`id`, `username`, `password`, `phone`, `email`)
VALUES (NULL, '{$name}', '{$password}', '{$phone}', '{$email}')";
$query="SELECT * FROM users WHERE email= '$email'";
if ($mysqli->query($sql)) {
$reslt=$mysqli->query($query);
$usr=$reslt->fetch_array();
$_SESSION[user_email]=$usr['email'];
redirect_to("profile.php?email={$_SESSION['user_email']}");
} else {
echo "<p>MySQL error no {$mysqli->errno} : {$mysqli->error}</p>";
exit();
}
}
I tried this way but insertion operation is doing properly but page is refreshing and not redirecting to "profile.php" which is i mentioned in code
first of all, I would suggest that for for a login you check both email and password. Your query should look like:
$query="SELECT * FROM users WHERE email= '$email' and password = '$password'";
Next, if ($mysqli->query($sql)) { just verifies if the sql operation has succeeded. If the user and password are wrong, the sql will succeed but you will have no rows returned.
What you have to do is to verify that you have only 1 row returned by the query. In fact your code should more look like:
...
// check how many users correspond to the query
// ! the result will be an arry
$users = $reslt->fetch_array();
// if I have only one user, login is successfull
if(count($users) === 1) {
$_SESSION['user_email'] = $users[0]['email'];
} else {
// login failed
}
...

How to get the post of the user using javascript sdk

I am creating my first facebook app using javascript sdk. In that i can able to post to the user's wall using(FB.api('me/feed', 'post', )).
Now what I need is, when the user accessing my app, it has to show (or list) the post of that user. The code is
FB.api('/me/posts', function(response) {
for (var i=0, l=response.length; i<l; i++) {
var post = response[i];
alert('The value of post is:'+post);
if (post.message) {
alert('Message: ' + post.message);
} else if (post.attachment && post.attachment.name) {
alert('Attachment: ' + post.attachment.name);
}
}
});
But it is not working. If I remove l=response.length and change the condition as i<5 it is going inside the loop but it gives the value of post is undefined.
I didn't get why it is returning as undefined. It returns same for post.message also.
I am getting the access_token of the user also.
If I want to get the post of my user what code i have to use. Can anyone help me in this.
Thanks in advance
You can use the Facebook Graph API Explorer to better understand what data you will be receiving. https://developers.facebook.com/tools/explorer/
You should have l=response.data.length and var post = response.data[i];. Also, some posts will not have a "message", but will have a "story" instead (mainly posts like "Joe Smith and Tom Someone are now friends."). Make sure you also have the appropriate permissions (e.g. user_status) for the information you're trying to receive.

How to check if email exists with MYSQLi

I'm 11 and I'm making a chat site for me and my friends. I'm using MYSQLi to handle the database things, and I'm kinda new to it. I always used normal mysql.
Oh! And if you can share a link to a mysqli tutorial, it would be great :)
Well here's my config file
<?PHP
define("HOST", "localhost"); define("USER", "root"); define("PASSWORD", "****"); define("DATABASE", "secure_login");
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
?>
The database is secure_login, then I have a table called members, and then a column named email in that table.
I included this to a file (register.php) where I have to check if the email exists or not. And if it exists, redirect to home.
If you guys can help me it would be cool!!! I hope to finish this soon :)
I'd start with reading the MySQLi documentation at http://php.net/manual/en/book.mysqli.php, in specific the methods related to the class. If you are in need of a tutorial I would suggest to search on Google, there are loads of tutorials on the web.
As for your question, something like this should work:
$query = "SELECT email FROM members WHERE USER = ? AND PASS = ?";
if ($stmt = $mysqli->prepare($query)){
// Bind the parameters, these are the ?'s in the query.
$stmt->bind_param("ss", $username, sha1($password));
// Execute the statement
if($stmt->execute()){
// get the results from the executed query
$stmt->store_result();
$email_res= "";
// This stores the value of the emailaddres inside $email_res
$stmt->bind_result($email_res);
$stmt->fetch();
// There is a result
if ($stmt->num_rows == 1){
// Validate the emailadres here, check the PHP function filter_var()
}
else {
// Not a valid email
}
}
else {
printf("Execute error: %s", $stmt->error);
}
}
else {
printf("Prepared Statement Error: %s\n", $mysqli->error);
}
}
I hope this helps

silverstripe external authentification

there is a custom login form that should give users access to certain contents on the same page. That works so far with Users stored as Members in the SS database and I was checking after Login if the user has permissions like this in the Page Class:
function isAllowed() {
if (Member::currentUser()) {
$PresseGroup = DataObject::get_one('Group', "Code = 'presse'");
$AdminGroup = DataObject::get_one('Group', "Code = 'administrators'");
if (Member::currentUser()->inGroup($PresseGroup->ID) || Member::currentUser()->inGroup($AdminGroup->ID)) {
return true;
}
}
}
in the Template I just did this:
<% if isAllowed %>
SecretContent
<% end_if %>
OK so far, but now the users will not be stored in the silverstripe database - they are stored on a another server.
On that external server is running a little php script accepting the username and password. The script just returns user has permission: true or false.
I´m calling that script via cURL.
I planned to overwrite the dologin Function of MemberLoginForm. Now I just wonder how to check after Login that the User got the permission and display the contents... I tried to set a variable in the controller of the Page or should I set a session Variable? Thats my attempt (CustomLoginForm extends MemberLoginForm):
public function dologin($data) {
if(userHasPermission("user1", "pw")==true){
$this->controller->Test("test");
}
$link = $this->controller->Link();
$this->performLogin($data);
$this->controller->redirect($link);
}
I hope someone can help me with that - I know very specific - problem.
Many thanx,
Florian
In SilverStripe you can create a custom authenticator, which means users can log in on your website with accounts that are stored somewhere else, or even just a hard coded user and password.
You can check out the OpenID Authentication Module for example code on how to do it
But for your task this might even be to complex of a solution, how about after login just do something like Session::set('isAllowed', true); and to check if the user is allowed to view:
function isAllowed() {
if (Member::currentUser()) {
$PresseGroup = DataObject::get_one('Group', "Code = 'presse'");
$AdminGroup = DataObject::get_one('Group', "Code = 'administrators'");
if (Member::currentUser()->inGroup($PresseGroup->ID) || Member::currentUser()->inGroup($AdminGroup->ID)) {
return true;
}
}
// if Member::currentUser() is not allowed to view,
// return the session, which is either set to true or it returns null if not set
return Session::get('isAllowed');
}

Facebook Invite User, retrieving the data field

Hi when my application lets a user invite their friends, I would like to append a tracking tag in the data field so that when someone receives that invite, I will be able to retrieve that tracking tag.
My problem is that once I pass the tracking tag, I don't know how to retrieve it when a user clicks on an application request.
My code for the invitation is
FB.ui(
{
method: 'apprequests',
message: 'You should learn more about this awesome game.',
data: UniqTrackIDInvite //a randomly generated number
},
and on my landing page, where a new user decides to accept my app or not after clicking on the, I would like to have a way to retrieve this
getting the request ids:
if(isset($_REQUEST['request_ids']))
$reqIds = explode(',', $_REQUEST['request_ids']);
you may store them in the session to use them later
this is the api call:
public function getInvitationData($reqId){
return $facebook->api('/'.$reqId, 'GET', array('access_token'=>$accessToken));
}
as the user may be invited by more than one user, he can hav several invites, so make a loop. also use a try/catch block, as a request id, which is already deleted, will throw an exception
foreach($reqIds as $reqId) {
try{
$invite = $application->facebook->getInvitationData($reqId);
$data = explode('.', $invite['data']);
if(sizeof($data) >= 3) list($in, $from, $code)=$data;
// tadaaa
echo $code;
}
}