Use parse.com in php - php

I am trying to use Parse in a php script.
I have done to following:
Uploaded the files 'autoload.php' and the folder 'Parse' from here to the root directory of the server
https://github.com/parseplatform/parse-php-sdk
Then I created an index.php with the following test code from here: https://www.webniraj.com/2014/08/05/parse-com-using-the-official-parse-php-sdk-v1-0-x/
// define location of Parse PHP SDK, e.g. location in "Parse" folder
// Defaults to ./Parse/ folder. Add trailing slash
define( 'PARSE_SDK_DIR', './Parse/' );
// include Parse SDK autoloader
require_once( 'autoload.php' );
// Add the "use" declarations where you'll be using the classes
use Parse\ParseClient;
use Parse\ParseObject;
use Parse\ParseQuery;
use Parse\ParseACL;
use Parse\ParsePush;
use Parse\ParseUser;
use Parse\ParseInstallation;
use Parse\ParseException;
use Parse\ParseAnalytics;
use Parse\ParseFile;
use Parse\ParseCloud;
// Init parse: app_id, rest_key, master_key
ParseClient::initialize('xxx', 'xxx', 'xxx');
// save something to class TestObject
$testObject = ParseObject::create("TestObject");
$testObject->set("foo", "bar");
$testObject->save();
// get the object ID
echo $testObject->getObjectId();
echo '<h1>Users</h1>';
// get the first 10 users from built-in User class
$query = new ParseQuery("_User");
$query->limit(10);
$results = $query->find();
foreach ( $results as $result ) {
// echo user Usernames
echo $result->get('username') . '<br/>';
}
Of course I replaced the xxx with my app_id, rest_key and master_key
When I now open index.php I am getting
Fatal error: Call to undefined function Parse\curl_init() in /Parse/ParseClient.php on line 304
Did I miss to do something?

I don't have enough reputation points to simply comment, but wanted to suggest you confirm that you have the curl PHP extension installed on your server.
phpinfo();
or
if (extension_loaded("curl"))
{
echo "cURL extension is loaded<br>";
}
else
{
echo "cURL extension is not available<br>";
}

Related

Google Adwords API integration (V201708/V201710) with Code Igniter 2.x

