PHP5 SOAP : how to keep an instance? - php

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!

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);

how to generate 403 error code in symfony before filter

i'm trying to use the before filter of symfony 2.7 to do authentication. my event listener is as follows
class TokenListener {
protected $dm;
function __construct() {
}
public function setDocumentManager(DocumentManager $dm) {
$this->dm = $dm;
}
public function onKernelController(FilterControllerEvent $event) {
$controller = $event->getController();
if (!is_array($controller)) {
return;
}
if ($controller[0] instanceof TokenAuthenticatedController) {
$content = $event->getRequest()->getContent();
$json = json_decode($content,true);
$authId = $json['authId'];
$authToken = $json['authToken'];
echo "authId: {$authId}, authToken: {$authToken}\n";
$user = $this->dm->getRepository('HcUserBundle:User')
->createQueryBuilder()
->field('authId')->equals($authId)
->getQuery()
->getSingleResult();
if (!isset($user) || $user->getAuthToken() != $authToken) {
throw new AccessDeniedException('This action needs a valid token!');
}
}
}
}
but i got 500 error, and symfony error log says
Uncaught PHP Exception Symfony\Component\Security\Core\Exception\AccessDeniedException: "This action needs a valid token!"
instead of getting a 403 error, I also tried to use the AccessDeniedHttpException and have the same problem, does anyone know how to generate a 403 response here? Thanks
you can also just return a new response, setting the status code to Codes::HTTP_FORBIDDEN
return new Response("This action needs a valid token!", Codes::HTTP_FORBIDDEN);
EDIT: nope this might not work since your in a listener ...
EDIT: are you sure it produces a 500 in your prod env aswell, not just on app_dev
EDIT: it SHOULD work this way, in a listener :
$response = new RedirectResponse("someUri", Codes::HTTP_FORBIDDEN);
$event->setResponse($response);

Some try catch issue with 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();
}

accessing of different classes through includes

I have a problem with the accessing of classes.
index.php
include('includes/header.php');
include('includes/step1.php');
include('includes/footer.php');
header.php
session_start();
include('php/classes/Errorhandler.php');
include('php/classes/User.php');
$errorhandler = new Errorhandler();
$user = new User();
// Test
print_r($errorhandler->errors);
...html
Errorhandler.php
class Errorhandler {
public $errors = array();
...
}
User.php
class User {
public function __construct() {
if($this->grab_computerid()) {
if(!$this->grab_mandant()) {
$errorhandler->errors[] = "102: There was an error.";
}
if(!$this->grab_os()) {
$errorhandler->errors[] = "103: There was an error.";
}
} else {
$errorhandler->errors[] = "101: There was an error.";
}
}
private function grab_computerid() {
$sqlconnection = new SqlConnection();
$conn = $sqlconnection->db_connect();
if ($conn) {
$query = "SELECT Computer_Idn FROM " . DB_PC_TABLE . " WHERE DeviceName = ?";
$params = array($this->get_hostname());
if ($sqlconnection->query($query, $params)) {
$computer_id = $sqlconnection->fetchRow();
$this->set_computer_id($computer_id['Computer_Idn']);
return true;
echo "Test";
} else {
$errorhandler->errors[] = "Statement error occurred.";
}
} else {
$errorhandler->errors[] = "Can't connect to database.";
// test
print_r($errorhandler->errors);
}
$sqlconnection->db_disconnect();
}
}
The index.php includes the relevant sections to build the site. In header.php I create two objects (1. errorhandler, 2. user). The User class check the return (boolean) from the sqlconnection. I know, that I use the wrong password and get a false. So the if ($conn) prints the print_r($errorhandler->errors) correctly. But when I want to show the errors in step1.php, the array errors is empty.
step1.php
// show negative messages
if ($errorhandler->errors) {
foreach ($errorhandler->errors as $error) {
echo '<div class="alert alert-danger message"><strong>Error: </strong>' . $error . '</div>';
}
}
I tested it in header.php also and the errors array is empty too. So, the errors array is only filled in the User.php class, but I want to display the erros in step1.php. Is there a problem with the includes?
Edit:
Hope to make it clearer:
header.php
// load the class Errorhandler
require_once('php/classes/Errorhandler.php');
// load the class User
require_once('php/classes/User.php');
// create errorhandler object
$errorhandler = new Errorhandler();
// create user object
$user = new User();
print_r($errorhandler->errors);
I set an error in class User:
$errorhandler->errors[] = "Can't connect to database.";
The array $errorhandler->errors is empty in header.php.
You have to call a function. You cannot get value directly.
1st->$errorhandler = new Errorhandler();
2nd->Errorhandler.php
class Errorhandler {
function error() //create a function like this
{
$error= /*any error*/;
return $error;
}
}
3rd->
if ($err=$errorhandler->error()) {
foreach ($err as $error) {
echo '<div class="alert alert-danger message"><strong>Error:</strong>'.$error.'</div>';
}
}
Also try using require_once() instead of include();
Try using require_once instead of include. require_once will throw an error when something goes wrong and kill the script. These errors should appear in an error_log file in the same folder as the file which has the include in it. include will only issue a warning and let the script continue. I personally use require_once everywhere. Also, double check your include paths.
You should pass $errorhandler to User class.
Like this:
$user = new User($errorhandler);
And in User class:
class User {
protected $err;
public function __construct($errorhandler) {
$this->err = $errorhandler;
//rest of your code
}
//rest of your code
}
or simply add: global $errorhandler; inside User constructor.

