Monthly Archives: October 2011

Talk about node.js and WebSockets

Last friday I spoke about node.js and Websockets with the people of The Mêlée. The talk was an introduction to node.js and focused in the new HTML5 feature: the WebSockets.

When I spoke about Websockets I also introduced the great library socket.io. The jQuery of WebSockets.

Working with Request objects in PHP

Normally when we work with web applications we need to handle Request objects. Requests are the input of our applications. According to the golden rule of security:

Filter Input-Escape Output

We cannot use $_GET and $_POST superglobals. OK we can use then but we shouldn’t use them. Normally web frameworks do this work for us, but not all is a framework.

Recently I have worked in a small project without any framework. In this case I also need to handle Request objects. Because of that I have built this small library. Let me show it.

Basically the idea is the following one. I want to filter my inputs, and I don’t want to remember the whole name of every input variables. I want to define the Request object once and use it everywhere. Imagine a small application with a simple input called param1. The URL will be:

test1.php?param1=11212

and we want to build this simple script:

echo "param1: " . $_GET['param1'] . '<p/>';

The problem with this script is that we aren’t filtering input. And we also need to remember the parameter name is param1. If we need to use param1 parameter in another place we need to remember its name is param1 and not Param1 or para1. It can be obvious but it’s easy to make mistakes.

My proposal is the following one. I create a simple PHP class called Request1 extending RequestObject object:

Example 1: simple example

class Request1 extends RequestObject
{
    public $param1;
}

Now if we create an instance of Request1, we can use the following code:

$request = new Request1();
echo "param1: " . $request->param1 . '<p/>';

I’m not going to explain the magic now, but with this simple script we will filter the input to the default type (string) and we will get the following outcomes:


test1.php?param1=11212
param1: 11212

test1.php?param1=hi
param1: hi

Maybe is hard to explain with words but with examples it’s more easy to show you what I want:

Example 2: data types and default values

class Request2 extends RequestObject
{
    /**
     * @cast string
     */
    public $param1;
    /**
     * @cast string
     * @default default value
     */
    public $param2;
}

$request = new Request2();

echo "param1: <br/>";
var_dump($request->param1);
echo "<br/>";

echo "param2: <br/>";
var_dump($request->param2);
echo "<br/>";

Now we are will filter param1 parameter to string and param2 to string to but we will assign a default variable to the parameter if we don’t have a user input.


test2.php?param1=hi&param2=1

param1: string(2) "hi"
param2: string(1) "1"

test2.php?param1=1&param2=hi

param1: string(1) "1"
param2: string(2) "hi"

test2.php?param1=1
param1: string(1) "1"
param2: string(13) "default value"

Example 3: validadors

class Request3 extends RequestObject
{
    /** @cast string */
    public $param1;
    /** @cast integer */
    public $param2;

    protected function validate_param1(&$value)
    {
        $value = strrev($value);
    }
    
    protected function validate_param2($value)
    {
        if ($value == 1) {
            return false;
        }
    }
}
try {
    $request = new Request3();

    echo "param1: <br/>";
    var_dump($request->param1);
    echo "<br/>";

    echo "param2: <br/>";
    var_dump($request->param2);
    echo "<br/>";
} catch (RequestObjectException $e) {
    echo $e->getMessage();
    echo "<br/>";
    var_dump($e->getValidationErrors());
}

Now a complex example. param1 is a string and param2 is an integer, but we also will validate them. We will alter the param1 value (a simple strrev) and we also will raise an exception if param2 is equal to 1


test3.php?param2=2&param1=hi
param1: string(2) "ih"
param2: int(2)

test3.php?param1=hola&param2=1
Validation error
array(1) { ["param2"]=> array(1) { ["value"]=> int(1) } }

Example 4: Dynamic validations

class Request4 extends RequestObject
{
    /** @cast string */
    public $param1;
    /** @cast integer */
    public $param2;
}

$request = new Request4(false); // disables perform validation on contructor
                               // it means it will not raise any validation exception
$request->appendValidateTo('param2', function($value) {
        if ($value == 1) {
            return false;
        }
    });

try {
    $request->validateAll(); // now we perform the validation

    echo "param1: <br/>";
    var_dump($request->param1);
    echo "<br/>";

    echo "param2: <br/>";
    var_dump($request->param2);
    echo "<br/>";
} catch (RequestObjectException $e) {
    echo $e->getMessage();
    echo "<br/>";
    var_dump($e->getValidationErrors());
}

More complex example. Param1 will be cast as string and param2 as integer again, same validation to param2 (exception if value equals to 1), but now validation rule won’t be set in the definition of the class. We will append dynamically after the instantiation of the class.


test4.php?param1=hi&param2=2
param1: string(4) "hi"
param2: int(2)

test4.php?param1=hola&param2=1
Validation error
array(1) { ["param2"]=> array(1) { ["value"]=> int(1) } }

Example 5: Arrays and default params

class Request5 extends RequestObject
{
    /** @cast arrayString */
    public $param1;

    /** @cast integer */
    public $param2;

