Some try catch issue with php - php

I'm trying to create a class for work with crontab in php.
I used this tutorial.
I've installed libssh2 but as you can see there is no work with it yet. So I have a file Ssh2_crontab_manager.php on my server. Here it's content:
<?php
Class Ssh2_crontab_manager
{
private $connection;
private $path;
private $handle;
private $cron_file;
function __construct($host=NULL, $port=NULL, $username=NULL, $password=NULL)
{
$path_length = strrpos(__FILE__, "/");
$this->path = substr(__FILE__, 0, $path_length) . '/';
$this->handle = 'crontab.txt';
$this->cron_file = "{$this->path}{$this->handle}";
/*try
{
if ((is_null($host)) || (is_null($port)) || (is_null($username)) || (is_null($password))) throw new Exception("Please specify the host, port, username and password!");
}
catch
{
}*/
}
}
?>
And here is noReplyCrontab.php where I try to use this class:
<?php
include './lib/Ssh2_crontab_manager.php';
//$crontab = new Ssh2_crontab_manager('host', '22', 'user', 'pass');
echo 'WORKS';
?>
If I run it now, it says 'works', but if I uncomment try/catch block it shows just white screen, so I suppose that there is some mistake. Any one can show it to me?

Your code says
catch
{
}
But catch What?
You have to provide that value to catch clause
catch (Exception $e)
{
//now it will work fine
}
Manual

try this
try
{
if (true) throw new Exception("Please specify the host, port, username and password!");
}
catch(Exception $e)
{
echo $e->getMessage();
}

Related

Exception isn't being picked up in catch

I current have a class that holds this method:
public function getUser(
) {
if (!empty($this->UserName)){
return $this->UserName;
} else {
throw new Exception('Empty UserName');
}
}
When I then run this method when the UserName is NOT set, the catch is not picking up the thrown exception, the page just silently dies.
try {
$example = $obj->getUser();
} catch (Exception $ex) {
die($ex->getMessage());
}
Suggestions? - I have read documentation and found nothing.
This seems to work, I had to recreate what I assumed would be your class.
<?php
class User {
public $UserName = '';
public function getUser() {
if (empty($this->UserName))
throw new Exception('UserName is empty!');
return $this->UserName;
}
}
try {
$user = (new User())->getUser();
} catch (Exception $e) {
echo $e->getMessage();
}
?>
Output
I can only assume that your variable is not actually empty.
Notice
In PHP a string with a space in it is NOT classed as empty,
var_dump(empty(' ')); // false
Unless you trim,
var_dump(empty(trim(' '))); // true
Error Reporting
If it isn't done so already, enable error_reporting,
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

Will the code in finally be run if I have program flow like this?

