Giter VIP home page Giter VIP logo

parse-php-sdk's Introduction

parse-repository-header-sdk-php


Build Status CI release Snyk Badge Coverage auto-release

PHP Version

packagist latest version

Backers on Open Collective Sponsors on Open Collective Forum Twitter


A library that gives you access to the powerful Parse Server backend from your PHP app. For more information on Parse and its features, see the website, the PHP guide, the Cloud Code guide or API Reference.


Table of Contents

Compatibility

The Parse PHP SDK is continuously tested with the most recent releases of PHP to ensure compatibility. We follow the PHP Long Term Support plan and only test against versions that are officially supported and have not reached their end-of-life date.

Version End-of-Life Compatible
PHP 8.2 Dec 2024 โœ… Yes
PHP 8.1 Nov 2023 โœ… Yes

Installation

There are various ways to install and use this sdk. We'll elaborate on a couple here. Note that the Parse PHP SDK requires PHP 5.4 or newer. It can also run on HHVM (recommended 3.0 or newer).

Install with Composer

Get Composer, the PHP package manager. Then create a composer.json file in your projects root folder, containing:

{
    "require": {
        "parse/php-sdk" : "1.5.*"
    }
}

Run "composer install" to download the SDK and set up the autoloader, and then require it from your PHP script:

require 'vendor/autoload.php';

Install with Git

You can clone down this sdk using your favorite github client, or via the terminal.

git clone https://github.com/parse-community/parse-php-sdk.git

You can then include the autoload.php file in your code to automatically load the Parse SDK classes.

require 'autoload.php';

Install with another method

If you downloaded this sdk using any other means you can treat it like you used the git method above. Once it's installed you need only require the autoload.php to have access to the sdk.

Setup

Once you have access to the sdk you'll need to set it up in order to begin working with parse-server.

Initializing

After including the required files from the SDK, you need to initialize the ParseClient using your Parse API keys:

ParseClient::initialize( $app_id, $rest_key, $master_key );

If your server does not use or require a REST key you may initialize the ParseClient as follows, safely omitting the REST key:

ParseClient::initialize( $app_id, null, $master_key );

Server URL

Directly after initializing the sdk you should set the server url.

// Users of Parse Server will need to point ParseClient at their remote URL and Mount Point:
ParseClient::setServerURL('https://my-parse-server.com:port','parse');

Notice Parse server's default port is 1337 and the second parameter parse is the route prefix of your parse server.

For example if your parse server's url is http://example.com:1337/parse then you can set the server url using the following snippet

ParseClient::setServerURL('https://example.com:1337','parse');

Server Health Check

To verify that the server url and mount path you've provided are correct you can run a health check on your server.

$health = ParseClient::getServerHealth();
if($health['status'] === 200) {
    // everything looks good!
}

If you wanted to analyze it further the health response may look something like this.

{
    "status"    : 200,
    "response"  : {
        "status" : "ok"
    }
}

The 'status' being the http response code, and the 'response' containing what the server replies with. Any additional details in the reply can be found under 'response', and you can use them to check and determine the availability of parse-server before you make requests.

Note that it is not guaranteed that 'response' will be a parsable json array. If the response cannot be decoded it will be returned as a string instead.

A couple examples of bad health responses could include an incorrect mount path, port or domain.

// ParseClient::setServerURL('http://localhost:1337', 'not-good');
{
    "status": 404,
    "response": "<!DOCTYPE html>...Cannot GET \/not-good\/health..."
}

// ParseClient::setServerURL('http://__uh__oh__.com', 'parse');
{
    "status": 0,
    "error": 6,
    "error_message": "Couldn't resolve host '__uh__oh__.com'"
}

Keep in mind error & error_message may change depending on whether you are using the curl (may change across versions of curl) or stream client.

Http Clients

This SDK has the ability to change the underlying http client at your convenience. The default is to use the curl http client if none is set, there is also a stream http client that can be used as well.

Setting the http client can be done as follows:

// set curl http client (default if none set)
ParseClient::setHttpClient(new ParseCurlHttpClient());

// set stream http client
// ** requires 'allow_url_fopen' to be enabled in php.ini **
ParseClient::setHttpClient(new ParseStreamHttpClient());

If you have a need for an additional http client you can request one by opening an issue or by submitting a PR.

If you wish to build one yourself make sure your http client implements ParseHttpable for it be compatible with the SDK. Once you have a working http client that enhances the SDK feel free to submit it in a PR so we can look into adding it in.

Alternate CA File

It is possible that your local setup may not be able to verify with peers over SSL/TLS. This may especially be the case if you do not have control over your local installation, such as for shared hosting.

If this is the case you may need to specify a Certificate Authority bundle. You can download such a bundle from http://curl.haxx.se/ca/cacert.pem to use for this purpose. This one happens to be a Mozilla CA certificate store, you don't necessarily have to use this one but it's recommended.

Once you have your bundle you can set it as follows:

// ** Use an Absolute path for your file! **
// holds one or more certificates to verify the peer with
ParseClient::setCAFile(__DIR__ . '/certs/cacert.pem');

Getting Started

We highly recommend you read through the guide first. This will walk you through the basics of working with this sdk, as well as provide insight into how to best develop your project.

If want to know more about what makes the php sdk tick you can read our API Reference and flip through the code on github.

Check out the Parse PHP Guide for the full documentation.

Use Declarations

Add the "use" declarations where you'll be using the classes. For all of the sample code in this file:

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;
use Parse\ParseClient;
use Parse\ParsePushStatus;
use Parse\ParseServerInfo;
use Parse\ParseLogs;
use Parse\ParseAudience;

Parse Objects

Parse Objects hold your data, can be saved, queried for, serialized and more! Objects are at the core of this sdk, they allow you to persist your data from php without having to worry about any databasing code.