For Google adwords API I've used this library and It's working fine alone. But I am unable to integrate this library with CI 2.x.
Some code snippet is :
if (!defined('BASEPATH')) exit('No direct script access allowed');
define('SRC_PATH', APPPATH.'/third_party/Adwords/src/');
define('COMMON_PATH', 'Google/AdsApi/Common/');
define('ADWORDS_PATH', 'Google/AdsApi/AdWords/');
define('ADWORDS_VERSION', 'v201710');
// Configure include path
ini_set('include_path', implode(array(
ini_get('include_path'), PATH_SEPARATOR, SRC_PATH))
);
// Include the AdWordsUser file
require_once SRC_PATH.ADWORDS_PATH. '/AdWordsSessionBuilder.php';
require_once SRC_PATH.ADWORDS_PATH. '/Reporting/v201710/DownloadFormat.php';
require_once SRC_PATH.ADWORDS_PATH. '/Reporting/v201710/ReportDefinition.php';
require_once SRC_PATH.ADWORDS_PATH. '/Reporting/v201710/ReportDefinitionDateRangeType.php';
require_once SRC_PATH.ADWORDS_PATH. '/Reporting/v201710/ReportDownloader.php';
require_once SRC_PATH.ADWORDS_PATH. '/ReportSettingsBuilder.php';
require_once SRC_PATH.ADWORDS_PATH. '/v201710/cm/Predicate.php';
require_once SRC_PATH.ADWORDS_PATH. '/v201710/cm/PredicateOperator.php';
require_once SRC_PATH.ADWORDS_PATH. '/v201710/cm/ReportDefinitionReportType.php';
require_once SRC_PATH.ADWORDS_PATH. '/v201710/cm/Selector.php';
require_once SRC_PATH.COMMON_PATH. '/OAuth2TokenBuilder.php';
class My_adwords {
}
Getting following fatal error:
Fatal error: Interface 'Google\AdsApi\Common\AdsBuilder' not found in /var/www/html/crm2017/application/third_party/Adwords/src/Google/AdsApi/AdWords/AdWordsSessionBuilder.php on line 38
Please suggest some optimum solution.
<?php
//namespace Google\AdsApi\Examples\AdWords\v201710\Reporting;
if (!defined('BASEPATH')) exit('No direct script access allowed');
require __DIR__ . '/../third_party/Googleadwords/googleads-php-lib/vendor/autoload.php';
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\Reporting\v201710\ReportDownloader;
use Google\AdsApi\AdWords\Reporting\v201710\DownloadFormat;
use Google\AdsApi\AdWords\ReportSettingsBuilder;
use Google\AdsApi\Common\OAuth2TokenBuilder;
use Google\AdsApi\AdWords\v201710\cm\ReportDefinitionReportType;
use Google\AdsApi\AdWords\v201710\cm\ReportDefinitionService;
use Google\AdsApi\AdWords\v201710\cm\CampaignCriterionService;
use Google\AdsApi\AdWords\v201710\cm\Predicate;
use Google\AdsApi\AdWords\v201710\cm\PredicateOperator;
use Google\AdsApi\AdWords\v201710\cm\Paging;
use Google\AdsApi\AdWords\v201710\cm\Selector;
use Google\AdsApi\AdWords\v201710\cm\BiddingStrategyConfiguration;
use Google\AdsApi\AdWords\v201710\cm\BiddingStrategyType;
class My_adwords {
public function __construct() {
//$oAuth2Credential = new OAuth2TokenBuilder();
}
function GetCampaignsCost() {
// Get the service, which loads the required classes.
$oAuth2Credential = (new OAuth2TokenBuilder())
->fromFile()
->build();
// See: AdWordsSessionBuilder for setting a client customer ID that is
// different from that specified in your adsapi_php.ini file.
// Construct an API session configured from a properties file and the OAuth2
// credentials above.
$session = (new AdWordsSessionBuilder())
->fromFile()
->withOAuth2Credential($oAuth2Credential)
->build();
$reportFormat = DownloadFormat::CSV;
$reportQuery = 'SELECT Cost,CampaignId,BiddingStrategyType,CampaignName FROM CAMPAIGN_PERFORMANCE_REPORT DURING YESTERDAY';
// Download report as a string.
$reportDownloader = new ReportDownloader($session);
$reportSettingsOverride = (new ReportSettingsBuilder())
->includeZeroImpressions(false)
->build();
$reportDownloadResult = $reportDownloader->downloadReportWithAwql(
$reportQuery, $reportFormat, $reportSettingsOverride);
$data = $reportDownloadResult->getAsString();
}
}
I've used use instead of require_once. Just include library once and use class which needs. I've done following steps:
Composer runs outside of CodeIgnitor and all dependencies adjusted
via composer and put same folder inside application/third_party.
Make a class inside application/library which interact with
third_party. Above snippet belongs to library class.
Load library in controller and call function of library.
Hence Solved.

Elephant.io integration php

Using only a simple file I can get elephant.io to work, but If I'm trying to integrate it inside an class, it won't work.
The reason why it won't work is that it says I can't use use elephant ... inside a class or function.
How would I integrate elephant.io in an already existing class ?
To be more specific , I'm trying to integrate elephant.io into codeigniter framework.
function tester() {
use ElephantIO\Client,
ElephantIO\Engine\SocketIO\Version1X;
require __DIR__ . '/vendor/autoload.php';
$client = new Client(new Version1X('http://www.textbasedmafiagame.com:8080'));
$client->initialize();
$client->emit('broadcast2', ['foo' => 'utførte et biltyveri']);
$client->close();
}
and get no response or outcome, but i do get:
use not allowed inside a function
and
Parse error: syntax error, unexpected 'use'
As the error states, the use keyword must be declared in the outermost scope of a file (the global scope) or inside namespace declarations.
Try something along these lines
<?php
use ElephantIO\Client, ElephantIO\Engine\SocketIO\Version1X;
require __DIR__ . '/vendor/autoload.php';
class foo{
public function tester() {
$client = new Client(new Version1X('http://www.textbasedmafiagame.com:8080'));
$client->initialize();
$client->emit('broadcast2', ['foo' => 'utførte et biltyveri']);
$ client->close();
}
}

