Parse PHP current user update failed but session updated - php

In Parse PHP SDK If the current user want to change his Email/username normally Parse check if username used by other user and if it is used it will return error, now this is good and work perfectly so far but the issue is the session is automatically updates to the new value where it failed.
so basically the session for the current user updated even if it wasn't for the backend
Steps to reproduce
$currentUser = Parse\ParseUser::getCurrentUser();
echo "Current Username is : ". $currentUser->get("username");
if ($currentUser) {
$currentUser->set("username", "ww");
try {
$currentUser->save();
echo "UPDATED";
} catch (Parse\ParseException $er) {
$ex = $er->getMessage();
echo "<br> Error: ". $ex;
}
}
here is a video that explains more:
https://youtu.be/KWS9fW5MReA

Since you have updated the object in your PHP application, it will keep updated locally unless you reset the action. So you can either:
save the old username and reverse the action in your catch method; or
use $currentUser->fetch() in your catch method; or
instantiate a new user object, do the change attempt in this new object, and finally $currentUser->fetch() only in case of success.
See below one of the possible solutions:
$currentUser = Parse\ParseUser::getCurrentUser();
echo "Current Username is : ". $currentUser->get("username");
if ($currentUser) {
$currentUser->set("username", "ww");
try {
$currentUser->save();
echo "UPDATED";
} catch (Parse\ParseException $er) {
$currentUser->fetch();
$ex = $er->getMessage();
echo "<br> Error: ". $ex;
}
}

Related

Debugging php object instantiation

I am using ajax to call a php script (wordpress). I get status code 200 OK but I dont get any data back.. My script dies, when trying to create an instant of an object. But I cant get any info why..
// create Order object
echo "this gets returned";
try {
if(new Order($auth_login, $auth_password, $caleo_live_mode)) {
echo "works";
} else {
echo "if error";
}
} catch (Exception $e) {
echo "try fail";
}
echo "This does not";
Nothing inside the try block is getting returned.
What can I do to try to see what is going on?
Moved solution from question to answer:
ANSWER:
I figured it out....
I read through the source code of Order and found a try/catch statement which looked like:
catch (Exception $e) {
exit();
}

Laravel 5 Parse

I have the following problem i'm using laravel 5 and laraparse package.Login with parse works without a problem,also things like insert categories works.The problem is for sign up i'm using ParseUser().I use the following code from parse docs for sign up:
$user = new ParseUser();
$user->set("username", $request->username);
$user->set("email", $request->email);
$user->set('isArtist', $isArtist);
$user->set("password", $request->password);
try {
$user->signUp();
return redirect('profile');
} catch (ParseException $ex) {
// Show the error message somewhere and let the user try again.
echo "Error: " . $ex->getCode() . " " . $ex->getMessage();
}
but it returns the following 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.
The keys in config are ok because login and everything else works so the keys are not the problem.

catching mailchimp php api errors

I am trying to create a subscribe method for my laravel app that uses the mailchimp api to subscribe a user to a given list. The method works fine when the email address is not already on the lsit. when it is already subscribed the mailchimp api throws the following error
Mailchimp_List_AlreadySubscribed blah#blah.co is already subscribed to
list Tc App Test List. Click here to update your profile.
with the following code being shown
public function castError($result) {
if($result['status'] !== 'error' || !$result['name']) throw new Mailchimp_Error('We received an unexpected error: ' . json_encode($result));
$class = (isset(self::$error_map[$result['name']])) ? self::$error_map[$result['name']] : 'Mailchimp_Error';
return new $class($result['error'], $result['code']);
}
I have attempted a try catch block to catch the error but it is still being returned to the browser, here is what I tried and were it says MailChimp_Error I tried with Exception as well.
public function subscribe($id, $email, $merge_vars)
{
try {
$this->mailchimp->lists->subscribe($id, $email, $merge_vars);
} catch (MailChimp_Error $e) {
$response = 'an error has occured';
}
return $response;
}
Ultimately I want to be able to run the method and then either return either a success message or a message describing the issue to the user. the 3 possible mailchimp method errors are Email_notexists, list_alreadysubscribed and list does not exist although tihs last one should not occur as I am providing the list in the source code.
edit 1; after being in touch with mailchimp api support they suggested this code but the error still gets returned to the browser in its entirety
try {
$results = $this->mailchimp->lists->subscribe($id, $email, $merge_vars);
} catch (Mailchimp_Error $e) {
if ($e->getMessage()) {
$error = 'Code:'.$e->getCode().': '.$e->getMessage();
}
}
echo $error;
You can do
try
{
$response = $this->mailchimp->lists->addListMember($list_id, [
"email_address" => $email,
"status" => "subscribed",
]);
}
catch (\EXCEPTION $e) {
return $e->getMessage();
}
The \EXCEPTION handles a sort of error for stripe
Subscribe is in a namespace Acme\Emails\Subscribe so catch(Mailchimp_Error $e) looks for Mailchimp_Error in this namespace.
Changing it to catch(\Mailchimp_Error $e) makes it look in the root namespace and then it works as intended

