Script dies when trying to use $model->save() - php

I am trying to use $model->save() .. but i can't get the error messages like the documentation instead the error message appears with trace error then the script dies.
for example i am trying to use this code:
$user = new Users();
$user->name = "Name";
if(!$user->save()){
//do stuff if there is an error
}
the problem is that i always get the validation error like this and the script dies and never returns false to enter the if condition :
password is required
#0 ..../UsersController.php(106): Phalcon\Mvc\Model->save()
#1 [internal function]: ....\UsersController->createAction()
#2 [internal function]: Phalcon\Dispatcher->callActionMethod(Object(....\UsersController), 'createAction', Array)
#3 [internal function]: Phalcon\Dispatcher->_dispatch()
#4 [internal function]: Phalcon\Dispatcher->dispatch()
#5 ....\public\index.php(41): Phalcon\Mvc\Application->handle()
#6 {main}**

I Finally found the solution, I found that somewhere in the services.php
this line was enabled and that what caused the exception to be thrown
Phalcon\Mvc\Model::setup(['exceptionOnFailedSave' => true] and after turning it to false,i can easily add my conditions and check the errors message using this code.
if ($model->save() === false) {
$messages = $model->getMessages();
foreach ($messages as $message) {
echo $message, "\n";
}
}

you can send flash error using
$this->flash->error("too bad! the form had errors");
$this->flash->success("yes!, everything went very smoothly");
$this->flash->notice("this a very important information");
$this->flash->warning("best check yo self, you're not looking too good.");
see documentation
https://docs.phalconphp.com/en/latest/reference/flash.html

Related

Uncaught exception 'No_Result_Exception' with message 'No results'

I'm working with this codeigniter script called Crysandrea, anyways everything was going smoothly until I tried out the trading system.
Here is the error.
Fatal error: Uncaught exception 'No_Result_Exception' with message 'No results' in C:\xampp\htdocs\application\core\CRYS_Model.php:97
Stack trace: #0 C:\xampp\htdocs\application\core\CRYS_Model.php(190):
CRYS_Model->_process_result(Object(CI_DB_mysql_result), 1) #1
C:\xampp\htdocs\application\controllers\trades.php(535):
CRYS_Composite_Model->findRelation('3', '1', '*', Array) #2 [internal
function]: Trades->accept_trade('2') #3
C:\xampp\htdocs\system\core\CodeIgniter.php(359):
call_user_func_array(Array, Array) #4 C:\xampp\htdocs\index.php(203):
require_once('C:\xampp\htdocs...') #5 {main} thrown in
C:\xampp\htdocs\application\core\CRYS_Model.php on line 97
Here's the code for CRYS_Model.php
protected function _process_result(&$result, $limit=1) {
if (!$result->result_array())
throw new No_Result_Exception();
if ($limit === 1)
return $result->row(0, static::$INNER_MODEL);
else
return $result->result(static::$INNER_MODEL);
}
If you need anything, please say so!

Invalid json in service response

