Login with facebook in codeigniter - javascript

I am using this, for login with Facebook, but i am not getting user response here is the link
http://demos.idiotminds.com/link.php?link=https://www.box.com/s/108pspt0o0oj0fpr6ghf
I have tried this solution also for codeigniter
protected function getCode() {
$server_info = array_merge($_GET, $_POST, $_COOKIE);
if (isset($server_info['code'])) {
if ($this->state !== null &&
isset($server_info['state']) &&
$this->state === $server_info['state']) {
// CSRF state has done its job, so clear it
$this->state = null;
$this->clearPersistentData('state');
return $server_info['code'];
} else {
self::errorLog('CSRF state token does not match one provided.');
return false;
}
}
return false;
}
for log in with Facebook but i am not getting value from this $user = $facebook->getUser(); it returns 0 value even if i have logged into Facebook.
I have used so many codes for this but did not success, kindly help me out.
I am very frustrated

Download PHP SDK for Facebook
Now create the a folder in application\libarires "facebook"
Put the "SRC" folder of PHP SDK
Now create a file with FacebookApp.php in that folder and put this code
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once( APPPATH . 'libraries/facebook/src/facebook.php' );
class FacebookApp extends Facebook {
var $ci;
var $facebook;
var $scope;
public function __construct() {
$this->ci =& get_instance();
$this->facebook = new Facebook(array('appId' => $this->ci->config- >item('app_id'),'secret' => $this->ci->config->item('app_secret'), 'cookie' => true));
$this->scope = 'public_profile';
}
public function login_url() {
$params = array('scope' => $this->scope);
return $this->facebook->getLoginUrl($params);
}
public function logout_url() {
return $this->facebook->getLogoutUrl(array('next' => base_url() .'logout'));
}
public function getFbObj(){
return $this->facebook;
}
public function get_user() {
$data = array();
$data['fb_user'] = $this->facebook->getUser();
if ($data['fb_user']) {
try {
$data['fb_user_profile'] = $this->facebook->api('/me');
return $data;
} catch (FacebookApiException $e) {
$this->facebook->destroySession();
$fb_login_url = $this->facebook->getLoginUrl(array('scope' => $this->scope));
redirect($fb_login_url, 'refresh');
}
}
}
Now in controller load this library
$this->load->library('facebook/FacebookApp)
in Method
$obj_fb = new FacebookApp();
$fb_user_data = $obj_fb->get_user();
$data['fb_login_url'] = $obj_fb->login_url();
put the fb_login_url in href of login button and now the login will done.
Hope it help you.

Rahul, I had a similar issue. You can find a pretty good solution here.
If you still cannot figure the solution, why don't you look into the JavaScript SDK. It is pretty straight forward and then use AJAX to act on the response that you get from Facebook.

Related

Parsing JSON data in WordPress

I want to get an Instagram user account info (follower, following and account name).
I used this endpoint:
https://www.instagram.com/{username}/?__a=1
When I add the username in the endpoint, it displays a JSON page that includes a lot of data such as follower, following and account name,
I use this code in WordPress for parsing the JSON code in functions.php and used a shortcode to a page.:
function insta_shortcode_func() {
$request = wp_remote_get('https://www.instagram.com/barkobco/?__a=1');
if (is_wp_error($request)) {
return false; // Bail early
}
$body = wp_remote_retrieve_body($request);
$data = json_decode($body);
return $data -> { 'count'};
}
add_shortcode('count_of_followers', 'insta_shortcode_func');
But nothing is displayed, I want to display follower, following and account name data.
You need to return this to get the followers
return $data->graphql->user->edge_followed_by->count;
Here is the full code
function insta_shortcode_func()
{
$request = wp_remote_get('https://www.instagram.com/barkobco/?__a=1');
if (is_wp_error($request)) {
return false; // Bail early
}
$body = wp_remote_retrieve_body($request);
$data = json_decode($body);
return $data->graphql->user->edge_followed_by->count;
}
add_shortcode('count_of_followers', 'insta_shortcode_func');
I think it will help you

When including session I can not use $_FILES

I am uploading a csv file and sending it to page to process using the js fetch api. I have session included using my init file and all works well accept for the page that should process to file info. Without including the session it works fine and I can process the file, when including it, I can see al the session info, but $_FILES just stops working, I can't see any of the info for some reason.
I really hope this is something stupid
Some code if needed
The init file
<?php
//define Site Root and Includes Path
defined('DS') ? null : define('DS', DIRECTORY_SEPARATOR);
defined('SITE_ROOT') ? null : define('SITE_ROOT', __DIR__ . DS );
defined('INCLUDES_PATH') ? null : define('INCLUDES_PATH', SITE_ROOT);
//get class files
include(INCLUDES_PATH.DS."Session.php");
require_once(INCLUDES_PATH.DS."functions.php");
require_once(INCLUDES_PATH.DS."DB.php");
require_once(INCLUDES_PATH.DS."Validation.php");
require_once(INCLUDES_PATH.DS."User.php");
require_once(INCLUDES_PATH.DS."Swp.php");
require_once(INCLUDES_PATH.DS."Incident.php");
require_once(INCLUDES_PATH.DS."Hira.php");
require_once(INCLUDES_PATH.DS."Mail.php");
The Session.php page
<?php
class Session
{
private $logged_in;
public $user_id;
function __construct()
{
session_start();
$this->check_login();
}
public function is_logged_in() {
return $this->logged_in;
}
private function check_login() {
if (isset($_SESSION['UserID'])) {
$this->user_id = $_SESSION['UserID'];
$this->logged_in = true;
} else {
unset($this->user_id);
$this->logged_in = false;
}
}
}
$session = new Session();
The form page
<?php
//get all the includes
require_once("../php_functions/_init.php");
print_r($_FILES);
//all rows from csv file
$rows = array_map('str_getcsv', file($_FILES['file']['tmp_name'][0]));
//get only the headers
$header = array_shift($rows);
//declare the array
$csv = array();
//create associative array using array_combine
foreach ($rows as $row) {
$csv[] = array_combine($header, $row);
}
print_r($csv);
like I mentioned if I removed the require once from this page it works as expected. Any ideas would help
Just in case you need it here is the js for uploading the file
document.querySelector("#upload_file").addEventListener("click", function () {
const url = 'php/employee/upload_employee_csv_form.php';
const files = document.querySelector('[type=file]').files;
const formData = new FormData();
for (let i = 0; i < files.length; i++) {
let file = files[i];
formData.append('file[]', file);
}
console.log(formData);
fetch(url, {
method: 'POST',
body: formData
}).then(response => {
console.log(response);
});
});
I actually figured it out. So my session was being included before I actually added it, to fix this instead of just saying session_start I check to see if the session is there and then only start if necessary.
The code
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
Bonus tip :-)
The above code will work for php 5.4 and up if you are running something lower than 5.4 you can do the following:
if(session_id() == '') {
session_start();
}
Hope this helps

incorporate asynchronous javascript post requests into php class file

I've inherited a website with an obscure PHP framework called syndrome for which I can't find any documentation, but the problem I'm trying to solve should be fairly simple for a good PHP developer.
I am trying to make ajax requests from javascript to a php file to execute a particular function. The ajax request is simply:
loadNewImage = function(){
$.ajax({ url: '/app/library/Controller/Reel.php',
data: {action: 'test'},
type: 'post',
success: function(output) {
alert(output);
}
});
}
The current PHP file is structured like this:
<?php
class Controller_Reel extends BaseController_Web {
protected function defaultAction() {
parent::getPage($this->template, 'home');
$homepage = Homepage::getInstance()->getHomepage();
$this->template->title = 'Homepage';
$this->template->image = $homepage['asset_image'];
$this->template->center = array('reel');
$this->setResponse($this->template);
}
}
What I want to do is add to the file a check for post data. I'm not good with PHP, but I tried:
<?php
if(isset($_POST['action']) && !empty($_POST['action'])) {
echo 'TEST POST';
}
class Controller_Reel extends BaseController_Web {
protected function defaultAction() {
parent::getPage($this->template, 'home');
$homepage = Homepage::getInstance()->getHomepage();
$this->template->title = 'Homepage';
$this->template->image = $homepage['asset_image'];
$this->template->center = array('reel');
$this->setResponse($this->template);
}
}
I'm assuming that's maybe because the check for post data is not happening within the class itself, but I'm not exactly sure how to structure the code. Can anybody help straighten me out?
UPDATE: I found this inside a file called ControllerSite.php -> (of which baseController_Web is extended:
protected function respond() {
switch($this->response_type) {
case self::RESPONSE_PAGE:
// always try to make ie use the latest rendering engine
case self::RESPONSE_TEXT:
Helper_Request::respond($this->processed_response, Helper_Request::RESPONSE_PRINT, Config::$platform);
break;
case self::RESPONSE_JSON:
Helper_Request::respond($this->processed_response, Helper_Request::RESPONSE_JSON, Config::$platform);
break;
case self::RESPONSE_REDIR:
Helper_Request::respond($this->processed_response, Helper_Request::RESPONSE_REDIR, Config::$platform);
break;
case self::RESPONSE_CONTENT:
// TODO: we'll need to figure the out, but don't need to worry about it for now
break;
}
return $this;
}
and then in Controller.php (of which ControllerSite.php is extended), this:
final private function execute() {
$action = $this->getMethodName();
$is_ajax = Helper_Request::isAjax();
$data_type = strtolower(Helper_Request::setDefault($_SERVER['HTTP_ACCEPT'], ''));
if($is_ajax && preg_match('/\w+\/json|\w+\/javascript/i', $data_type) && method_exists($this, $action . 'JsonAction')) {
// it there was a ajax json request and the ajax json specific method exists, execute it
return $this->{$action . 'JsonAction'}();
}
return $this;
}
Try this:
class Controller_Reel extends BaseController_Web {
protected function defaultAction() {
parent::getPage($this->template, 'home');
$homepage = Homepage::getInstance()->getHomepage();
$this->template->title = 'Homepage';
$this->template->image = $homepage['asset_image'];
$this->template->center = array('reel');
if(isset($_POST['action']) && !empty($_POST['action'])) {
$reponse['success'] = true;
$response['responseVal'] = 'This is a test';
$this->setResponse($response);
} else {
$this->setResponse($this->template);
}
}
}
Try to make a class method named testAction:
protected function testAction() {
parent::getPage($this->template, 'home');
$homepage = Homepage::getInstance()->getHomepage();
$this->template->title = 'Homepage';
$this->template->image = $homepage['asset_image'];
$this->template->center = array('reel');
$this->setResponse($this->template);
}
In ajax request you are trying to send action parameter with test value and i suppose it is the framework's duty to call the related method named with 'test' .
This may hep.

Backlink check script PHP

I got a script to check if a URL is present in a page. Here it is:
class LP_backlinkchecker
{
var $url;
var $content;
var $links;
var $linktocheck;
function __construct($url, $linktocheck)
{
$this->url = $url;
$this->linktocheck = $linktocheck;
}
function SetLinktocheck($link)
{
$this->linktocheck = $link;
}
function getContents()
{
$this->content = file_get_contents($this->url);
}
function lpFetchLinks()
{
$regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>";
preg_match_all("/$regexp/siU", $this->content, $matches);
$this->links = $matches;
return $matches;
}
function check()
{
foreach($this->links[2] as $key => $url)
{
if($url == $this->linktocheck)return TRUE;
}
return FALSE;
}
}
My problem is that the script only works for checking links on the same site. It does not work when the links to check is outside of the website. For example, the script works well to check the link
http://web.com/linktocheck present on the website http://web.com/
If think my $regexp is wrong, do you have some idea of the problem ?
Thanks for your help.
Not sure if I have misunderstood your issue but your code seems to work for me. I wrote you a little unit test that you can now have and expand upon, if you could write a test that does not work I might be able to help more.
class LP_backlinkcheckerTest extends PHPUnit_Framework_TestCase
{
public $l;
public function setUp()
{
$this->l = new LP_backlinkchecker('test.html', null);
}
public function tearDown()
{
}
public function testGetContents()
{
$this->l->getContents();
$this->assertNotEmpty($this->l->content);
}
public function testlpFetchLinks()
{
$this->l->getContents();
$matches = $this->l->lpFetchLinks();
$expected = array(
"http://google.com",
"http://www.bluesnews.com",
"http://www.bluesnews.com/somepage"
);
// 4 things captured by the regex
$this->assertEquals(4, count($matches));
$this->assertEquals($expected, $matches[2]);
}
}
and the HTML file I am using
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
Google.com
BluesNews.com
somepage
</body>
</html>
Although it would be better to make your class so that I don't have to supply it a file but that's the way you designed it. I would also suggest perhaps using parse_url to breakdown the url into it's component parts. Your problem may be just that your expecting one string to be equal to the other and there may be a user input error at construct time which your not checking at all.

Performing CRUD Operations in MongoDB Using PHP Application

I am a rookie PHP and MongoDB developer.
I have created a PHP web project with an HTML page that contains an 'Add' button. The name of the page is awards.html. The awards.html file contains its counterpart JavaScript file, awards.js. A code is executed in this js file when the Add button is clicked. This code sends an AJAX call to a PHP class elsewhere in the project named, example.php which contains code to execute a function called, connect() that is in an Awards.php file.
The source-code of my files is given as follows:
Awards.html
<div class = "divbottom">
<div id="divAddAward">
<button class="btn" onclick="onrequest();">Add</button>
</div>
</div>
awards.js
function onrequest() {
$("#divAddAward").load('example.php');
alert('Test');
$.post(
'example.php'
).success(function(resp) {
json = $.parseJSON(resp);
alert(json);
});
}
example.php
<?php
include 'Awards.php';
$class = new Awards();
$method = $class->connect();
echo json_encode($method);
Awards.php
<?php
require_once 'mongodb-library/libraries/Mongo_db.php';
include 'mongodb-library/libraries/Mongo_db.php';
class Awards extends Mongo_db
{
//put your code here
public function __construct()
{
parent::__construct();
}
public function connect()
{
$this->load();
//The following code is used for confirmation
$array = array(
$this->message => '1'
);
return $array;
}
public function create()
{
//Code to read
}
public function read()
{
//Code to read
}
public function update()
{
//Code to update
}
public function delete()
{
//Code to delete
}
}
The purpose of my project is to perform CRUD operations on my MongoDB database called, test. I am using the Codeigniter-MongoDB-Library to connect to this database. I have edited the mongodb.php library file accordingly to connect to my database. The config settings for this file are given as follows:
mongodb.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config['default']['mongo_hostbase'] = 'localhost:27017';
$config['default']['mongo_database'] = 'test';
$config['default']['mongo_username'] = '';
$config['default']['mongo_password'] = '';
$config['default']['mongo_persist'] = TRUE;
$config['default']['mongo_persist_key'] = 'ci_persist';
$config['default']['mongo_replica_set'] = FALSE;
$config['default']['mongo_query_safety'] = 'safe';
$config['default']['mongo_suppress_connect_error'] = TRUE;
$config['default']['mongo_host_db_flag'] = FALSE;
The problem here is that the connect function is not getting executed; in other words, I am not able to connect to my database successfully. How do I know this? Because on the awards.html page I am getting an output which reads, No direct script access allowed, which is coming from the mongo_db.php file (mind you not the mongodb.php file I have mentioned above).
Can anyone please tell me where exactly am I going wrong? Replies at the earliest will be highly appreciated. Thank you in advance.

Categories

Resources