How to use Parse in Wordpress Template?

I want to create a backend in Wordpress for my Parse app which displays information from the app using the Parse PHP SDK.
The SDK is included and I am using the autoloader.php to load it but I keep getting the following error:
Fatal error: Class 'Parse\ParseClient' not found in http://site
I have ensured that my file path is correct.
Any suggestions.
Thanks!
define( 'PARSE_SDK_DIR', bloginfo( 'template_url' ) . '/parse/' );
// include Parse SDK autoloader
require_once('autoload.php' );
// Add the "use" declarations where you'll be using the classes
use Parse\ParseClient;
use Parse\ParseObject;
use Parse\ParseQuery;
use Parse\ParseACL;
use Parse\ParsePush;
use Parse\ParseUser;
use Parse\ParseInstallation;
use Parse\ParseException;
use Parse\ParseAnalytics;
use Parse\ParseFile;
use Parse\ParseCloud;
ParseClient::initialize('wOI4ED7sqFMI9TN9bBbwVc9WGEePcUuq15V04liY', 'lfcUvPmvT6ayZFZflLWf7rZBgbZKICuS3ppwYIxo', 'NBHXiPtiz6ECMPjnKH33P2WZwxNAMdLJEpooPCe4');
And then for the autoload.php:
<?php
/**
* You only need this file if you are not using composer.
* Adapted from the Facebook PHP SDK 4.0.x autoloader
*/
if (version_compare(PHP_VERSION, '5.4.0', '<')) {
throw new Exception('The Parse SDK requires PHP version 5.4 or higher.');
}
/**
* Register the autoloader for the Parse SDK
* Based off the official PSR-4 autoloader example found here:
* https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader-examples.md
*
* #param string $class The fully-qualified class name.
* #return void
*/
spl_autoload_register(function ($class)
{
// Parse class prefix
$prefix = 'Parse\\';
// base directory for the namespace prefix
$base_dir = defined('PARSE_SDK_DIR') ? PARSE_SDK_DIR : bloginfo( 'template_url' ) . '/parse/';
// does the class use the namespace prefix?
$len = strlen( $prefix );
if ( strncmp($prefix, $class, $len) !== 0 ) {
// no, move to the next registered autoloader
return;
}
// get the relative class name
$relative_class = substr( $class, $len );
// replace the namespace prefix with the base directory, replace namespace
// separators with directory separators in the relative class name, append
// with .php
$file = $base_dir . str_replace( '\\', '/', $relative_class ) . '.php';
echo $file;
// echo $relative_class . '<br/>';
// if the file exists, require it
if ( file_exists( $file ) ) {
require $file;
}
});
Notice that I am echoeing the $file and this points to the correct directory :/
Add the "use" declarations where you'll be using the classes. For all
of the sample code in this file:
https://github.com/ParsePlatform/parse-php-sdk
So adding use Parse\ParseClient; to your PHP file should fix the issue, add the declaration for whatever class form the Parse PHP SDK you intend to use.
if the folder structure is:
autoload.php
yourcurrentfile.php
/src
/src/Parse
you can skip / remove:
define( 'PARSE_SDK_DIR', bloginfo( 'template_url' ) . '/parse/' );
if you want to set another url just use:
define( 'PARSE_SDK_DIR', __DIR__.'/src/Parse/' );
and change to the correct URL.

How to add parse.com library in codeigniter