$object = ParseObject::create("TestObject");
$objectId = $object->getObjectId();
$php = $object->get("elephant");

// Set values:
$object->set("elephant", "php");
$object->set("today", new DateTime());
$object->setArray("mylist", [1, 2, 3]);
$object->setAssociativeArray(
    "languageTypes", array("php" => "awesome", "ruby" => "wtf")
);

// Save normally:
$object->save();

// Or pass true to use the master key to override ACLs when saving:
$object->save(true);

// encode an object for later use
$encoded = $object->encode();

// decode an object
$decodedObject = ParseObject::decode($encoded);

Users

Users are a special kind of object. This class allows individuals to access your applications with their unique information and allows you to identify them distinctly. Users may also be linked with 3rd party accounts such as facebook, twitter, etc.

// Signup
$user = new ParseUser();
$user->setUsername("foo");
$user->setPassword("Q2w#4!o)df");
try {
    $user->signUp();
} catch (ParseException $ex) {
    // error in $ex->getMessage();
}

// Login
try {
    $user = ParseUser::logIn("foo", "Q2w#4!o)df");
} catch(ParseException $ex) {
    // error in $ex->getMessage();
}

// Current user
$user = ParseUser::getCurrentUser();

Session Id and Session Fixation

In an attempt to avoid session fixation exploits, the PHP SDK will call session_regenerate_id() when a session's permissions are elevated (since 1.5.0). In practice this means that session_regenerate_id() will be called when a session goes from no user to anonymous user or from no user / anonymous user to registered user.

Changing the PHP session id should have no impact on the contents of the session and state should be maintained for a user that was anonymous and becomes registered.

Verification Emails

If you are using email verification in your parse server setup you can request to send verification emails by hand.

ParseUser::requestVerificationEmail('[email protected]');

Note that this will only send if the account for the email requested has not already been verified.

ACLs

Access Control Lists (ACLs) allow you to granularly control access to individual Parse Objects. ACLs allow you to configure access to the general public, roles, and individual users themselves.

// Access only by the ParseUser in $user
$userACL = ParseACL::createACLWithUser($user);

// Access only by master key
$restrictedACL = new ParseACL();

// Set individual access rights
$acl = new ParseACL();
$acl->setPublicReadAccess(true);
$acl->setPublicWriteAccess(false);
$acl->setUserWriteAccess($user, true);
$acl->setRoleWriteAccessWithName("PHPFans", true);

Queries

Queries allow you to recall objects that you've saved to parse-server. Query methods and parameters allow allow a varying degree of querying for objects, from all objects of a class to objects created within a particular date range and more.

$query = new ParseQuery("TestObject");

// Get a specific object:
$object = $query->get("anObjectId");

$query->limit(10); // default 100, max 1000

// All results, normally:
$results = $query->find();

// Or pass true to use the master key to override ACLs when querying:
$results = $query->find(true);

// Just the first result:
$first = $query->first();

// Process ALL (without limit) results with "each".
// Will throw if sort, skip, or limit is used.
$query->each(function($obj) {
    echo $obj->getObjectId();
});

Aggregate

Queries can be made using aggregates, allowing you to retrieve objects over a set of input values. Keep in mind that _id does not exist in parse-server. Please replace with objectId. MasterKey is Required

For a list of available operators please refer to Mongo Aggregate Documentation.

Mongo 3.2 Aggregate Operators

// group pipeline is similar to distinct, can apply $sum, $avg, $max, $min
// accumulate sum and store in total field
$pipeline = [
    'group' => [
        'objectId' => null,
        'total' => [ '$sum' => '$score']
    ]
];
$results = $query->aggregate($pipeline);

// project pipeline is similar to keys, add or remove existing fields
// includes name key
$pipeline = [
    'project' => [
        'name' => 1
    ]
];
$results = $query->aggregate($pipeline);

// match pipeline is similar to equalTo
// filter out objects with score greater than 15
 $pipeline = [
    'match' => [
        'score' => [ '$gt' => 15 ]
    ]
];
$results = $query->aggregate($pipeline);

Distinct

Queries can be made using distinct, allowing you find unique values for a specified field. Keep in mind that MasterKey is required.

// finds score that are unique
$results = $query->distinct('score');

// can be used with equalTo
$query = new ParseQuery('TestObject');
$query->equalTo('name', 'foo');
$results = $query->distinct('score');

Relative Time

Queries can be made using relative time, allowing you to retrieve objects over a varying ranges of relative dates. Keep in mind that all relative queries are performed using the server's time and timezone.

// greater than 2 weeks ago
$query->greaterThanRelativeTime('createdAt', '2 weeks ago');

// less than 1 day in the future
$query->lessThanRelativeTime('updatedAt', 'in 1 day');

// can make queries to very specific points in time
$query->greaterThanOrEqualToRelativeTime('createdAt', '1 year 2 weeks 30 days 2 hours 5 minutes 10 seconds ago');

// can make queries based on right now
// gets everything updated up to this point in time
$query->lessThanOrEqualToRelativeTime('updatedAt', 'now');

// shorthand keywords work as well
$query->greaterThanRelativeTime('date', '1 yr 2 wks 30 d 2 hrs 5 mins 10 secs ago');

Cloud Functions

Directly call server-side cloud functions and get their results.

$results = ParseCloud::run("aCloudFunction", array("from" => "php"));

Cloud Jobs

Like cloud functions, cloud jobs allow you to run code server-side but in an asynchronous fashion. Instead of waiting for execution to complete you are immediately returned an id for tracking the job's progress. You can use this id to see the current information on a job and whether it has completed.

// start job
$jobStatusId = ParseCloud::startJob('MyCloudJob', array("startedBy" => "me!"));

