Parse has released an official PHP SDK, similar to the Facebook PHP SDK 4.0. As usual, it’s not very well documented and you may have to jump between different documentations to find the complete solution. As always, I’ve created a simple tutorial to help you get started with using the new Parse PHP SDK. I’ve also created an autoload script you can use instead of using compose.
Autoloader
If you don’t want to use compose to use the SDK, I’ve created an autoloader you can use to include all the files form the PHP SDK easily. Simply use the below code and add it to the autoload.php
file.
Getting Started
You can then include the autoload file in your code and initialise it as shown in the code below. You can then save data to Parse, or retrieve results as shown in the code too.
Documentation
The complete documentation for the official Parse PHP SDK is located in two places: the Parse PHP SDK GitHub repository and the Parse Documentation website.
Need specific help? Leave us a comment below and I’ll create the most requested tutorials.
Hi Niraj Shah, Im getting the following error when trying to initialize : “Fatal error: Class ‘ParseParseClient’ not found in C:xampphtdocsstevenindex.php on line 33” Im sure the keys I’m using are the correct ones, please advise I’m kind of stuck.
The error is related to PHP not being able to find the ParseClient class, not your settings. Make sure you define the location of the Parse PHP files. By default, the autoloader will look for the files in the ‘./Parse/’ directory.
Where exactly does the directory need to be changed? In autoload.php, during the initialization or both?
I keep getting:
Class ‘ParseParseClient’ not found …
*I’m doing the initialization from functions.php. Parse SDK is in themes folder.
Thanks!
If the Parse directory is not directly in the theme folder, set
define( 'PARSE_SDK_DIR', 'path/to/Parse/' );
to tell theautoload.php
file where to find it. By default, it’s set to look in the./Parse
folder (containing all the other PHP files).The parse folder (with the “internal” folder and all the ParseClient.php, etc) is in my main theme folder (same folder as my other php files ie: index.php, front-page.php, header.php, footer.php, functions.php, etc)
RESULT:
Class ‘ParseParseClient’ not found in …
Thanks!
Ahh, I see the issue. WordPress needs the full path to the file, since everything goes through the
index.php
page. Try changing the define to:define( 'PARSE_SDK_DIR', 'wp-content/themes/your-theme/Parse/' );
. Remember to add in the name of your theme.That worked! With the exception, now wp-admin gets this same error. Any thoughts?
Thank you for your help!!!
Ahh. It appears the problem was including the initialization in the functions.php file. Do you recommend creating a plugin for parse initialization?
If you are using Parse for just your website, I would put the autoload include and initialisation in the
wp-config.php
file – that way, it should work from all area. If the admin side still fails, I would use a if statement to check the location and then init the SDK:Are there any other files I need to download or install other than these codes?
You just need the Parse SDK and the code on this page to get started.
it works, thank you very much for your help!!
Hey there!
Could someone tell me how to set up user location via php?
Thnx
You mean trying to get the user’s location using geolocation?
Hi there,
I’m stuck in configuring the Parse PHP SDK, any help appreciated.
Parse error: syntax error, unexpected T_FUNCTION, expecting ‘)’ in /public_html/zzzz/parse/autoload.php on line 20
———————————————
SDK directory structure
/public_html/zzzz/parse/src/Parse/
/public_html/zzzz/parse/autoload.php
———————————————-
/public_html/zzzz/myscript.php
Can you help me where I’m going wrong
Thanks!
The error is not with the files or setup of the SDK, its with your code. You are missing a
)
somewhere in your code on Line 20. Please check the syntax and add in the missing)
.Hi Niraj I’m having problems with the login I’ve search the web but there isnt that much information about PHP with Parse. When I put the correct data it displays “correct username” but when I put the wrong data it displays the same thing and I also get this error
Warning: file_get_contents(https://api.parse.com/1/login?username=example%40gmail.com&password=efesfes): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in C:xampphtdocsstevenParseParseClient.php on line 240
Warning: Invalid argument supplied for foreach() in C:xampphtdocsstevenParseParseObject.php on line 488
Warning: Invalid argument supplied for foreach() in C:xampphtdocsstevenParseParseObject.php on line 528
this is the code, I’ve tried the login in different ways but still get the same error, please help.
try
{
$user = ParseUser::logIn(“$myusername”, “$mypassword”);
$currentUser = ParseUser::getCurrentUser();
// Do stuff after successful login.
if($currentUser != NULL)
{
//Header(“Location:userprofile.php”);
echo “correct username”;
}
else if($currentUser == NULL)
{
echo “wrong username or password”;
}
}
catch(ParseException $error)
{
$status =($error->getMessage());
echo $status;
// The login failed. Check error to see why.
}
The correct way to log a user in would be to do the following instead:
If the
ParseUser:logIn()
call fails, it throws an exception, so it would always hit the Catch statement. Also, note that you need the username and password to login, not the email address. It could explain why you’re getting the 404 error in your code.Now I get the following and I’m using username instead of email now.
correct username
ParseParseUser Object ( [_sessionToken:protected] => s1WOIzSH8WQzFCzW0qQbAkRdr [serverData:protected] => Array ( [email] => email@example.com [username] => steven ) [operationSet:protected] => Array ( ) [estimatedData:ParseParseObject:private] => Array ( [email] => email@example.com [username] => steven ) [dataAvailability:ParseParseObject:private] => Array ( [email] => 1 [sessionToken] => 1 [username] => 1 ) [className:ParseParseObject:private] => _User [objectId:ParseParseObject:private] => BXvWdU2XDy [createdAt:ParseParseObject:private] => DateTime Object ( [date] => 2014-10-27 22:26:43.238000 [timezone_type] => 2 [timezone] => Z ) [updatedAt:ParseParseObject:private] => DateTime Object ( [date] => 2014-11-13 10:37:57.887000 [timezone_type] => 2 [timezone] => Z ) [hasBeenFetched:ParseParseObject:private] => 1 )
That means it’s working. The debug data you see is the result of the getCurrentUser() function in the code. I can see your username and registration data in there.
I can see it works when I put the correct info, but when I enter the incorrect user and/or password it still displays “correct username” and displays the same warnings I gave you in the begining. this probably may be more than just a simple code error.
I’ve tested with both correct and incorrect information. For me, when using incorrect information the code jumps to the catch part of the code and displays “wrong username or password”.
Fatal error: Uncaught exception ‘Parse\ParseException’ with message ‘SSL certificate problem: unable to get local issuer certificate’
I am getting this error when trying to execute any query or even log-in. Please suggest a solution.
What you need to do is add the line:
curl_setopt($rest, CURLOPT_SSL_VERIFYPEER, false);
to the_request
function inParseClient.php
, just above$response = curl_exec($rest);
. This will stop the code from checking if you have a valid SSL certificate.Hi Niraj,
I’m trying to retrieve the ‘bio’ from the class Profile using a specific email, is the query below correct?
$query = new ParseQuery(“Profile”);
$query->equalTo(“Email”, “$email”);
$object = $query->find();
$object->get(“bio”);
echo $object;
Try changing the last to lines to:
Hi niraj please help me i am new in parse.com use. i don’t know how to use this DB in php.
i request to you to if possible please give me on basic example that include fetching & updating record from parse.com DB.
If you take a look at the code, it already give you an example of how to Insert something into parse, and retrieve information (in this case Users) from the database. For everything else, you can use the official PHP documentation on the Parse website.
Array ( [0] => Parse\ParseObject Object ( [serverData:protected] => Array ( [foo] => bar ) [operationSet:protected] => Array ( ) [estimatedData:Parse\ParseObject:private] => Array ( [foo] => bar ) [dataAvailability:Parse\ParseObject:private] => Array ( [foo] => 1 ) [className:Parse\ParseObject:private] => TestObject [objectId:Parse\ParseObject:private] => ycUEhzGXNI [createdAt:Parse\ParseObject:private] => DateTime Object ( [date] => 2014-11-26 13:30:51.422000 [timezone_type] => 2 [timezone] => Z ) [updatedAt:Parse\ParseObject:private] => DateTime Object ( [date] => 2014-11-26 13:30:51.422000 [timezone_type] => 2 [timezone] => Z ) [hasBeenFetched:Parse\ParseObject:private] => 1 ) [1] => Parse\ParseObject Object ( [serverData:protected] => Array ( [ACL] => Parse\ParseACL Object ( [permissionsById:Parse\ParseACL:private] => Array ( [*] => Array ( [read] => 1 [write] => 1 ) ) [shared:Parse\ParseACL:private] => ) [foo] => bar ) [operationSet:protected] => Array ( ) [estimatedData:Parse\ParseObject:private] => Array ( [ACL] => Parse\ParseACL Object ( [permissionsById:Parse\ParseACL:private] => Array ( [*] => Array ( [read] => 1 [write] => 1 ) ) [shared:Parse\ParseACL:private] => ) [foo] => bar ) [dataAvailability:Parse\ParseObject:private] => Array ( [foo] => 1 ) [className:Parse\ParseObject:private] => TestObject [objectId:Parse\ParseObject:private] => gcS5HgR9Wr [createdAt:Parse\ParseObject:private] => DateTime Object ( [date] => 2014-11-25 19:44:16.854000 [timezone_type] => 2 [timezone] => Z ) [updatedAt:Parse\ParseObject:private] => DateTime Object ( [date] => 2014-11-26 19:22:17.197000 [timezone_type] => 2 [timezone] => Z ) [hasBeenFetched:Parse\ParseObject:private] => 1 ) )
Above is the response I am getting. I want to convert above data to php array. How to do it?
Please help
What is the reason for converting it to an array? You can use objects in similar ways to an array. It’s extra work to convert the object to an array.
Hi Niraj,
the code below uploads a music file and some info, everything uploads but the music file uploads incorrectly(it provides a URL but does not play the music) is the code correct?
$songname = $_POST[‘songname’];
$songgenre = $_POST[‘songgenre’];
$songdesc = $_POST[‘songdesc’];
$musicfile = $_FILES[‘mymusic’];
$file = ParseFile::createFromData($musicfile, “newmusic.mp3”);
$file->save();
$url = $file->getURL();
$songinfo = new ParseObject(“Songs”);
$songinfo->set(“songFile”, $file);
$songinfo->set(“songName”,$songname);
$songinfo->set(“genre”, $songgenre);
$songinfo->set(“description”, $songdesc);
$songinfo->save();
The code looks correct to me, but is the extension of the file correct? It could be that the file won’t play in the browser, so have you tried to download it and play it on your computer?
the file extension is correct, but when I upload the song manually in parse.com everything works fine and it plays on the browser.
Ah, I see the issue. Change
$file = ParseFile::createFromData($musicfile, “newmusic.mp3″);
to$file = ParseFile::createFromData( file_get_contents( $musicfile['tmp_name'] ), “newmusic.mp3″);
. For reference, see my tutorial.You’re trying to upload the file array, instead of the content of the file itself. That’s why the file is not playing in the browser.
I put the files in my directory, but it doesn’t work.
Somebody help me.
Without telling us what the specific issue is, no one is able to help you. Do you see an error message?
Sorry, but when I run this PHP code, error message said that “This website will not be able to show.” ….
Ah, I could solve that problem.
It was a problem of “ParseClient.php”.
I found the patch for this.
I’m sorry about this question.
I want to integrate Parse with a new WordPress site. I know the Javascript SDK reasonably well so is there any advantage in using php which I am less familiar with? Or is it not possible to use the JS SDK?
The PHP SDK will provide better security and keep your API key a secret so people cannot extract public data using the JavaScript SDK, but the disadvantage is that it will add extra load to your server.
Could you tell me how could i do compound query in parse php sdk.
I want to fire search query on two class, which is linked with a common field.
i have offers class which has bank field (pointer data type).
I have another offers_cards_outlets class which has brandname (string type)
,category (pointer type), offerid (pointer type). *where these fields repeat
offerid of offers_cards_outlets class is object id of offers class.
I have inputs like bank object id which is offers class,
and category, brandname which is in offers_cards_outlets class.
So, How do we write code for these two classes.
Have a look at the documentation for Relational Queries on the Parse website. I’m afraid I can’t help you here as I don’t have experience with these types of queries.
Hi Niraj,
I saw your blog and tutorial on Parse PHP SDK. I am currently trying to use parse for the first time in one of my new projects. I see that the parse response is a bit slower in getting data. The reason why I think so is, if you see the below code
// 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’) . ”;
echo $result->get(‘Password’) . ”;
echo $result->get(‘FirstName’) . ”;
}
In this above code you running the query for finding results makes a httprequest and then when we run the foreach loop it again makes a http request for each get command fired.
Do you think my understanding is correct here and if I am correct then do you see a better way of doing this stuff, by simply running a single query and navigating through each objects locally.
I have quiet a bit of data to be fetched and if it has to be done this way i ll run into a lot of performance issues
Let me know your thoughts on the same
Regards
Shakil
The
$result->get()
function in the code isn’t making a second API request. It’s a method to get the properties of the object that was returned in the original API call. In Parse, calling$result->get('username')
is the same as doing$result->username
for a standard PHP object.hi
its not working for me ..
my file directory location: mysite.com/projects/parsetest/parse/ (all sdk files in this folder)
my index file location :mysite.com/projects/parsetest/(index.php file is in here)
autoload file content:
<?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 : __DIR__ . '/parse/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 $relative_class . '’;
// if the file exists, require it
if ( file_exists( $file ) ) {
require $file;
}
});
?>
————————————-
my index php file code:
————————————-
set(“foo”, “bar”);
$testObject->save();
// get the object ID
echo $testObject->getObjectId();
echo ‘Users’;
$query = new ParseQuery(“_User”);
$query->limit(10);
$results = $query->find();
foreach ( $results as $result ) {
// echo user Usernames
echo $result->get(‘username’);
}
?>
when i open the index.php page it showes me the blank page .. what do i do .. where im wrong i dont get that please guide me
im waiting for your reply
You probably have a syntax error in your code. Enable PHP errors to see where the issue could be.
Hello Everyone,
I just start using parse, and with the help of this blog it’s really easy for me setup parse with php sdk in a day.
Cheers guys.
Hey Niraj, I need your help, I am trying to retrieve the date field from parse and showing on text field, but php is giving me an error and saying can’t convert time to string…How to solve it??
Thanks
The date field returned by Parse will be a object. If you field is called
date
, then you can get the date correctly as:echo ParseClient::getProperDateFormat( $result->get('date') );
Hello Niraj
i’m getting the error “Uncaught exception ‘Parse\ParseException’ with message ‘unauthorized’ in ParseClient.php…
It’s occurs when i’m going for example to $testObject->save();
Regards and thanks a lot
Check that you have permission to create a new object in that Class. Make sure
write
permission allowed from the Parse dashboard – check the “Security” button.Hi
Thank you for your post
Can i get installation device count from parse in php?
Yes, if you app is correctly recording device installs, you can get this in PHP by querying the _Installation class. E.g.
Hello Niraj
I am facing an issue while submitting a form.It would be greatfull if you help me
Here when I submit the form it gives a success response but it is not seen in Parse database.All the credentials are given correctly
Thank You
Have you set the correct permissions in Parse? I.e. have you allowed the user / public to create rows in that class? And have the fields been correctly setup? Are you getting any error or result from parse after saving (e.g.
objectId
or error).Hi Niraj
can you please help me with this same issue as on stack overflow. I am facing the same problem in codeigniter? http://stackoverflow.com/questions/32766588/i-cant-start-a-session-in-parse-php-sdk
You need to provide some more details in your question about what error you’re seeing or what exactly is going wrong. Try and be as specific as possible.
Its working.. you save my day.. 🙂 I integrated this in Yii2.
Hi Niraj, i am problem with the Parse Exception. I am trying to make a query.
“Fatal error: Uncaught exception ‘Parse\ParseException’ with message ‘SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed'”
Thanks
please help me, I am working integration parse sdk in my web site. I have issue. issue is failure to parse.com.
Fatal error: Uncaught exception ‘Parse\ParseException’ with message ‘SSL certificate problem: unable to get local issuer certificate’ in C:\APM_Setup\htdocs\parsesdk\src\Parse\ParseClient.php:314 Stack trace: #0 C:\APM_Setup\htdocs\parsesdk\src\Parse\ParseQuery.php(362): Parse\ParseClient::_request(‘GET’, ‘classes/data?li…’, NULL, NULL, false) #1 C:\APM_Setup\htdocs\index.php(50): Parse\ParseQuery->find() #2 {main} thrown in C:\APM_Setup\htdocs\parsesdk\src\Parse\ParseClient.php on line 314
thanks you for your help
This is my favourite page on the internet! thank you so much!
sir i am getting following error
( ! ) Fatal error: Uncaught exception ‘Parse\ParseException’ with message ‘unauthorized’ in C:\wamp\www\myphp\push\vendor\parse\php-sdk\src\Parse\ParseClient.php on line 302
( ! ) Parse\ParseException: unauthorized in C:\wamp\www\myphp\push\vendor\parse\php-sdk\src\Parse\ParseClient.php on line 302
This means that you are accessing a resource you do not have access to. Make sure your API Key / Master Key is correct in your code.