I'm trying to get my profile info using the PHP API, yet it doesn't seem to be working in the last couple days.
My code is as follows:
<?php
try {
$client_id = '****************.apps.googleusercontent.com';
$client_secret = '*********************';
$redirect_uri = '**********************';
$google_key = '***************';
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setDeveloperKey($google_key);
$client->setAccessType('offline');
$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile'));
$plus = new Google_Service_Plus($client);
if(isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$accessToken = $client->getAccessToken();
$refreshToken = json_decode($accessToken)->refresh_token;
setcookie('refresh_token', $refreshToken, (time()+60*60*24*30));
setcookie('access_token', $accessToken, (time()+60*60*24*30));
header('Location: ./');
exit();
}
if(isset($_COOKIE['access_token']) && $_COOKIE['access_token']) {
$refreshToken = json_decode($_COOKIE['access_token'])->refresh_token;
$accessToken = $_COOKIE['access_token'];
setcookie('access_token', $accessToken, (time()+60*60*24*30));
$client->setAccessToken($_COOKIE['access_token']);
} else {
$authUrl = $client->createAuthUrl();
}
if($client->getAccessToken()) {
$accessToken = $client->getAccessToken();
setcookie('access_token', $accessToken, (time()+60*60*24*30));
if(isset($plus)){
$userInfo = $plus->people->get('me');
}
}
if($client->isAccessTokenExpired() && isset($userInfo)){
$refreshToken = $_COOKIE['refresh_token'];
$client->refreshToken($refreshToken);
$newtoken = $client->getAccessToken();
setcookie('access_token', $newtoken, (time()+60*60*24*30));
header('Location: ./');
exit();
}
} catch (Google_Service_Exception $gse){
error_log($gse, 0);
} catch (Google_Auth_Exception $gae){
error_log($gae, 0);
}
?>
I will be using a database soon, but i'd like to get it working with cookies first. The error I'm getting is as follows:
[05-Aug-2015 20:40:36 Europe/London] exception 'Google_Service_Exception' with message 'Error calling GET https://www.googleapis.com/plus/v1/people/me?key=**********************: (403) ‹' in /home5/commodit/public_html/workflow/src/Google/Http/REST.php:110
Stack trace:
#0 /home5/commodit/public_html/workflow/src/Google/Http/REST.php(62): Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request), Object(Google_Client))
#1 [internal function]: Google_Http_REST::doExecute(Object(Google_Client), Object(Google_Http_Request))
#2 /home5/commodit/public_html/workflow/src/Google/Task/Runner.php(174): call_user_func_array(Array, Array)
#3 /home5/commodit/public_html/workflow/src/Google/Http/REST.php(46): Google_Task_Runner->run()
#4 /home5/commodit/public_html/workflow/src/Google/Client.php(593): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request))
#5 /home5/commodit/public_html/workflow/src/Google/Service/Resource.php(237): Google_Client->execute(Object(Google_Http_Request))
#6 /home5/commodit/public_html/workflow/src/Google/Service/Plus.php(562): Google_Service_Resource->call('get', Array, 'Google_Service_...')
#7 /home5/commodit/public_html/workflow/includes/head.php(87): Google_Service_Plus_People_Resource->get('me')
#8 /home5/commodit/public_html/workflow/index.php(4): include('/home5/commodit...')
#9 {main}
I also get a "Response not valid json" if i try to use OAuth2 instead of Google Plus as the service.
[05-Aug-2015 20:46:02 Europe/London] exception 'Google_Service_Exception' with message 'Invalid json in service response: ‹' in /home5/commodit/public_html/workflow/src/Google/Http/REST.php:125
Stack trace:
#0 /home5/commodit/public_html/workflow/src/Google/Http/REST.php(62): Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request), Object(Google_Client))
#1 [internal function]: Google_Http_REST::doExecute(Object(Google_Client), Object(Google_Http_Request))
#2 /home5/commodit/public_html/workflow/src/Google/Task/Runner.php(174): call_user_func_array(Array, Array)
#3 /home5/commodit/public_html/workflow/src/Google/Http/REST.php(46): Google_Task_Runner->run()
#4 /home5/commodit/public_html/workflow/src/Google/Client.php(593): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request))
#5 /home5/commodit/public_html/workflow/src/Google/Service/Resource.php(237): Google_Client->execute(Object(Google_Http_Request))
#6 /home5/commodit/public_html/workflow/src/Google/Service/Oauth2.php(175): Google_Service_Resource->call('get', Array, 'Google_Service_...')
#7 /home5/commodit/public_html/workflow/includes/head.php(89): Google_Service_Oauth2_Userinfo_Resource->get()
#8 /home5/commodit/public_html/workflow/index.php(4): include('/home5/commodit...')
#9 {main}
Thanks for any help!
Bethany
P.S - I have also tried the "opt_params" variable but it still says invalid JSON :(
I suggest to check the Google/Config.php file, there are several default parameters that can be adjust to get solution for different problems.
In my case i was also receiving an invalid-json-in-service-response, i was sure of correct credential settings, i tryed to run the URL that was passed to Google API with GET protocol and query string, and always had full plain text in json format answer, so i looked at "disable_gzip" parameter and modifiy it to see what was the behaviour if changed.
'Google_Http_Request' => array(
// Disable the use of gzip on calls if set to true. Defaults to false.
'disable_gzip' => self::GZIP_DISABLED, //self::GZIP_ENABLED,
// We default gzip to disabled on uploads even if gzip is otherwise
// enabled, due to some issues seen with small packet sizes for uploads.
// Please test with this option before enabling gzip for uploads in
// a production environment.
'enable_gzip_for_uploads' => self::GZIP_UPLOADS_DISABLED,
),
You may set different values for a Google_Client Config, Class Attribute invoking the defined method.
public function setClassConfig($class, $config, $value = null)

Creating an Invoice with Paypal-Php-SDK fails with "Can not deserialize instance of java..." error

I'm trying to create an invoice with Paypal-Php-Sdk, everything's okay, but when I try to set Billing Info something goes wrong and I get this error:
{"name":"VALIDATION_ERROR","message":"Invalid request - see details.","debug_id":"2d34973f0cfef","details":[{"field":"billing_info","issue":"Can not deserialize instance of java.util.ArrayList out of START_OBJECT token at line:1, column:2"}]}exception 'PayPal\Exception\PayPalConnectionException' with message 'Got Http response code 400 when accessing https://api.sandbox.paypal.com/v1/invoicing/invoices.' in /var/www/admin/data/www/****/vendor/paypal/rest-api-sdk-php/lib/PayPal/Core/PayPalHttpConnection.php:176
Stack trace:
#0 /var/www/admin/data/www/****/vendor/paypal/rest-api-sdk-php/lib/PayPal/Transport/PayPalRestCall.php(74): PayPal\Core\PayPalHttpConnection->execute('{"billing_info"...')
#1 /var/www/admin/data/www/****/vendor/paypal/rest-api-sdk-php/lib/PayPal/Common/PayPalResourceModel.php(103): PayPal\Transport\PayPalRestCall->execute(Array, '/v1/invoicing/i...', 'POST', '{"billing_info"...', NULL)
#2 /var/www/admin/data/www/****/vendor/paypal/rest-api-sdk-php/lib/PayPal/Api/Invoice.php(736): PayPal\Common\PayPalResourceModel::executeCall('/v1/invoicing/i...', 'POST', '{"billing_info"...', NULL, Object(PayPal\Rest\ApiContext), NULL)
#3 var/www/admin/data/www/****/application/controllers/store.php(487): PayPal\Api\Invoice->create(Object(PayPal\Rest\ApiContext))
#4 [internal function]: Store->payment()
#5 /var/www/admin/data/www/****/system/core/CodeIgniter.php(359): call_user_func_array(Array, Array)
#6 /var/www/admin/data/www/****/index.php(202): require_once('/var/www/admin/...')
#7 {main}
Here's the code I use:
$client_id = "****";
$secret = "****";
$apiContext = new ApiContext(new OAuthTokenCredential(
$client_id, $secret));
$merchantInfo = new PayPal\Api\MerchantInfo();
$merchantInfo->setEmail("****");
$merchantInfo->setWebsite("****");
$billingInfo = new PayPal\Api\BillingInfo();
$billingInfo->setEmail("****");
$invoice = new PayPal\Api\Invoice();
$invoice->setMerchantInfo($merchantInfo);
$invoice->setBillingInfo($billingInfo);
try
{
$invoice->create($apiContext);
} catch (PayPal\Exception\PayPalConnectionException $ex) {
echo $ex->getData();
die($ex);
} catch (Exception $ex) {
die($ex);
}
Here's what I've received from Paypal support:
Change these two lines to this:
$invoice->setMerchantInfo(array($merchantInfo));
$invoice->setBillingInfo(array($billingInfo));
Both billing info and merchant info takes in array of objects, not an object directly.
It's strange but it started to work when I changed this only for Billing Info, so the right code for me was:
$invoice->setMerchantInfo($merchantInfo);
$invoice->setBillingInfo(array($billingInfo));

unable to update status using facebook PHP sdk: couldn't open file

i am trying to update Facebook status using Facebook PHP SDK.
i have updated my status several time using the code below:
try {
$session = new FacebookSession($page_token);
$session->validate();
(new FacebookRequest($session, 'POST', '/' . $id . '/feed', array(
'message' => $message
)))->execute();
} catch(FacebookRequestException $e) {
.....
}
but it giving me error while i am trying to update this status:
RiversofGrue: Returns To The Palace http://clc.li/cxG #Grueheads #horror #crashpalace
surprisingly a have updated this status from my localhost successfully. but in the production server it is throwing error.
The error is:
Error Message: couldn't open file "RiversofGrue: Returns To The Palace http://clc.li/cxG #Grueheads #horror #crashpalace"
File: .../vendor/facebook/php-sdk-v4/src/Facebook/HttpClients/FacebookCurlHttpClient.php
Error Code: 26
Line: 150
TraceAsString: #0 .../vendor/facebook/php-sdk-v4/src/Facebook/FacebookRequest.php(248): Facebook\HttpClients\FacebookCurlHttpClient->send()
#1 .../Demo.php(146): Facebook\FacebookRequest->execute()
#2 .../DemoDemo.php(31): Demo->execute()
#3 .../vendor/laravel/framework/src/Illuminate/Console/Command.php(112): FacebookJobCommand->fire()
#4 .../vendor/symfony/console/Symfony/Component/Console/Command/Command.php(253): Illuminate\Console\Command->execute()
#5 .../vendor/laravel/framework/src/Illuminate/Console/Command.php(100): Symfony\Component\Console\Command\Command->run()
#6 .../vendor/symfony/console/Symfony/Component/Console/Application.php(889): Illuminate\Console\Command->run()
#7 .../vendor/symfony/console/Symfony/Component/Console/Application.php(193): Symfony\Component\Console\Application->doRunCommand()
#8 .../vendor/symfony/console/Symfony/Component/Console/Application.php(124): Symfony\Component\Console\Application->doRun()
#9 .../artisan(59): Symfony\Component\Console\Application->run()
#10 {main}
I don't know what is the problem. Any idea guys???
Thanks
Edit:
#ceejayoz 's answer help me a lot. i was working on the wrong path. but the main problem was #. if ceejayoz did not show me that, may be i was going to spend many more time to figure it out. if there was a way to accept two answer, i would love to accept ceejayoz also. thanks.
Original:
Finally i have decided to cut off the starting # from the string. so i have used this:
if(strpos($message, "#") === 0){
$message = substr($message, 1);
}
I did not find the solution, so i have used this path. if you have any other solution please post.
Your issue is that the message starts with #. cURL treats any parameter starting with # in a POST request to be a filename, and attempts to load and send that data's file contents as that parameter. This is very useful for things like file uploads, but a problem in your situation.
You should be able to fix this by wrapping your FacebookRequest parameters with http_build_query like so:
try {
$session = new FacebookSession($page_token);
$session->validate();
(new FacebookRequest($session, 'POST', '/' . $id . '/feed', http_build_query(array(
'message' => $message
))))->execute();
} catch(FacebookRequestException $e) {
.....
}

Laravel Routes for Facebook Login

I'm sorta kinda new again on the programming scene. I did some php back in college but I haven't touched it ever since and now I'm working on a side project. I'm Trying to create a simple app that will use Laravel and Facebook Login as the only source of logging into the app.
I did found some tutorials on how to do this but it seems to be outdated. (src = http://maxoffsky.com/code-blog/integrating-facebook-login-into-laravel-application/)
It seems to be all working until the Route.php part.
I have this code under the route.php
Route::get('/', function()
{
return 'Hello World';
});
Route::get('login/fb', function() {
$facebook = new Facebook(Config::get('facebook'));
$params = array(
'redirect_uri' => url('/login/fb/callback'),
'scope' => 'email', 'public_profile', 'user_friends' ,
);
return Redirect::away($facebook->getLoginUrl($params));
});
Route::get('login/fb/callback', function() {
$code = Input::get('code');
if (strlen($code) == 0) return Redirect::to('/')->with('message', 'There was an error communicating with Facebook');
$facebook = new Facebook(Config::get('facebook'));
$uid = $facebook->getUser();
if ($uid == 0) return Redirect::to('/')->with('message', 'There was an error');
$me = $facebook->api('/me');
dd($me);
});
In the said tutorial, I'm being asked to access the login/fb of the route. I tried doing this by accessing localhost/myapp/public/login/fb and it gave me an error
Whoops! Something went wrong
I tried to set the debug => true and I got a more puzzling set of errors
Symfony\Component\HttpKernel\Exception\NotFoundHttpException thrown with message ""
Stacktrace:
#11 Symfony\Component\HttpKernel\Exception\NotFoundHttpException in D:\Xampp\htdocs\GrabATable\bootstrap\compiled.php:5465
#10 Illuminate\Routing\RouteCollection:match in D:\Xampp\htdocs\GrabATable\bootstrap\compiled.php:4794
#9 Illuminate\Routing\Router:findRoute in D:\Xampp\htdocs\GrabATable\bootstrap\compiled.php:4782
#8 Illuminate\Routing\Router:dispatchToRoute in D:\Xampp\htdocs\GrabATable\bootstrap\compiled.php:4774
#7 Illuminate\Routing\Router:dispatch in D:\Xampp\htdocs\GrabATable\bootstrap\compiled.php:706
#6 Illuminate\Foundation\Application:dispatch in D:\Xampp\htdocs\GrabATable\bootstrap\compiled.php:687
#5 Illuminate\Foundation\Application:handle in D:\Xampp\htdocs\GrabATable\bootstrap\compiled.php:7440
#4 Illuminate\Session\Middleware:handle in D:\Xampp\htdocs\GrabATable\bootstrap\compiled.php:8047
#3 Illuminate\Cookie\Queue:handle in D:\Xampp\htdocs\GrabATable\bootstrap\compiled.php:7994
#2 Illuminate\Cookie\Guard:handle in D:\Xampp\htdocs\GrabATable\bootstrap\compiled.php:10615
#1 Stack\StackedHttpKernel:handle in D:\Xampp\htdocs\GrabATable\bootstrap\compiled.php:648
#0 Illuminate\Foundation\Application:run in D:\Xampp\htdocs\GrabATable\public\index.php:49
Can someone point to me what am I doing wrong here? Thanks in advance. :)

Categories