// get job status, a ParseObject!
$jobStatus = ParseCloud::getJobStatus($jobStatusId);
$status = $jobStatus->get('status'); // failed / succeeded when done

Config

ParseConfig allows you to access the global Config object for your parse server setup. You can get, set and update simple values much like you would on an instance of ParseObject. Through this all your SDKs and applications can have access to global settings, options, and more. What you choose to put in your config is purely up to you however.

$config = new ParseConfig();

// check a config value of yours
$allowed = $config->get('feature_allowed');

// add a simple config value
$config->set('feature_allowed', true);

// save this global config
$config->save();

Analytics

A specialized Parse Object built purposely to make analytics easy.

ParseAnalytics::track("logoReaction", array(
    "saw" => "elephant",
    "said" => "cute"
));

Files

Persist files to parse-server and retrieve them at your convenience. Depending on how your server is setup there are a variety of storage options including mongodb, Amazon S3 and Google Cloud Storage. You can read more about that here.

// Get from a Parse Object:
$file = $aParseObject->get("aFileColumn");
$name = $file->getName();
$url = $file->getURL();
// Download the contents:
$contents = $file->getData();

// Upload from a local file:
$file = ParseFile::createFromFile(
    "/tmp/foo.bar", "Parse.txt", "text/plain"
);

// Upload from variable contents (string, binary)
$file = ParseFile::createFromData($contents, "Parse.txt", "text/plain");

Push

Push notifications can be constructed and sent using this sdk. You can send pushes to predefined channels of devices, or send to a customized set of devices using the power of ParseQuery.

In order to use Push you must first configure a working push configuration in your parse server instance.

Push to Channels

You can send push notifications to any channels that you've created for your users.

$data = array("alert" => "Hi!");

// Parse Server has a few requirements:
// - The master key is required for sending pushes, pass true as the second parameter
// - You must set your recipients by using 'channels' or 'where', but you must not pass both


// Push to Channels
ParsePush::send(array(
    "channels" => ["PHPFans"],
    "data" => $data
), true);

Push with Query

You can also push to devices using queries targeting the ParseInstallation class.

// Push to Query
$query = ParseInstallation::query();
$query->equalTo("design", "rad");

ParsePush::send(array(
    "where" => $query,
    "data" => $data
), true);

Push with Audience

If you want to keep track of your sends when using queries you can use the ParseAudience class. You can create and configure your Audience objects with a name and query. When you indicate it's being used in a push the lastUsed and timesUsed values are updated for you.

$iosQuery = ParseInstallation::getQuery();
$iosQuery->equalTo("deviceType", "ios");

// create & save your audience
$audience = ParseAudience::createAudience(
    'MyiOSAudience',
    $iosQuery
);
$audience->save(true);

// send a push using the query in this audience and it's id
// The 'audience_id' is what allows parse to update 'lastUsed' and 'timesUsed'
// You could use any audience_id with any query and it will still update that audience
ParsePush::send([
    'data'          => [
        'alert' => 'hello ios users!'
    ],
    'where'         => $audience->getQuery(),
    'audience_id'   => $audience->getObjectId()
], true);

// fetch changes to this audience
$audience->fetch(true);

// get last & times used for tracking
$timesUsed = $audience->getTimesUsed();
$lastUsed = $audience->getLastUsed();

Audiences provide you with a convenient way to group your queries and keep track of how often and when you send to them.

Push Status

If your server supports it you can extract and check the current status of your pushes. This allows you to monitor the success of your pushes in real time.

// Get Push Status
$response = ParsePush::send(array(
    "channels" => ["StatusFans"],
    "data" => $data
), true);

if(ParsePush::hasStatus($response)) {

    // Retrieve PushStatus object
    $pushStatus = ParsePush::getStatus($response);

    // check push status
    if($pushStatus->isPending()) {
        // handle a pending push request

    } else if($pushStatus->isRunning()) {
        // handle a running push request

    } else if($pushStatus->hasSucceeded()) {
        // handle a successful push request

    } else if($pushStatus->hasFailed()) {
        // handle a failed request

    }

    // ...or get the push status string to check yourself
    $status = $pushStatus->getPushStatus();

    // get # pushes sent
    $sent = $pushStatus->getPushesSent();

    // get # pushes failed
    $failed = $pushStatus->getPushesFailed();

}

Server Info

Any server version 2.1.4 or later supports access to detailed information about itself and it's capabilities. You can leverage ParseServerInfo to check on the features and version of your server.

Version

Get the current version of the server you are connected to.

// get the current version of the server you are connected to (2.6.5, 2.5.4, etc.)
$version = ParseServerInfo::getVersion();

Features

Check which features your server has and how they are configured.

// get the current version of the server you are connected to (2.6.5, 2.5.4, etc.)
$version = ParseServerInfo::getVersion();

// get various features
$globalConfigFeatures = ParseServerInfo::getGlobalConfigFeatures();
/**
 * Returns json of the related features
 * {
 *    "create" : true,
 *    "read"   : true,
 *    "update" : true,
 *    "delete" : true
 * }
 */

 // you can always get all feature data
 $data = ParseServerInfo::getFeatures();

You can get details on the following features as well:

ParseServerInfo::getHooksFeatures();
ParseServerInfo::getCloudCodeFeatures();
ParseServerInfo::getLogsFeatures();
ParseServerInfo::getPushFeatures();
ParseServerInfo::getSchemasFeatures();

// additional features can be obtained manually using 'get'
$feature = ParseServerInfo::get('new-feature');

Schema

Direct manipulation of the classes that are on your server is possible through ParseSchema. Although fields and classes can be automatically generated (the latter assuming client class creation is enabled) ParseSchema gives you explicit control over these classes and their fields.

// create an instance to manage your class
$mySchema = new ParseSchema("MyClass");