zend db error on switching tables Catchable fatal error: Argument 1 passed to __construct() must be an array, object given, called in

In my application I have set up the db connection. Now i want to switch tables and i keep getting following error
Catchable fatal error: Argument 1 passed to Application_Model_PgeSeismicFile::__construct() must be an array, object given, called in /opt/eposdatatransfer/application/models/PgeSeismicFileMapper.php on line 58 and defined in /opt/eposdatatransfer/application/models/PgeSeismicFile.php on line 10
I have two models for the two tables. i get error when I try to access the second table. Accessing and setting the 1st table is fine and i do it the same way. Here is how I am switching the tables.
private $_dbTable = null;
public function setDbTable($dbTable, $path = false)
{
$project = $_REQUEST['username'];
$filename = $path . "PSDB.db"; //APPLICATION_PATH . "/data/db/".$project."/PSDB.db";
if (!file_exists($filename)) {
//$this->_redirect('/');
// need to redirect and pass eror message for user
throw new Exception("File does not exist");
}
try{
//exit("3");
$dbAdapter = Zend_Db::factory("pdo_sqlite", array("dbname"=> $filename));
}catch (Zend_Db_Adapter_Exception $e) {
// perhaps a failed login credential, or perhaps the RDBMS is not running
var_dump($e);
exit("1");
} catch (Zend_Exception $e) {
// perhaps factory() failed to load the specified Adapter class
var_dump($e);
exit("2");
}
if (is_string($dbTable)) {
print_r($dbAdapter);
$dbTable = new $dbTable($dbAdapter);
$dbTableRowset = $dbTable->find(1);
$user1 = $dbTableRowset->current();
//var_dump($user1);
//exit("hello");
//$row = $user1->findDependentRowset();
}
if (!$dbTable instanceof Zend_Db_Table_Abstract) {
throw new Exception('Invalid table data gateway provided');
}
$this->_dbTable = $dbTable;
//$session = new Zend_Session_Namespace();
//$session->dbAdapter = $this->_dbTable;
//var_dump($this);
//exit();
return $this;
}
public function getDbTable($path = false)
{
if (null === $this->_dbTable) {
$session = new Zend_Session_Namespace();
//$this->setDbTable('Application_Model_PgeSeismicFile',$path);
$this->dbTable = new Application_Model_PgeSeismicFile($session->dbAdapter);
}
return $this->_dbTable;
}
It errors on this line
$this->dbTable = new Application_Model_PgeSeismicFile($session->dbAdapter);
In my session i am storing:
$dbAdapter = Zend_Db::factory("pdo_sqlite", array("dbname"=> $filename));
try this
$dbAdapter = Zend_Db::factory("pdo_sqlite", array("dbname"=> $filename));
Zend_Db_Table::setDefaultAdapter($dbAdapter);
$this->dbTable = new Application_Model_PgeSeismicFile;

Categories