detect exception - if - php

If i have this:
function valid($valor) {
foreach($valor as $valor){
if (!empty($valor)) {
if (preg_match("/[^A-Za-z0-9-áàçéúâôóã ]|(\d+)/", $valor)) {
$error = "invalid";
throw new Exception($error);
}
}
}
}
and
if (isset($_POST['myform'])){
if ($val_->valid($form1['new'])) {
echo "ok";
}
else
echo "bad";
}
but i got: Fatal error: Uncaught exception 'Exception
What i want is basically something like that (pseudo code):
if (exception true) {
echo "problem";
}
else
echo "ok";
How can i do that ?

You have to handle the exception.
try {
...
//statements
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
EDIT:
try{
if ($val_->valid($form1['new'])) {
echo "ok";
}
}catch(Exception $e){
echo "bad";
}

Related

Facebook SDK getGraphNode(); as array not working

So i started learning facebook sdk and i wanted to get attening_count/list from my event page as an array, but i'm unable to get it working. It only displays me id, name etc.
if (isset($_SESSION['access_tok'])) {
echo 'Out!<br>';
try {
$response = $fb->get('me/accounts?fields=', $_SESSION['access_tok']);
$page = $response->getGraphEdge();
} 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;
}
foreach($page as $pages)
{
$name = $pages['name'];
$cc = $pages['access_token'];
if($name == 'Testing')
{
try {
$response1 = $fb->get('/eventid', $cc);
$page1 = $response1->getGraphNode()->asArray();
} 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;
}
$page1 ['id'];
}
else
{
}
}
}

I can't catch Facebookexceptions in try catch block

I'm having an issue catching the proper exception, no matter what i do i get the same response. This is the response i get in the view
Error validating access token: The user has not authorized application FacebookResponseException in FacebookResponseException.php line 89:
The issue arrises after a user de-authorizes my app from Facebook after have created an access_token , what I ant to do is catch the exception and automatically log them out and flush the session: But i can't seem to find the right exception to catch
I've tested with all these: I narrowed the problem to being inside this catch block: I included the catch block, then the full code I'm using in my route's function after.
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('/me?fields=permissions');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookAuthenticationException $e) {
echo 'Facebook Dan1 returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookAuthorizationException $e) {
echo 'Facebook Dan2 returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookClientException $e) {
echo 'Facebook Dan3 returned an error: ' . $e->getMessage();
exit;
} catch(Exception $e) {
echo 'Facebook Dan4 returned an error: ' . $e->getMessage();
exit;
}
now my full code for this page:
public function getHomeProfile(Request $request, LaravelFacebookSdk $fb)
{
$user = Auth::user();
$token = Session::get('fb_user_access_token');
$twitterToken = Session::get('access_token');
// $fb->setDefaultAccessToken($token);
// $resp = $fb->get('/debug_token?=input_token=$token');
// dd($resp);
$permissionsToRequest = ([
'public_profile',
'publish_actions'
]);
$login_link_for_public_actions = $fb->getLoginUrl($permissionsToRequest, 'http://pms.dev:8000/facebook/publicactions/callback');
if (isset($token)) {
$fb->setDefaultAccessToken($token);
// $debugToken = $fb->get('/debug_token?input_token=' . $token);
// $debugTokenResponse = $debugToken->getGraphNode()->asArray();
// echo "<pre>";
// print_r($debugTokenResponse);
// echo "<pre>";
// die();
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('/me?fields=permissions');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookAuthenticationException $e) {
echo 'Facebook Dan1 returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookAuthorizationException $e) {
echo 'Facebook Dan2 returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookClientException $e) {
echo 'Facebook Dan3 returned an error: ' . $e->getMessage();
exit;
} catch(Exception $e) {
echo 'Facebook Dan4 returned an error: ' . $e->getMessage();
exit;
}
// Returns a `Facebook\GraphNodes\GraphUser` collection
$facebookuser = $response->getGraphUser();
//$ty= json_decode($facebookuser);
$permissions = $facebookuser['permissions'];
$checked = '';
foreach ($permissions as $p) {
if ($p['permission'] == 'publish_actions' && $p['status'] == 'granted' ) {
$checked = 'checked';
}
}
} else {
$checked = null;
}
if (isset($twitterToken)) {
$twitterChecked = 'checked';
} else {
$twitterChecked = null;
}
$userPlugsCountry = $user->plugsCountry()->setPath($request->url());
$user_plugs_list = Auth::user()->plugs()->lists('id');
if (Auth::check()) {
$statuses = Status::where(function($query) {
return $query->where('user_id', Auth::user()->id)->where('parent_id', NULL)
->orWhereIn('user_id', Auth::user()->plugs()->lists('id'));
})->orderBy('created_at', 'desc')->paginate(7);
}
if (array_key_exists('REQUEST_SCHEME', $_SERVER)) {
$cors_location = $_SERVER["REQUEST_SCHEME"] . "://" . $_SERVER["SERVER_NAME"] .
dirname($_SERVER["SCRIPT_NAME"]) . "/cloudinary_cors.html";
} else {
$cors_location = "http://" . $_SERVER["HTTP_HOST"] . "/cloudinary_cors.html";
}
if ($request->ajax()) {
return [
'statuses' => view('ajax.status')->with('user', $user)->with(compact('statuses'))->render(),
'next_page' => $statuses->nextPageUrl(),
'countries' => view('ajax.next_countries')->with('user', $user)->with(compact('userPlugsCountry'))->render(),
'next_countries_page' => $userPlugsCountry->nextPageUrl(),
'prev_countries_page' => $userPlugsCountry->previousPageUrl(),
];
}
return view('profile.home')->with('user', $user)->with('cors_location', $cors_location)->with('statuses',$statuses)->with('userPlugsCountry',$userPlugsCountry)->with('checked', $checked)->with('login_link_for_public_actions',$login_link_for_public_actions)->with('twitterChecked', $twitterChecked);
}
OK i figured out whet i was doing wrong. I'm using sammyk laravelfacebooksdk https://github.com/SammyK/LaravelFacebookSdk and was only including:
use SammyK\LaravelFacebookSdk\LaravelFacebookSdk;
I didn't realize i also needed to add
use Facebook;
to the namespace.
easy fix, that gave me a lot of trouble.