// gets the current schema data as an associative array, for inspection
$data = $mySchema->get();

// add any # of fields, without having to create any objects
$mySchema->addString('string_field');
$mySchema->addNumber('num_field');
$mySchema->addBoolean('bool_field');
$mySchema->addDate('date_field');
$mySchema->addFile('file_field');
$mySchema->addGeoPoint('geopoint_field');
$mySchema->addPolygon('polygon_field');
$mySchema->addArray('array_field');
$mySchema->addObject('obj_field');
$mySchema->addPointer('pointer_field');

// you can even setup pointer/relation fields this way
$mySchema->addPointer('pointer_field', 'TargetClass');
$mySchema->addRelation('relation_field', 'TargetClass');

// new types can be added as they are available
$mySchema->addField('new_field', 'ANewDataType');

// save/update this schema to persist your field changes
$mySchema->save();
// or
$mySchema->update();

Assuming you want to remove a field you can simply call deleteField and save/update to clear it out.

$mySchema->deleteField('string_field');
$mySchema->save():
// or for an existing schema...
$mySchema->update():

A schema can be removed via delete, but it must be empty first.

$mySchema->delete();

Index

Indexes support efficient execution of queries from the database. MasterKey is required.

// To add an index, the field must exist before you create an index
$schema->addString('field');
$index = [ 'field' => 1 ];
$schema->addIndex('index_name', $index);
$schema->save();

// Delete an index
$schema->deleteIndex('index_name');
$schema->save();

// If indexes exist, you can retrieve them
$result = $schema->get();
$indexes = $result['indexes'];

Purge

All objects can be purged from a schema (class) via purge. But be careful! This can be considered an irreversible action. Only do this if you really need to delete all objects from a class, such as when you need to delete the class (as in the code example above).

// delete all objects in the schema
$mySchema->purge();

Logs

ParseLogs allows info and error logs to be retrieved from the server as JSON. Using the same approach as that which is utilized in the dashboard you can view your logs with specific ranges in time, type and order. Note that this requires the correct masterKey to be set during your initialization for access.

// get last 100 info logs, sorted in descending order
$logs = ParseLogs::getInfoLogs();

// get last 100 info logs, sorted in descending order
$logs = ParseLogs::getErrorLogs();

// logs can be retrieved with further specificity
// get 10 logs from a date up to a date in ascending order
$logs = ParseLogs::getInfoLogs(10, $fromDate, $untilDate, 'asc');

// above can be done for 'getErrorLogs' as well

Contributing / Testing

See CONTRIBUTING for information on testing and contributing to the Parse PHP SDK.


As of April 5, 2017, Parse, LLC has transferred this code to the parse-community organization, and will no longer be contributing to or distributing this code.

parse-php-sdk's People

Contributors

acinader avatar awgeorge avatar dplewis avatar egreenmachine avatar fcrosfly avatar gfosco avatar grahamcampbell avatar inmanpaul avatar isaacaskew avatar juliangut avatar lacker avatar lucianocn avatar mistahgandhi avatar montymxb avatar mtrezza avatar niraj-shah avatar noughts avatar osniel avatar phelipealves avatar pinguineras avatar sahanh avatar schuylr avatar semantic-release-bot avatar somus avatar stafox avatar thebabayaga avatar tomwfox avatar vespakoen avatar vferdiansyah avatar zeliard91 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

parse-php-sdk's Issues

User sessions between browser quit and open

Sorry for the title, but I wasn't able to explain better this problem. I have set up Parse PHP SDK on a web app, with the login working and logout too. The problem is that if I log in, then I close the browser and I open the web app, I'm not logged in.

I'm pretty sure that it's something very easy to implement, but I don't have much experience on PHP. I would love if you help me!

Thanks!

Using ParseRole seems to throw exception error

I tried to add a new Role using the ParseRole class but i keep getting an error

Uncaught exception 'Exception' with message 'You must specify a Parse class name or register the appropriate subclass when creating a new Object. Use ParseObject::create to create a subclass object.' in /Applications/MAMP/htdocs/parse/vendor/parse/php-sdk/src/Parse/ParseObject.php:88 Stack trace: #0 /Applications/MAMP/htdocs/parse/index.php(22): Parse\ParseObject->__construct('Moderator', Array) #1 {main} thrown in /Applications/MAMP/htdocs/parse/vendor/parse/php-sdk/src/Parse/ParseObject.php on line 88

This is odd as i am following the PHP guide examples. Heres how i tried to create a new role and retrieve a role:

$role = new ParseRole("Moderator", $someACLObject);
$role->save(); 

That throws an error. To add, I had to make do like this:

$role = ParseRole::createRole('Moderator', $someACLObject);

And to retrieve a role (this is the ONLY method that works for me):

$query = new ParseQuery("_Role");
$query->equalTo('name', 'Moderator');
$role = $query->first();

If i try anything else I get the error above. Is this the intended methods or is it a bug?

Is the php SDK slower?

So, I was testing the PHP and JS SDK on a website, and it appears the php sdk takes 4-5 seconds more than the JS SDK. Any reason?

Here's my code:-

<?php
require 'vendor/autoload.php';

use Parse\ParseClient;
 //removed my api keys

use Parse\ParseObject;
use Parse\ParseQuery;


$query=new ParseQuery("something");
try {
  $gameScore = $query->get("EYzG1jJs1g");
  // The object was retrieved successfully.
} catch (ParseException $ex) {
  // The object was not retrieved successfully.
  // error is a ParseException with an error code and message.
}
echo("\n");
echo($gameScore->get("name"));

$query=new ParseQuery("something");
try {
    $results=$query->find();
    echo "Successfully retrieved " . count($results) . " scores.";

    echo($results[3]->get("name"));

  // The object was retrieved successfully.
} catch (ParseException $ex) {
  // The object was not retrieved successfully.
  // error is a ParseException with an error code and message.
}
?>