How to validate Facebook App ID

I need to check if the given Facebook app id is valid. Also, I need to check which domain and site configurations are set for this app id. It doesn't matter if it's done through PHP or Javascript.
I checked everywhere but couldn't find any information about this. Any ideas?
You can validate the ID by going to http://graph.facebook.com/<APP_ID> and seeing if it loads what you expect. For the app information, try using admin.getAppProperties, using properties from this list.
Use the Graph API. Simply request:
https://graph.facebook.com/<appid>
It should return you a JSON object that looks like this:
{
id: "<appid>",
name: "<appname>",
category: "<app category>",
subcategory: "<app subcategory>",
link: "<applink>",
type: "application",
}
So, to validate if the specified app_id is indeed the id of an application, look for the type property and check if it says application. If the id is not found at all, it will just return false.
More info: https://developers.facebook.com/docs/reference/api/application/
For example:
<?php
$app_id = 246554168145;
$object = json_decode(file_get_contents('https://graph.facebook.com/'.$app_id));
// the object is supposed to have a type property (according to the FB docs)
// but doesn't, so checking on the link as well. If that gets fixed
// then check on isset($object->type) && $object->type == 'application'
if ($object && isset($object->link) && strstr($object->link, 'http://www.facebook.com/apps/application.php')) {
print "The name of this app is: {$object->name}";
} else {
throw new InvalidArgumentException('This is not the id of an application');
}
?>
Use the Graph API:
$fb = new Facebook\Facebook(/* . . . */);
// Send the request to Graph
try {
$response = $fb->get('/me');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
var_dump($response);
// class Facebook\FacebookResponse . . .
More info:FacebookResponse for the Facebook SDK for PHP

PHP Try and Catch for SQL Insert

I have a page on my website (high traffic) that does an insert on every page load.
I am curious of the fastest and safest way to (catch an error) and continue if the system is not able to do the insert into MySQL. Should I use try/catch or die or something else. I want to make sure the insert happens but if for some reason it can't I want the page to continue to load anyway.
...
$db = mysql_select_db('mobile', $conn);
mysql_query("INSERT INTO redirects SET ua_string = '$ua_string'") or die('Error #10');
mysql_close($conn);
...
Checking the documentation shows that its returns false on an error. So use the return status rather than or die(). It will return false if it fails, which you can log (or whatever you want to do) and then continue.
$rv = mysql_query("INSERT INTO redirects SET ua_string = '$ua_string'");
if ( $rv === false ){
//handle the error here
}
//page continues loading
This can do the trick,
function createLog($data){
$file = "Your path/incompletejobs.txt";
$fh = fopen($file, 'a') or die("can't open file");
fwrite($fh,$data);
fclose($fh);
}
$qry="INSERT INTO redirects SET ua_string = '$ua_string'"
$result=mysql_query($qry);
if(!$result){
createLog(mysql_error());
}
You can implement throwing exceptions on mysql query fail on your own. What you need is to write a wrapper for mysql_query function, e.g.:
// user defined. corresponding MySQL errno for duplicate key entry
const MYSQL_DUPLICATE_KEY_ENTRY = 1022;
// user defined MySQL exceptions
class MySQLException extends Exception {}
class MySQLDuplicateKeyException extends MySQLException {}
function my_mysql_query($query, $conn=false) {
$res = mysql_query($query, $conn);
if (!$res) {
$errno = mysql_errno($conn);
$error = mysql_error($conn);
switch ($errno) {
case MYSQL_DUPLICATE_KEY_ENTRY:
throw new MySQLDuplicateKeyException($error, $errno);
break;
default:
throw MySQLException($error, $errno);
break;
}
}
// ...
// doing something
// ...
if ($something_is_wrong) {
throw new Exception("Logic exception while performing query result processing");
}
}
try {
mysql_query("INSERT INTO redirects SET ua_string = '$ua_string'")
}
catch (MySQLDuplicateKeyException $e) {
// duplicate entry exception
$e->getMessage();
}
catch (MySQLException $e) {
// other mysql exception (not duplicate key entry)
$e->getMessage();
}
catch (Exception $e) {
// not a MySQL exception
$e->getMessage();
}
if you want to log the error etc you should use try/catch, if you dont; just put # before mysql_query
edit :
you can use try catch like this; so you can log the error and let the page continue to load
function throw_ex($er){
throw new Exception($er);
}
try {
mysql_connect(localhost,'user','pass');
mysql_select_db('test');
$q = mysql_query('select * from asdasda') or throw_ex(mysql_error());
}
catch(exception $e) {
echo "ex: ".$e;
}
Elaborating on yasaluyari's answer I would stick with something like this:
We can just modify our mysql_query as follows:
function mysql_catchquery($query,$emsg='Error submitting the query'){
if ($result=mysql_query($query)) return $result;
else throw new Exception($emsg);
}
Now we can simply use it like this, some good example:
try {
mysql_catchquery('CREATE TEMPORARY TABLE a (ID int(6))');
mysql_catchquery('insert into a values(666),(418),(93)');
mysql_catchquery('insert into b(ID, name) select a.ID, c.name from a join c on a.ID=c.ID');
$result=mysql_catchquery('select * from d where ID=7777777');
while ($tmp=mysql_fetch_assoc($result)) { ... }
} catch (Exception $e) {
echo $e->getMessage();
}
Note how beautiful it is. Whenever any of the qq fails we gtfo with our errors. And you can also note that we don't need now to store the state of the writing queries into a $result variable for verification, because our function now handles it by itself. And the same way it handles the selects, it just assigns the result to a variable as does the normal function, yet handles the errors within itself.
Also note, we don't need to show the actual errors since they bear huge security risk, especially so with this outdated extension. That is why our default will be just fine most of the time. Yet, if we do want to notify the user for some particular query error, we can always pass the second parameter to display our custom error message.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
I am not sure if there is a mysql version of this but adding this line of code allows throwing mysqli_sql_exception.
I know, passed a lot of time and the question is already checked answered but I got a different answer and it may be helpful.
$sql = "INSERT INTO customer(FIELDS)VALUES(VALUES)";
mysql_query($sql);
if (mysql_errno())
{
echo "<script>alert('License already registered');location.replace('customerform.html');</script>";
}
To catch specific error in Mysqli
$conn = ...;
$q = "INSERT INTO redirects (ua_string) VALUES ('$ua_string')";
if (mysqli_query($conn, $q)) {
// Successful
}
else {
die('Mysqli Error: '.$conn->error); // Show Error Complete Description
}
mysqli_close($conn);
Use any method described in the previous post to somehow catch the mysql error.
Most common is:
$res = mysql_query('bla');
if ($res===false) {
//error
die();
}
//normal page
This would also work:
function error() {
//error
die()
}
$res = mysql_query('bla') or error();
//normal page
try { ... } catch {Exception $e) { .... } will not work!
Note: Not directly related to you question but I think it would much more better if you display something usefull to the user. I would never revisit a website that just displays a blank screen or any mysterious error message.
$new_user = new User($user);
$mapper = $this->spot->mapper("App\User");
try{
$id = $mapper->save($new_user);
}catch(Exception $exception){
$data["error"] = true;
$data["message"] = "Error while insertion. Erron in the query";
$data["data"] = $exception->getMessage();
return $response->withStatus(409)
->withHeader("Content-Type", "application/json")
->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
}
if error occurs, you will get something like this->
{
"error": true,
"message": "Error while insertion. Erron in the query",
"data": "An exception occurred while executing 'INSERT INTO \"user\" (...) VALUES (...)' with params [...]:\n\nSQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for integer: \"default\"" }
with status code:409.

Categories