    /**
     * @cast arrayString
     * @defaultArray "hello", "world"
     */
    public $param3;

    protected function validate_param2(&$value)
    {
        $value++;
    }
}

$request = new Request5();

echo "<p>param1: </p>";
var_dump($request->param1);

echo "<p>param2: </p>";
var_dump($request->param2);

echo "<p>param3: </p>";
var_dump($request->param3);

Now a simple example but input parameters allow arrays and default values.


test5.php?param1[]=1&param1[]=2&param2[]=hi
param1: array(2) { [0]=> int(1) [1]=> int(2) }
param2: int(1)
param3: array(2) { [0]=> string(5) "hello" [1]=> string(5) "world" }

test5.php?param1[]=1&param1[]=2&param2=2
param1: array(2) { [0]=> string(1) "1" [1]=> string(1) "2" }
param2: int(3)
param3: array(2) { [0]=> string(5) "hello" [1]=> string(5) "world" }

RequestObject

The idea of RequestObject class is very simple. When we create an instance of the class (in the constructor) we filter the input request (GET or POST depending on REQUEST_METHOD) with filter_var_array and filter_var functions according to the rules defined as annotations in the RequestObject class. Then we populate the member variables of the class with the filtered input. Now we can use to the member variables, and auto-completion will work perfectly with our favourite IDE with the parameter name. OK. I now. I violate encapsulation principle allowing to access directly to the public member variables. But IMHO the final result is more clear than creating an accessor here. But if it creeps someone out, we would discuss another solution :).

Full code here on github

What do you think?

Display errors on screen even with display errors = off with PHP

Last month I was in a coding kata session playing with StingCalculator, and between iteration and iteration we were taking about the problems of shared hostings. Shared hosting are cheap, but normally they don’t allow us the use some kind of features. For example we cannot see the error log. That’s a problem when we need to see what happens within our application. Normally I work with my own servers, and I have got full access to error logs. But if we cannot see the error log and the server is configured with display errors = off in php.ini (typical configuration in shared hosting), we have a problem.

One of my post came to my mind “Real time monitoring PHP applications with websockets and node.js”. Basically we can solve the problem using this technique, but if we are speaking about shared hosting without error log access, it’s very probably that we cannot install a node.js server or even use sockets functions. So it’s not “Real” solution to our problem.

The idea is create a variation of the original script (one kind of script’s Spin-off ;)). In this scprit we will capture errors and exceptions and show them in script at the end of the script. We don’t have access to the error log but we will show it in the browser.

Imagine the following script:

$a = 1/0;
throw new Exception("myException");
echo "hi";

It will show one warning (1/0) and one exception (myException)

  • Warning: Division by zero
  • Fatal error: Uncaught exception ‘Exception’ with message ‘myException’

If we change php.ini show errors = off we will see a nice white screen.

The idea is add to the script:

include('ErrorSniffer.php');
ErrorSniffer::factory('127.0.0.1');

$a = 1/0;
throw new Exception("myException");
echo "hi";

Now with with ErrorSniffer library we will see a nice output, even with display errors = off.
I also add a IP in the class constructor to restrict the output message to one IP. The idea is to place this script at production, so we don’t want to expose error messages to whole users.

If we see the source code of ErrorSniffer class we a constructor like this:

    public function __construct($restingToIp)
    {
        if ($this->getip() == $restingToIp) {
            self::register_exceptionHandler($this);
            self::set_error_handler($this);
            self::register_shutdown_function($this);
        }
    }

    private static function set_error_handler(ErrorSniffer &$that)
    {
        set_error_handler(function ($errno, $errstr, $errfile, $errline) use (&$that) {
                $type = ErrorSniffer::getErrorName($errno);
                $that->registerError(array('type' => $type, 'message' => $errstr, 'file' => $errfile, 'line' => $errline));
                return false;
        });
    }

    private static function register_exceptionHandler(ErrorSniffer &$that)
    {
        set_exception_handler(function($exception) use (&$that) {
                $exceptionName = get_class($exception);
                $message = $exception->getMessage();
                $file  = $exception->getFile();
                $line  = $exception->getLine();
                $trace = $exception->getTrace();
    
                $that->registerError(array('type' => 'EXCEPTION', 'exception' => $exceptionName, 'message' => $message, 'file' => $file, 'line' => $line, 'trace' => $trace));
                return false;
        });
    }

    private static function register_shutdown_function(ErrorSniffer &$that)
    {
        register_shutdown_function(function() use (&$that) {
                $error = error_get_last();

                if ($error['type'] == E_ERROR) {
                    $type = ErrorSniffer::getErrorName($error['type']);
                    $that->registerError(array('type' => $type, 'message' => $error['message'], 'file' => $error['file'], 'line' => $error['line']));
                }

                $that->printErrors();
        });
    }

As we can see we will catch errors and exceptions, we populate the member variable $errors and we also use register_shutdown_function to show information on shutdown.

You can see the full script at github here.

What do you think?

Follow

Get every new post delivered to your Inbox.

Join 990 other followers