And here's the JS code:-

<script>

var TestObject = Parse.Object.extend("TestObject");
var testObject = new TestObject();
testObject.save({foo: "bar"}).then(function(object) {
  alert("yay! it worked");
});

var GameScore = Parse.Object.extend("something");
var query = new Parse.Query(GameScore);
query.get("vRNYbTWwuW", {
  success: function(gameScore) {

    alert(gameScore.get("name"));   
    // The object was retrieved successfully.
  },
  error: function(object, error) {
    // The object was not retrieved successfully.
    // error is a Parse.Error with an error code and message.
  }
});
</script>

Travis

Will Travis CI be enabled for this repo?

PHP files missing end quote

There are some files missing the ending for PHP files (this is: "?>")
I found this when including the autoload.php file as well as in any other file. Do I am missing any point or this is a bug in this version?
Thanks a lot!

Include Issue

Hi Forum,

I have coded in PHP in the past but, not for a few years now. I have included the 'autoload.php' file and confirmed that it is including the Parse/ParseClient.php file by just putting in a line to display on the screen in ParseClient.php.

My error is:

Fatal error: Class 'ParseClient' not found in /Users/kevint/Documents/local-web-host/index.php on line 11

Here is my code sans my real ID's:

Keys $app_id = "blah"; $rest_key = "blah"; $master_key = "blah"; ParseClient::initialize( $app_id, $rest_key, $master_key ); echo "parse initialization

"; $query = new ParseQuery("Birthday"); try { $timsBirthday = $query->get("BLAH"); // The object was retrieved successfully echo "tim's birthday " . $timsBirthday; } catch (ParseException $error) { // The object was not retrieved successfully. // error is a ParseException with an error code and message. echo $error->getCode(); echo $error->getMessage(); } ?>

I am running PHP 5.4.30 on a Mac Mini using http://localhost:8888 as my local web server. This is pretty basic and I have followed the instructions, I think. Any help would be appreciated.

K

Undefined relation method

The relation method is not defined for the ParseObject as it should be as stated in the PHP Developer Guide with this excerpt:

$user = ParseUser::getCurrentUser();
$relation = $user->relation("likes");
$relation->add($post);
$user->save();

fetch method does not offer master key support.

Hi,
In my system admin need to change the status field of user in _User table.I tried to use below code but it is not updating and getting some warning.Here current user is admin and trying to update other user info filed.

public function updateAdminComent($status = true,$comment,$objectID){

$object = new \Parse\ParseObject("_User", $objectID);
$object->fetch();
    $object->set('status',$status);
$object->set("comment",strip_tags($comment));
try {
        $object->save(true);
        return true;
} catch (ParseException $ex) {

return false;
}

}

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\src\Parse\ParseObject.php on line 532

Problem in create new user.

ERROR: You must specify a Parse class name or register the appropriate subclass when creating a new Object. Use ParseObject::create to create a subclass object.

using PHP

$user = new ParseUser();
$user->set("username", "test");
$user->set("email", "[email protected]");
$user->set("password", "Cf%09ude");

    try {
        $user->signUp();
        $result = true;
    } catch (ParseException $ex) {
        echo "Error: " . $ex->getCode() . " " . $ex->getMessage();
    }

I do not know what else to do.

http://postimg.org/image/e8e08c2m1/

Correct way to pass values to Cloud function

I have tried various approaches but cannot seem to get this right.

When I pass data to the Cloud function I have trouble retrieving them in Cloud Code.

Example:

ParseCloud::run('addAlarm', ['subject' => $subject]);

Will pass the following request to the function in Cloud Code:

{"body":"{"subject":"Re: Alarm"}","params":{"subject":"Re: Alarm"},"installationId":"","user":null,"master":false}

I can read request.body to get:

{"subject":"Re: Alarm"}

But reading request.body.subject yields undefined

I was unable to find any examples where arguments is passed to the Cloud function in PHP, so am currently running on trial and error.

ParseCloud::run() not using session key

Suggest changing to:

public static function run($name, $data = array(), $useMasterKey = false)
{
$sessionToken = null;
if (ParseUser::getCurrentUser()) {
  $sessionToken = ParseUser::getCurrentUser()->getSessionToken();
}
$response = ParseClient::_request(
  'POST',
  '/1/functions/' . $name,
  $sessionToken,
  json_encode(ParseClient::_encode($data, null, false)),
  $useMasterKey
);
return ParseClient::_decode($response['result']);

}

how can i update parse user table with object id which is not a current user object id

How can i update the user table with object id which is not a current user object id. I used following code but not able to update the result.

public function updateAdminComent($status,$comment,$objectID){

$object = new \Parse\ParseObject("_User", $objectID);
$object->set('verifyStatus',$status);
$object->set("comment",strip_tags($comment));
try {
$object->save();
return true;
} catch (ParseException $ex) {
return false;
}
}
Unfortunately it is not updating

Problem with object->add

Test code to reproduce the problem: http://pastebin.com/jXyfBjDa

From the documentation.
https://parse.com/docs/php_guide#objects-updating

I am building a photo-album test app for the php-sdk to be used as example.

When doing something like this

$object->add("pictures", "xx") I get an exception " Parse\ParseException: AddOperation requires an array. in vendor/parse/php-sdk/src/Parse/Internal/AddOperation.php on line 32"

I tried also with $object->add("pictures", array("xx")) but that just creates an array with a single element (same as doing set)

Is this a bug or am I doing something wrong.

An excerpt from the code..