PHP rollback method has failed

I have tried this piece of code and unfortunately rollback method failed!
Thank in advance!!
$bash = new mysqli('localhost', 'root', '','dbastegoi');
$bash->autocommit(FALSE);
echo 'timologio';
$r =$bash->query("INSERT INTO tbparastatika (strArithmos, fkERGO, strPROMITH, sngCOST, intTYPOS, intDRASH) VALUES ('1','1001','123123123',800138,1,1)");
//ΕΙΣΑΓΩΓΗ ΤΙΜΟΛΟΓΙΟΥ
$i = $bash->insert_id;
ECHO PHP_EOL;
echo 'dapanh';
try {
$r =$bash->query("INSERT INTO tbdapanes_stegash (idPARASTATnIKO, sngCOST, fkDIAMERISMA, intMONTH) VALUES ($i,100,1,1)");
echo $r;
} catch (Exception $e) {
echo 'error2';
}
$bash->commit();
$bash->rollback();
//$SYNDESH->commit();
//$SYNDESH->rollback();
$bash->close();
You can not make a commit first and then a roolback. You have to make a commit if your query runs without error or make a rollback if you get an error:
try {
$r =$bash->query("INSERT INTO tbdapanes_stegash (idPARASTATnIKO, sngCOST, fkDIAMERISMA, intMONTH) VALUES ($i,100,1,1)");
echo $r;
$bash->commit();
} catch (Exception $e) {
echo 'error2';
$bash->rollback();
}

php throw exception stop execution