I was wondering if the following program flow will prevent the finally from being run in this try-catch-finally block due to a return in the try.
Please excuse poor error checking and sanitisation, this is just a mock:
function doLogin() {
$dbh = new PDO('mysql:host=localhost;dbname=test', "root", "");
$errors = array();
$loginSuccess = false;
try {
$query = $dbh->prepare('SELECT *
FROM users
WHERE username = :username');
$query->bindParam(':username', $_POST['username'], PDO::PARAM_STR);
$result = $query->fetch(PDO::FETCH_ASSOC);
if (!password_verify($_POST['password'], $result['password'])) {
array_push($errors, 'Invalid password.');
return; // will this return prevent the finally from being run?
}
else {
$loginSuccess = true;
}
}
catch (PDOException $pdoEx) {
echo 'Error occurred ' . $pdoEx->getMessage();
}
finally {
$dbh = null;
}
}
Code is pretty poorly written, but hopefully you understand my point.
The answer is yes, the code in finally will be run.
For example:
function example() {
try {
return true;
}
catch(Exception $e){
echo "error";
}
finally{
return false;
}
}
var_dump( example() );
Outputs:
bool(false)
It's also (hiddenly) stated in the docs:
In PHP 5.5 and later, a finally block may also be specified after the
catch blocks. Code within the finally block will always be executed
after the try and catch blocks, regardless of whether an exception has
been thrown, and before normal execution resumes.
To my understanding the try block finishes with the return statement. The normal execution is "paused" and the finally executed.

PHP - sem_get undefined runnin on linux CentOs

I'm having this error
Call to undefined function sem_get()
It is running on PHP Version 5.3.27, Apache/2.2.15 and CentOS.
I can't find a reason for this, also we have a testing server with (almost) the same setup and it is working fine (maybe different PHP extensions because we use this server with other projects too).
The test that I am running is the following:
<pre>
starts
<?
try {
echo "instance\n";
$mutex = new Mutex(633);
echo "Acquire \n";
$mutex->Acquire();
echo "\n\n Atomic magic \n\n";
echo "release \n";
$mutex->Release();
echo "null \n";
$mutex = null;
echo "end \n";
}
catch (Exception $e)
{
echo $e;
echo "\n<hr>\n";
var_dump(error_get_last());
}
And the class Mutex is the following:
<?php
class Mutex
{
protected $_Id;
protected $_SemId;
protected $_IsAcquired = false;
/**
* #param int $id Identifier of the Mutex, must be a number
*/
function __construct($id)
{
if (!is_int($id))
{
throw new Exception('The Mutex identifier must be a number');
}
$this->_Id = $id;
if (!($this->_SemId = sem_get($this->_Id, 1)))
{
throw new Exception('Error getting semaphore');
}
}
public function Acquire()
{
if (!sem_acquire($this->_SemId))
{
throw new Exception('Error acquiring semaphore');
}
$this->_IsAcquired = true;
}
public function Release()
{
if (!$this->_IsAcquired)
{
return;
}
if (!sem_release($this->_SemId))
{
throw new Exception('Error releasing semaphore');
}
$this->_IsAcquired = false;
}
}
?>
Thanks

Break from try/catch block

Is this possible in PHP?
try {
$obj = new Clas();
if ($obj->foo) {
// how to exit from this try block?
}
// do other stuff here
} catch(Exception $e) {
}
I know I can put the other stuff between {}, but that increases indenting on a bigger code block and I don't like it :P
With a goto of course!
try {
$obj = new Clas();
if ($obj->foo) {
goto break_free_of_try;
}
// do other stuff here
} catch(Exception $e) {
}
break_free_of_try:
Well, there is no reason for that, but you can have fun forcing an exception in your try block, stopping execution of your function.
try {
if ($you_dont_like_something){
throw new Exception();
//No code will be executed after the exception has been thrown.
}
} catch (Exception $e){
echo "Something went wrong";
}
I also faced this situation, and like you, didn't want countless if/else if/else if/else statements as it makes the code less readable.
I ended up extending the Exception class with my own. The example class below was for validation problems that when triggered would produce a less severe 'log notice'
class ValidationEx extends Exception
{
public function __construct($message, $code = 0, Exception $previous = null)
{
parent::__construct($message, $code, $previous);
}
public function __toString()
{
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
}
In my main code I call it;
throw new ValidationEx('You maniac!');
Then at the end of the Try statement I have
catch(ValidationEx $e) { echo $e->getMessage(); }
catch(Exception $e){ echo $e->getMessage(); }
Happy for comments and criticisms, we're all here to learn!
try
{
$object = new Something();
if ($object->value)
{
// do stuff
}
else
{
// do other stuff
}
}
catch (Exception $e)
{
// handle exceptions
}
Couldn't you just do like this?
try{
$obj = new Clas();
if(!$obj->foo){
// do other stuff here
}
}catch(Exception $e){
}
In php 5.3+ the nice thing about using exceptions with a try catch block, is that you can make your own Exceptions and handle them how and when you want. See: Extending Exceptions
class AcceptedException extends \Exception
{
//...
}
You can then catch specific exceptions or use if ($e instanceof AcceptedException) within your catch \Exception block to determine how you want to handle the exception(s).
Handled Example: http://ideone.com/ggz8fu
Unhandled Example: http://ideone.com/luPQel
try {
$obj = (object) array('foo' => 'bar');
if ($obj->foo) {
throw new \AcceptedException;
}
} catch (\AcceptedException $e) {
var_dump('I was accepted');
} catch (\Exception $e) {
if ($e instanceof \InvalidArgumentException) {
throw $e; //don't handle the exception
}
}
This makes your code much more readable and easier to troubleshoot as opposed to a lot of alternative solutions.
Personally I like to exit try/catch statements by using a
throw new MyException("optional message", MyException::ERROR_SUCCESS);
which I obviously catch by using:
switch($e->getCode()) {
/** other cases make sense here */
case MyException::ERROR_SQL:
logThis("A SQL error occurred. Details: " . $e->getMessage());
break;
case MyException::ERROR_SUCCESS:
logThis("Completed with success. Details: " . $e->getMessage());
break;
case MyException::ERROR_UNDEFINED:
default:
logThis("Undefined error. Details: " . $e->getMessage());
break;
}
This is the way I'd do that :
<?php
echo 'this' . PHP_EOL;
switch(true) {
default:
try {
echo 'is' . PHP_EOL;
break;
echo 'not' . PHP_EOL;
} catch (Exception $e) {
// error_log($e->getMessage());
}
}
echo 'fun !';
:-)

PHP5 SOAP : how to keep an instance?

I'm playing around with SOAP and PHP. But I can't figure it out why the returned object seems not to keep the instance. Let me show you first the example code and then I will explain:
client.php :
$client = new SoapClient("http://myhost/remote.wsdl");
try {
if($client->login("root","toor")) {
echo $client->getTotal()."\n";
}
} catch (SoapFault $exception) {
echo $exception;
}
server.php :
class Remote {
private $auth = false;
public function login($user, $pass) {
if($user == "root" && $pass == "toor") {
$this->auth = true;
return true;
} else throw new SoapFault("Server","Access Denied to '$user'.");
}
public function getTotal() {
if($this->auth) {
return rand(1000,9999);
} else throw new SoapFault("Server","Error: Not Authorized.");
}
}
$server = new SoapServer("remote.wsdl");
$server->setClass("Remote");
$server->handle();
I'm able to "login" so the returned value from $client->login is true.
But, when I call $client->getTotal, $this->auth is false (and thus the error is raised).
What do I need to do in order to keep the value I set previously?
Thank you in advance...
Ok! the solution was here:
http://www.php.net/manual/en/soapserver.setpersistence.php
This is the result:
session_start(); //Important
$server = new SoapServer("remote.wsdl");
$server->setClass("Remote");
$server->setPersistence(SOAP_PERSISTENCE_SESSION);
$server->handle();
And that's it!

Categories