function addPicture($album_id, $path){
    $query = new ParseQuery("Albums");
    $album = $query->get($album_id);
    $file = $this->addFile($path);

    $album->add("pictures", $file);  // <-----------------   Here is where I get the exception..
    $album->save();

    print "<pre>" . print_r($album, true) . "</pre>";
}

public function addFile($path){
    // Get the filename and slugify it (remove all characters that may cause problems)
    $pathinfo = pathinfo($path);
    $slugger = new Slugify();
    $filename = $slugger->slugify($pathinfo['filename']) . '.' . strtolower($pathinfo['extension']);
    $file = ParseFile::createFromFile($path, $filename);
    $file->save();

    return $file;
}

The only thing I can think of is to do a
$pictures = $album->get("pictures");
$pictures[] = $file;
$album->setArray("pictures", $pictures);

Can't delete or destroy

Hi Forum,

Me again. Working with the API documentation and things were going well until I tried to delete a field or destroy an object. I can create, retrieve and update fine. However, when I try to destroy() the object, I get the following error:

Fatal error: Uncaught exception 'Parse\ParseException' with message 'object not found for delete' in /Users/kevint/Documents/local-web-host/src/Parse/ParseClient.php:258 Stack trace: #0 /Users/kevint/Documents/local-web-host/src/Parse/ParseObject.php(643): Parse\ParseClient::_request('DELETE', '/1/classes/Birt...', NULL, NULL, false) #1 /Users/kevint/Documents/local-web-host/index.php(30): Parse\ParseObject->destroy() #2 {main} thrown in /Users/kevint/Documents/local-web-host/src/Parse/ParseClient.php on line 258

Here is my code. I can see it echo out the value of $timsBirthday fine but, get the error right after this.

$query = new ParseQuery("Birthday");
// just get a specific record
try {
$timsBirthday = $query->get('mmSHXt6GpO');
//The object was retrieved successfully
echo "

tim's birthday " . $timsBirthday->get("name") . "

";
// $timsBirthday->delete('name');
// $timsBirthday->save();
$timsBirthday->destroy();
} catch (ParseException $error) {
//The object was not retrieved successfully.
//error is a ParseException with an error code and message.
echo $error->getCode();
echo $error->getMessage();
}

For the delete()/save() methods, I get this error:

Fatal error: Uncaught exception 'Parse\ParseException' with message 'object not found for update' in /Users/kevint/Documents/local-web-host/src/Parse/ParseClient.php:258 Stack trace: #0 /Users/kevint/Documents/local-web-host/src/Parse/ParseObject.php(919): Parse\ParseClient::_request('PUT', '/1/classes/Birt...', NULL, '{"name":{"__op"...', false) #1 /Users/kevint/Documents/local-web-host/src/Parse/ParseObject.php(830): Parse\ParseObject::deepSave(Object(Parse\ParseObject), false) #2 /Users/kevint/Documents/local-web-host/index.php(29): Parse\ParseObject->save() #3 {main} thrown in /Users/kevint/Documents/local-web-host/src/Parse/ParseClient.php on line 258

How to use ParseObject update field?

How to use Extend to update the field?

Example SQL: UPDATE Empresa SET categorias = 'cat_01' WHERE id_user = 'dlkj83d'

    $query = new ParseQuery('Empresa');
    $query->equalTo("users", Session::get('user'));
    $query->add("categorias", 'cat_01');   <- ERROR
    $query->save();

Test

    $query = new ParseQuery('Empresa');
    $query->equalTo("users", Session::get('user'));

    $empresa = new ParseObject($query);
    $empresa->add('categorias', array('cat_01'));
    $empresa->save();

Does not work.

:(

Major Limitations

We can only have one instance of the client because it's all static. This is a major blocker for me.

Extending ParseUser

Is this possible? I have tried for ParseObjects and that worked fine, for ParseUser no.

Problem with $_SESSION and authentification

Hi,

I'm trying to use the PHP SDK to make a basic php app but i have a problem with the authentification. Indeed, once a user is log in via the logIn() function I redirect to another page where I try to retrieve the current user by the ParseUser::getCurrentUser() method. However I get an error that appears and I can not solve :

Fatal error: Cannot use object of type __PHP_Incomplete_Class as array in /Users/quentin/Dropbox/Projets/sites/filmoapp/vendor/parse/php-sdk/src/Parse/ParseUser.php on line 217

I tried to remove the session_start () but if I take it off I do not have any user who is registered in the local session (which is normal).

Any ideas to solve this problem?

Thanks :-)

Error during sending push via query-method

Hi, my team using parse-php-sdk in symfony2 project. Trying to send some pushes via query-method. But all the way got the error. We take a not so deep look into library, and find that bug quickly.

parse-php-sdk / src / Parse / ParsePush.php:42

...

      if ($data['where'] instanceof ParseQuery) {
        $data['where'] = $data['where']->_getOptions();
      } else {
...

In this place we got extra nested array of where and where parameters. So on the server side its return the regular error.

We fixed it with this hack:

$data = $data['where']->_getOptions();

But will waiting for the native update.

SessionStorage

Not sure if this is entirely a bug , but there's no mention in the documentation for the PHP SDK that session_start() needs to be called before using persistent storage.

Thanks,

Alan R

Send push from a server with php 5.3

I want to know if someone has achieved to implement this in a server with 5.3, because when i was testing the proyect, the started guide doesn't say anything about this requirement, and i want to implement this for my work, unfortunately the server that is hosted at my work can not upgrade to this version for now, so far the changes I did did not give errors, but the query that is sent to parse api is not the same as my local test, reviewing the dashboard push notifications I found that the correct query was received in this way.

Targeting :
deviceToken is "c2f034eb6e01d996779152f686c9a9ae98966d8a8b885ce95597a899cbc894ba"
deviceType is any of "ios", "android", "winphone" or "js"
Sending date :
August 27th, 2014 at 12:11 PM
Expiration :
None
Full target :
{ "deviceToken": "c2f034eb6e01d933434349a9ae98966d8a8b885ce95597a899cbc894ba", "deviceType": { "$in": [ "ios", "android", "winphone", "js" ] } }
Full data :
{ "alert": "Hi!" }

And the failure push sended was this way.

Targeting :
where advanced operator (deviceToken "c2f034eb6e01d996779152f686c9a9ae98966d8a8b885ce95597a899cbc894ba")
deviceType is any of "ios", "android", "winphone" or "js"
Sending date :
August 27th, 2014 at 1:47 PM
Expiration :
None
Full target :
{ "where": { "deviceToken": "c2f034eb6e01d933434349a9ae98966d8a8b885ce95597a899cbc894ba" }, "deviceType": { "$in": [ "ios", "android", "winphone", "js" ] } }
Full data :
{ "alert": "Hi!" }

The lines in ParseQuery.php that i modify was a few with [ ] and i change to array(), like this.
['$box' => [$southwest, $northeast]]); to array('$box' => array($southwest, $northeast)));