I have this code:
function divide($a,$b){
try{
if($b==0){
throw new Exception("second variable can not be 0");
}
return $a/$b;
}
catch(Exception $e){
echo $e->getMessage();
}
}
echo divide(20,0);
echo "done";
It throws an exception when the second parameter is 0. How can I stop done from printing?
Don't catch your exception in divide() and catch it later:
function divide($a,$b){
if($b==0){
throw new Exception("second variable can not be 0");
}
return $a/$b;
}
try {
echo divide(20,0);
echo "done";
} catch(Exception $e){
echo $e->getMessage();
}

No handler in dropbox sdk?

I'm trying to get an example from the dropbox sdk to work.
Here is some of the code that is in index.php in the root.
$req = $_SERVER['SCRIPT_NAME'];
if ($req === "/") {
//a bunch of code and elseif:s
}else{
echo renderHtmlPage("Bad URL", "No handler for $req");
exit;
}
I get the following output:
Bad URL
No handler for /index.php
How come req is set to index and how could it be set to / for example?
Full code
$dbxClient = getClient();
if ($dbxClient === false) {
header("Location: /dropbox-auth-start");
exit;
}
$path = "/";
if (isset($_GET['path'])) $path = $_GET['path'];
if (isset($_GET['dl'])) {
passFileToBrowser($dbxClient, $path);
}
else {
$entry = $dbxClient->getMetadataWithChildren($path);
if ($entry['is_dir']) {
echo renderFolder($entry);
}
else {
echo renderFile($entry);
}
}
}
else if ($req === "/dropbox-auth-start") {
$authorizeUrl = getWebAuth()->start();
header("Location: $authorizeUrl");
}
else if ($req === "/dropbox-auth-finish") {
try {
list($accessToken, $userId, $urlState) = getWebAuth()->finish($_GET);
assert($urlState === null);
unset($_SESSION['dropbox-auth-csrf-token']);
}
catch (dbx\WebAuthException_BadRequest $ex) {
error_log("/dropbox-auth-finish: bad request: " . $ex->getMessage());
// Respond with an HTTP 400 and display error page...
exit;
}
catch (dbx\WebAuthException_BadState $ex) {
// Auth session expired. Restart the auth process.
header('Location: /dropbox-auth-start');
exit;
}
catch (dbx\WebAuthException_Csrf $ex) {
error_log("/dropbox-auth-finish: CSRF mismatch: " . $ex->getMessage());
// Respond with HTTP 403 and display error page...
exit;
}
catch (dbx\WebAuthException_NotApproved $ex) {
echo renderHtmlPage("Not Authorized?", "Why not, bro?");
exit;
}
catch (dbx\WebAuthException_Provider $ex) {
error_log("/dropbox-auth-finish: unknown error: " . $ex->getMessage());
exit;
}
catch (dbx\Exception $ex) {
error_log("/dropbox-auth-finish: error communicating with Dropbox API: " . $ex->getMessage());
exit;
}
// NOTE: A real web app would store the access token in a database.
$_SESSION['access-token'] = $accessToken;
echo renderHtmlPage("Authorized!", "Auth complete, <a href='/'>click here</a> to browse");
}
else if ($req === "/unlink") {
// "Forget" the access token.
unset($_SESSION['access-token']);
header("Location: /");
}
else if ($req === "/upload") {
if (empty($_FILES['file']['name'])) {
echo renderHtmlPage("Error", "Please choose a file to upload");
exit;
}
if (!empty($_FILES['file']['error'])) {
echo renderHtmlPage("Error", "Error ".$_FILES['file']['error']." uploading file. See <a href='http://php.net/manual/en/features.file-upload.errors.php'>the docs</a> for details");
exit;
}
$dbxClient = getClient();
$remoteDir = "/";
if (isset($_POST['folder'])) $remoteDir = $_POST['folder'];
$remotePath = rtrim($remoteDir, "/")."/".$_FILES['file']['name'];
$fp = fopen($_FILES['file']['tmp_name'], "rb");
$result = $dbxClient->uploadFile($remotePath, dbx\WriteMode::add(), $fp);
fclose($fp);
$str = print_r($result, TRUE);
echo renderHtmlPage("Uploading File", "Result: <pre>$str</pre>");
}

Categories