I am new in codeigniter . i can easily work with parse.com library on core php like this
<?php
// define location of Parse PHP SDK, e.g. location in "Parse" folder
// Defaults to ./Parse/ folder. Add trailing slash
define( 'PARSE_SDK_DIR', '../src/Parse/' );
// include Parse SDK autoloader
require_once( 'autoload.php' );
// Add the "use" declarations where you'll be using the classes
use Parse\ParseClient;
use Parse\ParseObject;
use Parse\ParseQuery;
use Parse\ParseACL;
use Parse\ParsePush;
use Parse\ParseUser;
use Parse\ParseInstallation;
use Parse\ParseException;
use Parse\ParseAnalytics;
use Parse\ParseFile;
use Parse\ParseCloud;
// Init parse: app_id, rest_key, master_key
ParseClient::initialize('id', 'id2', 'id3');
// save something to class TestObject
$testObject = ParseObject::create("TestObject");
$testObject->set("foo", "bar");
$testObject->save();
// get the object ID
echo $testObject->getObjectId();
echo '<h1>Users</h1>';
// get the first 10 users from built-in User class
$query = new ParseQuery("_User");
$query->limit(10);
$results = $query->find();
foreach ( $results as $result ) {
// echo user Usernames
echo $result->get('username') . '<br/>';
}
but i am unable to use this in codeigniter . please help me how i can add parse.com in codeigniter and use this.
please provide me some direction and example
download CI library from here
parse.com paste all code inside your application/libraries folder. make sure you have created custom config parse.php file sample
<?php
/**
* Parse keys
*/
$config['parse_appid'] = '';
$config['parse_masterkey'] = '';
$config['parse_restkey'] = '';
$config['parse_parseurl'] = 'https://api.parse.com/1/';
?>
and in your sample controller ParseSample.php try this.
<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
class ParseSample extends CI_Controller {
public function index()
{
$temp = $this->load->library('parse');
$testObj = $this->parse->ParseObject('testObj');
$testObj->data = array("testcol" => "it works");
$return = $testObj->save($testObj->data);
echo "<pre>";
print_r($return);
echo "<pre>";
var_dump($return);
exit;
}
}
Hope someone might feel helpful.

how to include php file contains 'use' command in another file with class

I have two files.
in the first file (Facebook.php) i take user data via Facebook (Facebook access token):
<?php
require_once '../include/Config.php';
require_once ( '../libs/facebook/autoload.php' );
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\FacebookRequestException;
function getUserData($token){
// init app with app id and secret
FacebookSession::setDefaultApplication( FB_APP_ID,FB_APP_SECRET ); //
// If you already have a valid access token:
$session = new FacebookSession($token); // 'access-token'
// To validate the session:
try {
$session->validate();
} catch (FacebookRequestException $ex) {
// Session not valid, Graph API returned an exception with the reason.
echo $ex->getMessage();
} catch (\Exception $ex) {
// Graph API returned info, but it may mismatch the current app or have expired.
echo $ex->getMessage();
}
if($session) {
try {
$user_profile = (new FacebookRequest( $session, 'GET', '/me'))->execute()->getGraphObject()->asArray(); //(GraphUser::className());
// print profile data
echo '<pre>' . print_r( $user_profile, 1 ) . '</pre>';
return $user_profile;
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
}
}
?>
and this is the second file for manage user data:
<?php
require_once '../../../include/Facebook.php';
class userManager {
function __construct() {
}
/**
* Get user data from facebook
* #param user key
* #return user data if exist else false
*/
public function facebookSignIn($token){
$fbUserData = getUserData($token);
print_r($fbUserData);
}
}
?>
in the second file i want to manage user data with a class but i think that my script don't run because the code lines in Facebook.php
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\FacebookRequestException;
causing an error in compiling time.
if I comment out these lines my script compiles but naturally doesn't retrieve facebook user data.
what is the right way to include 'facebook.php' in my class?
where am I wrong?
I apologize but I do not understand 'use' command and how I can use it.
If i include Facebook.php in a test file without class:
<?php
require_once '../include/Facebook.php';
$token = $_GET["token"];
getUserData($token);
?>
the script run fine!
i found a solution for my problem. The problem is in the include lines in the first file because test.php is in different hierarchy path of second file.
I found the error using these lines of code:
error_reporting(E_ALL);
ini_set('display_errors', 1);
I apologize, but sometimes the most obvious things that are beyond our control.
thanks to everyone for the support
I ran into this problem myself early on because I was not accustomed to using these commands. Use commands have to be used within the same file that the functions relative to them are called. So if File A contains the SDK initialization and you try the use commands then your API requests should work. If File B is required or included within File A (or vice-versa), you must add the use commands within File B to initiate any Graph functions but they should still work. It seems use commands only work within the file for which they are located and no others.
In your second file, add the use commands that you need and I believe you'll find it will work. In your specific case, you may also need it within your function.

Categories