Facebook Sign up Login

Good morning!

I am trying to sign up and login my users through facebook, I alreday included the auth method for users using Facebook PHP SDK, once the user logs in facebook returns a code but I don't know how to link that with a PFUser from Parse. As it has nothing to do with the authData field used in Android or iOS.

Has anyone tried this?

Thanks in advance.

Insert Data Table

Hi, i downloaded the sdk from here few days ago. There is an issue with inserting data into database server. Here is my code ๐Ÿ‘

$object = new ParseObject("table");
$object->set("notes","test");

// Save:
$object->save();

during execution of this code it's showing below error :

"
Fatal error: Cannot use object of type __PHP_Incomplete_Class as array in C:\wamp\www\race-day-engineer-web\application\models\parseSDK\src\Parse\ParseUser.php on line 217
"

Thanks

Add fetchAll: for batch fetching an array of objects

This would bring the PHP SDK in line with the other SDKs (iOS and Android are what I'm familiar with). I have an array of several hundred objects and I'd prefer not to have to loop through it and execute an individual fetch on each one.

_encode() for ParseObject

Hello I think the _encode() for ParseObject is not implemented correctly.

_encode() should not json_encode at all (Like the ParseGeoPoint encode method). If nested arrays are encoded (due to recursion) then encoding the top level array will cause a heap of issues when parsing the final JSON using existing JSON parsers.

The encode should really be a toArray() method, where the result can be passed to a json_encode().

Line 790 and 795 should check if $value and $item are either a instanceof ParseObject or ParseGeoPoint. Since ParseGeoPoint is not being checked, then it will never be encoded.

I have made changes to my application as necessary, but would like to hear discussion. Hope this is clear.

ParseClient.php line 259

Hi Gfosco, hope everything is ok, I need some guidance, I have an app that is sending/scheduling like 200 pushes to parse early in the morning at the same time, just in case I added a usleep(100000); to make it wait after each push (so I don't exceed the 30 r/s parse limit) but Im getting an error:

ParseException in ParseClient.php line 259:
the request took too long to process

do you know how can I fix this?

Appreciate any help, regards

Signing up user error

When trying to perform a user sign up, I'm getting the following error:

PHP Fatal error:  Call to private method Parse\ParseObject::_isDirty() from context 'Parse\ParseUser' in /Users/charliehield/Desktop/parse-signup-error/vendor/parse/php-sdk/src/Parse/ParseObject.php on line 968

Here's my sample application

<?php

require 'vendor/autoload.php';

use Parse\ParseUser;
use Parse\ParseClient;

ParseClient::initialize('***', '***', '***');

$user = new ParseUser();
$user->set("username", "superuser");
$user->set("password", "superpass");
$user->set("email", "[email protected]");

try {
    $user->signUp();
    // Hooray! Let them use the app now.
} catch (ParseException $ex) {
    // Show the error message somewhere and let the user try again.
    echo "Error: " . $ex->getCode() . " " . $ex->getMessage();
}

?>

Allow ParseClient to accept pluggable transport layers

It would be nice to allow users to set different transport on a per use-case basis.

Current implementation is final class ParseClient with request method relying on CURL. While curl is widely adopted, it might not be available due to platform restrictions/system setup (e.g. wordpress.com VIP does not allow usage of CURL: http://vip.wordpress.com/documentation/fetching-remote-data/#uncached-remote-requests).

Nice approach to the problem can be found in Facebook's PHP SDK v4:
https://github.com/facebook/facebook-php-sdk-v4/blob/4.0-dev/src/Facebook/FacebookRequest.php

FacebookRequest allows injection of various transports that implement FacebookHttpable interface, allowing developers to add custom transports that fit their needs.

Cheers,
Rinat

push_time

Hi, thank you for your work on php parse, I hope you can help me with this, Im trying to schedule a push to be send in the future, but when I add the push_time it doesn't work, can you please help me?

Appreciate any help, regards Michael

ParsePush::send(array(
  "channels" => ["xxxxx"],
  "data" => $data,
  "push_time" => "2014-11-01T14:35:00"
));

This is the error: Warning: date_format() expects parameter 1 to be DateTimeInterface, string given

Get all data from an object into an associative array

I'm not sure if I overlooked this, but I could not find any method to retrieve all of an objects data as an associative array rather than a parse object.

Something simple such as:

$object->getAll();

I could see this being useful for many of different reasons. The reason I am trying to get this is to write a Parse database adapter for a custom framework I have. This would be used to get all the objects currently set properties and values for use within the models class.

I currently added this to ParseObject.php as a temporary fix for the time being:

public function getAll()
{
  return $this->estimatedData;
}

Not sure what problems I will run into doing it this way. I'm hoping for solution to this in a later release.

Add connection timeout

Something like

    // Timeouts in seconds
    curl_setopt($rest, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($rest, CURLOPT_TIMEOUT, 10);

It will also need a specific error/exception

[ParseRole] Fatal error: Call to undefined method Parse\ParseACL::setWriteAccessWithName()

HI guys,
I'm getting the error:

Fatal error: Call to undefined method Parse\ParseACL::setWriteAccessWithName() in /<dir>/vendor/parse/php-sdk/src/Parse/ParseACL.php on line 496

here's the call:

$role = ParseRole::query()->equalTo('name', "Administrateur")->first();
if (empty($role))
    die();
$message = new ParseObject("Message");
$roleACL = new ParseACL();
$roleACL->setRoleWriteAccess($role, true);
$message->setACL($roleACL);
$message->save();

here is the role:
Image

The function setWriteAccessWithName is only used in this function and defined nowhere.

Oh ! And by the way: Thanks, awesome job.

edit:
Need to changes ParseACL.php:496:
$this->setWriteAccessWithName($role->getName(), $allowed);
to
$this->setRoleWriteAccessWithName($role->getName(), $allowed);

Trouble storing pointers in associative array

When storing ParseObjects in an associative array, the objects are not converted to pointers and empty objects are inserted instead. I currently have to manually convert the ParseObjects into pointers.

Expected to work:
$gameScore1 = new ParseObject('GameScore');
$gameScore1->set('score', 1337);
$gameScore1->save();

$gameScore2 = new ParseObject('GameScore');
$gameScore2->set('score', 13371337);
$gameScore2->save();

$scores = [
  'team1' => $gameScore1,
  'team2' => $gameScore2
];

$scoreBoard = new ParseObject('ScoreBoard');
$scoreBoard->setAssociativeArray('scores', $scores);
$scoreBoard->save();
Temporary solution:
$gameScore1 = new ParseObject('GameScore');
$gameScore1->set('score', 1337);
$gameScore1->save();

$gameScore2 = new ParseObject('GameScore');
$gameScore2->set('score', 13371337);
$gameScore2->save();

$scores = [
  'team1' => $gameScore1->_toPointer(),
  'team2' => $gameScore2->_toPointer()
];

$scoreBoard = new ParseObject('ScoreBoard');
$scoreBoard->setAssociativeArray('scores', $scores);
$scoreBoard->save();

Parse PHP & Laravel

Hi!

I am trying to add PHP SDK to my laravel application, parse_autoload.php is the autoload.php that Parse provides.

This is my code:

   require 'parse_autoload.php';

   use Parse\ParseObject;
   use Parse\ParseClient;


  Route::get('/', function()
  {

  ParseClient::initialize(****, ****,*****);

  });

But my app fails when calling ParseClient::initialize...

Any ideas?

how i can add or in multiple condition

$sql = 'select location,airportName, IATA,ICAO from tbl_name where IATA like "'. mysql_real_escape_string($_REQUEST['term']) .'%" '
. 'or airportName like "'. mysql_real_escape_string($_REQUEST['term']) .'%" '
. 'or location like "'. mysql_real_escape_string($_REQUEST['term']) .'%" order by IATA asc limit 0,100';

How i can make a query like this in Parse SDK

Problems sending a push notification to an specific installation -> userid

HI, i'm having some problems sending push notifications to an specific installation -> userid, when i check the Parse log i get the error "Done (with error)".
Here's the code that i'm using:

$data = array("alert" => "Test parse PHP SDK");
// Push to Query
$query = ParseInstallation::query();
$query->equalTo("userid", 9);
ParsePush::send(array(
  "where" => $query,
  "data" => $data
));

I think the problem is with te SDK, because when i check the log, the full query is:

{ "where": { "userid": 9 }, "deviceType": { "$in": [ "ios", "android", "winphone", "js" ] } }

and i think normally should be without the "where":

{ "userid": 9 , "deviceType": { "$in": [ "ios", "android", "winphone", "js" ] } }

About the user signup

screenshot from 2014-08-12 23 18 40

I use PHP5.5, and don't why it will appear this error when using $user->signup(), but it work after change the private function to protected

Cannot retrieve getCreatedAt()

Hi!

I am retrieving my object properly and accessing all the fields except from the dates.

I tried calling $obj->getCreatedAt() but it returned null.

Is it working for anyone? Any ideas?

Thanks in advance

not able to save pointer in user table

public function userSignUP($data)
{
$user = new \Parse\ParseUser();
$generalInfo = new \Parse\ParseObject("General_Info");
$user->set("responderInfo",$generalInfo);
$backgroundInfo = new \Parse\ParseObject("Background_Info");
$user->set("backgroundInfo",$backgroundInfo);
$experienceDetails = new \Parse\ParseObject("Experience_Details");
$user->set("experienceDetails",$experienceDetails);
try {
$user->signUp();
return true;
} catch (ParseException $ex) {
return false;
}
}

Fatal error: Uncaught exception 'Parse\ParseAggregateException' with message 'Errors during batch save.' in C:\xampp\htdocs\src\Parse\ParseObject.php:953 Stack trace: #0 C:\xampp\htdocs\src\Parse\ParseObject.php(834): Parse\ParseObject::deepSave(Object(Parse\ParseUser), false) #1 C:\xampp\htdocs\src\Parse\ParseUser.php(112): Parse\ParseObject->save() #2 C:\xampp\htdocs\class\classRegister.php(25): Parse\ParseUser->signUp() #3 C:\xampp\htdocs\register.php(26): murRegister\signUpProcess->userSignUP(Array) #4 {main} thrown in C:\xampp\htdocs\src\Parse\ParseObject.php on line 953

please help me for solving this issue

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.