1. Go to this page and download the library: Download parse/php-sdk library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
// 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');
// set curl http client (default if none set)
ParseClient::setHttpClient(new ParseCurlHttpClient());
// set stream http client
// **
// ** Use an Absolute path for your file! **
// holds one or more certificates to verify the peer with
ParseClient::setCAFile(__DIR__ . '/certs/cacert.pem');
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;
$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);
// 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();
// 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);
$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();
});
// 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
//
// 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');
// 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');
// 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 = 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();
// 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");
$data = array("alert" => "Hi!");
// Parse Server has a few ue 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);
$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();
// 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();
}
// get the current version of the server you are connected to (2.6.5, 2.5.4, etc.)
$version = ParseServerInfo::getVersion();
// 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();
ParseServerInfo::getHooksFeatures();
ParseServerInfo::getCloudCodeFeatures();
ParseServerInfo::getLogsFeatures();
ParseServerInfo::getPushFeatures();
ParseServerInfo::getSchemasFeatures();
// additional features can be obtained manually using 'get'
$feature = ParseServerInfo::get('new-feature');
// 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();
$mySchema->deleteField('string_field');
$mySchema->save():
// or for an existing schema...
$mySchema->update():
$mySchema->delete();
// 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'];
// delete all objects in the schema
$mySchema->purge();
// 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