I am trying to use phpunit to test connection, I already make error_reporting(0) and assign PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT, but when I give the wrong information on purpose, it always dump error message, for example, if I give the wrong account, it shows
PDOException: SQLSTATE[HY000] [1045] Access denied for user 'test'#'localhost' (us
ing password: YES)
How to turn it off?
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT => false,
);
$dsn = 'mysql:host=' . $config['host'] . ';dbname=' . $config['database'] . ';charset=utf8';
try {
$this->dbh = new PDO($dsn, $config['username'], $config['password'], $options);
} catch (PDOExeception $e) {
// Do something
}
PDO::__construct will always throw a PDOException if the connection fails. There is nothing you can do about that. Any sane application should throw exception if it fails to connect or maybe you have good reason to explain why you need to turn off exception on connections.
Beside the connection It will work on others transactions.
Example:
<?php
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT,
PDO::ATTR_PERSISTENT => false,
);
$dsn = 'mysql:host=' . $config['host'] . ';dbname=' . $config['database'] . ';charset=utf8';
try {
//THIS WILL THROW EXECPTION IF FAILED, NO MATTER WHAT ERROR MODE YOU SET
$this->dbh = new PDO($dsn, $config['username'], $config['password'], $options);
} catch (PDOException $e) {
// Do something
}
//JUST SILENT THIS WILL NOT CAUSE EXCEPTION
$dbh->query("SELECT badColumn FROM wrongTable");
?>
Related
when i tried to connect to Soap Api, i'm getting this error :
SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://www.lignedublanc.fr/index.php/api/soap/?wsdl' : failed to load external entity "https://www.lignedublanc.fr/index.php/api/soap/?wsdl
i tried with soap UI and same errors.
i tried everything on the net but nothing helped.
Maybe someone here can help me ?
<?php
ini_set('soap.wsdl_cache_enabled',0);
ini_set('soap.wsdl_cache_ttl',0);
$url = 'https://www.lignedublanc.fr/index.php/api/soap/?wsdl=1';
$MagentoAPILogin = '';
$MagentoAPIPass = '';
$context = stream_context_create([
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
]
]);
try {
echo "Connecting to : $url\n";
//$client = new SoapClient($url);
$client = new SoapClient($url, ['stream_context' => $context]);
echo $client->login($MagentoAPILogin, $MagentoAPIPass)."\n";
echo 'Login successful';
} catch (Exception $e) {
echo 'Login fail'."\n";
echo $e->getMessage()."\n";
echo $e->getTraceAsString()."\n";
}
I believe the problem is caused by the server not being able to access the API from the local machine. It is actually the .htaccess file that blocking any hosts except the development machines. Hence, it results in a 403 Forbidden error which is actually the SOAP error. For more reference, have a look:
Unable to connect to Magento SOAP API v2 due to "failed to load external entity"
I would like my site to connect to another database with the same credentials as the current one if the current one is unavailable or not found.
You can try a connection by using a query and if it fails change the connection.
try {
User::find(1); // or any other SQL query you want to check
} catch (\Exception $e) {
config(['database.connections.data' => array( // you don't have to add the connection runtime but it can be done.
'driver' => 'sqlsrv',
'host' => $connection['Database_Server'],
'database' => $connection['Database_Name'],
'username' => $connection['Database_User'],
'password' => $connection['Database_Pass'
)]);
DB::setDefaultConnection('data'); // change the default connection
i am requesting a webservice using :
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
try {
$client = new Client();
$response = $client->request('GET', $url); //it crashes at this line
$content = json_decode($response->getBody(), true);
}
catch (ConnectException $e) {
\Drupal::logger('amu_hal')->error('incorrect_url'.$url);
}
today the distant server return a error 500.
How can i modify my code not to crash my site when it happens?
I assume that by distant server you mean a server that takes a long time to connect. You can specify a timeout for the request.
Or perhaps the server returned error 500 and it fails during json_decode? You can check the status code returned by the request.
Or even perhaps the code is failing the line that you indicate but the exception ConnectException is not being caught? Try using Exception as a catch-all to debug this situation.
Instead of using Guzzle directly, I recommend that you use the Drupal wrapper (which uses Guzzle under the hood).
$client = Drupal::httpClient();
$request = $client->get($uri, ['connect_timeout' => 5]);
if ($request->getStatusCode() === 200) {
echo 'Connection Success';
} else {
echo sprintf('Error %d occurred', $request->getStatusCode());
}
I am trying to use google-api-client in PHP for a project.
I got a "permission denied" response while at this statement:
$client->getAuth()->refreshTokenWithAssertion();
Google_IO_Exception, Message:Failed to connect to 74.125.193.84: Permission denied
File: /home/www/blah.com/restful/libs/Google/IO/Curl.php
Line:81
/home/www/blah.com/restful/libs/Google/IO/Abstract.php(125): Google_IO_Curl->executeRequest(Object(Google_Http_Request))
#1 /home/www/blah.com/restful/libs/Google/Auth/OAuth2.php(326): Google_IO_Abstract->makeRequest(Object(Google_Http_Request))
#2 /home/www/blah.com/restful/libs/Google/Auth/OAuth2.php(306): Google_Auth_OAuth2->refreshTokenRequest(Array)
#3 /home/www/blah.com/restful/v2/index.php(122): Google_Auth_OAuth2->refreshTokenWithAssertion()
I checked all my credentials and they look correct, what could be the problem?
Thanks,
John
code:
$client_id = '1234blahblahblah.apps.googleusercontent.com'; //Client ID
$service_account_name = '1234blahblah#developer.gserviceaccount.com'; //Email Address
$key_file_location = 'blahblah-1234.p12'; //key.p12
$client = new Google_Client();
$client->setApplicationName("test");
$service = new Google_Service_Calendar($client);
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/calendar'),
$key
);
print_r($cred);
$client->setAssertionCredentials($cred);
$client->setClientId($client_id);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion(); //<<<<<failed here.
}
$_SESSION['service_token'] = $client->getAccessToken();
echo $_SESSION['service_token'];
}
Hi John I´ve the same problem and finally this works for me:
Before the lines:
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion(); //<<<<<failed here.
}
I put a try catch and that returns me that I had a writtin permissions problem:
try {
$client->getAuth()->refreshTokenWithAssertion($cred);
} catch (Exception $e) {
var_dump($e->getMessage());
}
I could do 2 things:
1) Go to Google/src/Config.php and change line 94: 'directory' => sys_get_temp_dir() . '/Google_Client'and change the directory to save cache temp files
2) or like me, made a echo sys_get_temp_dir(); before the try catch and give a chmod 777 permission to that dir
This solution works for me, I hope also for you. Anyway made an try/catch waiting for the exception message
See the service-account.php sample in the examples/ directory of the Google APIs Client Library for PHP on Github.com:
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred); // set credentials there
}
We use a zend framework 2 for a web application.
We though to have disabled error_reporting and display_errors in our production environment.
But if an SQL error occured (It should not in production but ... :-) ), the exception is still displayed:
PDOException
File:
[...]/vendor/doctrine/dbal/lib/Doctrine/DBAL/Statement.php:165
Message:
SQLSTATE[42000]: Syntax error or access violation
The query use Doctrine\DBAL\Statement (Doctrine2).
We cannot find where to globally catch this exception.
Ensure you have the correct view_manager config settings.
// config/autoload/global.php
return array(
'view_manager' => array(
'display_not_found_reason' => false,
'display_exceptions' => false,
),
);
Remember that this config is merged; if it's in your main global.php it will take preference over the module.config.php.
How it works
Every time ZF2 encounters and error (an exception) it will always catch the error. Instead of 'rethrowing' the exception information to the screen, the info is added to the MVC event and an 'error' event is triggered (either dispatch.error or render.error depending on where it is within the dispatch loop).
The Zend\Mvc\View\Http\ViewManager attaches 'error listeners' to handle these occurrences - (normally to show the error template). If you're using the standard skeleton application, the default error template will check the display_exceptions option and only render the error if it's enabled.
inside: Zend\Db\Adapter\Driver\Pdo\Connection
search for line :
$this->resource = new \PDO($dsn, $username, $password, $options);
$this->resource->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
and change it into:
$this->resource = new \PDO($dsn, $username, $password, $options);
$this->resource->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_SILENT);
I don't know if there is a way to override it globally without changing it in the library itself..
this is how i do it, inside index.php
try {
include ROOT . '/init_autoloader.php';
Zend\Mvc\Application::init(include 'config/application.config.php')->run();
} catch (Exception $e) {
if (IS_DEVELOPMENT_SERVER)
throw $e;
else {
echo('Error : ' . $e->getCode() . " " . $e->getMessage());
}
}