Rob AllenSlim-Csrf with Slim 3 (25.8.2015, 06:18 UTC)

In addition to the core Slim framework, we also ship a number of add-ons that are useful for specific types of problems. One of these is Slim-Csrf which provides CSRF protection.

This is middleware that sets a token in the session for every request that you can then set as an hidden input field on a form. When the form is submitted, the middleware checks that the value in the form field matches the value stored in the session. If they match, then the all is okay, but if they don't then an error is raised.

For the simplest use case, you need start the session and add the middleware:

$app->add(new Slim\Csrf\Guard());

Then, from within a given route callable, you can create your form and add two hidden fields: one for the token's name and one for its value:

$app->get('/', function ($request, $response, $args) {
    // CSRF token name and value
    $name = $request->getAttribute('csrf_name');
    $value = $request->getAttribute('csrf_value');

    // Render a form
    $html = <<<EOT
<!DOCTYPE html>
<head><title>CSRF test</title></head>
    <form method="POST" action="/process">
        <input type="hidden" name="csrf_name" value="$name">
        <input type="hidden" name="csrf_value" value="$value">
        <input type="text" name="name" placeholder="Name">
        <input type="submit" value="Go">

    return $response->write($html);

If you run this in a browser and view the source, you'll see something like this:

Slim csrf view source

Refresh and you see different values for the csrf_name and csrf_value fields, which means that the user can have multiple tabs open and submit without any issues.

For testing, I created a simple route callable:

$app->post('/process', function ($request, $response, $args) {
    return $response->write("Passed CSRF check.");

Pressing form's submit button will result in the display of "Passed CSRF check.". If you then refresh and confirm the post, you'll see "Failed CSRF check!" and the HTTP status code will be 400.

Customising the CSRF failure

It's likely that you'll want to customise the CSRF failure display as a plaint text error message isn't very user friendly! To change this, supply a callable to the Guard class which has the same signature as middleware: `
function($request, $response, $next). The middleware must return a Response.

This allows you to supply a custom error page:

$guard = new Slim\Csrf\Guard();
$guard->setFailureCallable(function ($request, $response, $next) {
    return $response->write(<<<EOT
<!DOCTYPE html>
<head><title>CSRF test</title></head>
    <p>An error occurred with your form submission.
       Please start again.</p>

As the failure callable has the middleware signature, you can also set a flag into $request and then deal with the CSRF failure later. The failure callable would look something like this:

$guard->setFailureCallable(function ($request, $response, $next) {
    $request = $request->withAttribute("csrf_result", 'FAILED');
    return $next($request, $response);

Now, your route callable can decide what to do:

$app->post('/process', function ($request, $response, $args) {
    if (false === $request->getAttribute('csrf_result')) {
        // Deal with error here and update $response as appropriate
    } else {
        // successfully passed CSRF check
        $response->write("Passed CSRF check.");
    return $response;

This is very powerful and remarkably easy to set up.


The flexibility of the failure callable allows you to handle a CSRF validation failure in the most appropriate way for your application and is a very powerful feature of this middleware.

As it's PSR-7 compliant, you can use the middleware independently of Slim with any PSR-7 middleware dispatch system that uses the middleware signature of function($request, $response, $next) where a Response is returned.

Cal EvansInterview with Josh Butts (25.8.2015, 05:00 UTC) Link
PHP ClassesThe Benefits of Using Git in Your Software Projects Part 2: Collaboration, Web Platforms and Migration (25.8.2015, 04:06 UTC)
By Nicola Pietroluongo
Nowadays working with a version control application like Git is mandatory for all software developers, even those that work alone in private projects that are not going to be published anywhere.

In the first part of this article we covered the basic benefits of working it explaining some of the most commonly used features, some very well known, others not so much.

Read this part the article to learn how use Git in projects the involve collaboration between multiple developers, how to take advantage of existing Web platforms that support Git, and how to migrate from older version control applications like SubVersion.
David SklarFixing Broken UTF-8 (25.8.2015, 04:00 UTC)

When working on the i18n bits of Learning PHP 7, I had a problem. My example showing how plain string functions such as strtolower() and strtoupper() mangle multibyte UTF-8 characters was making the book formatting/rendering pipeline barf. The processing tools are expecing nicely formatted, valid, UTF-8 encoded HTMLBook files. It didn’t like the mangled invalid UTF-8 characters in my example output.

To fix this, I wrote the following function to replace invalid UTF-8 sequences with the Unicode Replacement Character (U+FFFD):

<script src="">

Now I can keep the real invalid byte sequences in my raw book source code (which makes my automatic “does the output of this code example match what it’s supposed to?” checker happy) but end up with a nice (constructed from three valid bytes) in the formatted output.

SitePoint PHPWatch: Fundamental PHP Arrays and Array Functions in PHP (24.8.2015, 17:30 UTC)

In this screencast I'll walk you through 5 useful functions PHP provides to manipulate and extract data from arrays.

<script src="">

Loading the player...

<script type="text/javascript"> jwplayer("video-5697").setup({ image: "", sources: [ { file: "", label: "SD" }, { file: "", label: "HD" }, ], tracks: [ { file: "", "default": true } ], aspectratio: "16:9", width: "100%", height: "480px", fallback: true, primary: "flash", streaming: false, analytics: { enabled: false, cookies: false }, captions: { back: false, fontsize: 12 }, advertising: { client: "googima", schedule: { "myAds": { "offset": "pre", "tag": "\u0026iu=/7448792/Video\u0026cust_params=[post_id]%3Dstaging%26channel%3D[channel]\u0026impl=s\u0026gdfp_req=1\u0026env=vp\u0026output=xml_vast2\u0026unviewed_position_start=1\u0026url=[url]/\u0026description_url=[description_url]\u0026correlator=[timestamp]" } } } });

Continue reading %Watch: Fundamental PHP Arrays and Array Functions in PHP%

SitePoint PHPRe-introducing PDO – the Right Way to Access Databases in PHP (24.8.2015, 16:00 UTC)

PDO is the acronym of PHP Data Objects. As the name implies, this extension gives you the ability to interact with your database through objects.

Stock graphic of database icon branching into other icons

Why not mysql and mysqli?

The very valid question people ask when confronted by a new technology is simply, why should they upgrade? What does this new technology give them that is worth the effort of going through their entire application and converting everything to this new library, extension, or whatever?

It’s a very valid concern. We’ve written about this to some degree before, but let’s go through why we think it’s worth it to upgrade.

PDO is object-oriented

Let’s face it: PHP is rapidly growing, and it is moving toward becoming a better programming language. Usually, when this happens in a dynamic language, the language increases its strictness in order to allow programmers to write enterprise applications with peace of mind.

In case of PHP, better PHP means object-oriented PHP. This means the more you get to use objects, the better you can test your code, write reusable components, and, usually, increase your salary.

Using PDO is the first step in making the database layer of your application object-oriented and reusable. As you will see in the rest of this article, writing object-oriented code with PDO is much simpler than you may think.


Imagine that you have written a killer application using MySQL at your current workplace. All of a sudden, someone up the chain decides that you must migrate your application to use Postgres. What are you going to do?

You have to do a lot of messy replaces, like converting mysql_connect or mysqli_connect to pg_connect, not to mention all the other functions you used for running queries and fetching results. If you were using PDO, it would be very simple. Just a few parameters in the main configuration file would need changing, and you’d be done.

It allows parameter binding

Parameter binding is a feature that allows you to replace placeholders in your query with the value of a variable. It means:

  • You don’t have to know, at runtime, how many placeholders you will have.
  • Your application will be much safer against SQL injection.

You can fetch data into objects

People who have used ORMs like Doctrine know the value of being able to represent data in your tables with objects. If you would like to have this feature, but don’t want to learn an ORM, or don’t want to integrate it into an already existing application, PDO will allow you to fetch the data in your table into an object.

The mysql extension is no longer supported!

Yes, the mysql extension is finally removed from PHP 7. That means if you’re going to use PHP 7, you need to change all those functions to mysqli_* instead of mysql_*. This is a great time to just upgrade straight to PDO because of how much it helps you in writing maintainable, portable code with much less effort.

I hope the reasons above have convinced you to start integrating PDO into your application. Don’t worry about setting it up; you may already have it on your system!

Continue reading %Re-introducing PDO – the Right Way to Access Databases in PHP%

Anna FilinaConFoo Call for Papers is Open (24.8.2015, 10:39 UTC)

confooConFoo is once more seeking passionate speakers for the upcoming conference.

The event is happening in Montreal, Canada, between February 24th and 26th, 2016. It is an exciting conference for web developers with speakers from all over the world. It unites many web programming languages under one roof, as well as other topics related to web development. The call for papers closes on September 20th.

ConFoo renews 50% of its speakers each year. If you’re new to this conference, you should definitely submit.

If you would just like to attend, there is a discount until October 13th.

PHP ClassesSentiment Analysis in PHP Part 1: Introduction to the Problem and a Solution (24.8.2015, 07:38 UTC)
By Samuel Adeshina
With growth of people that go on the Internet to express their opinions about brands and other matters, Sentiment Analysis tools are becoming increasingly important to help companies and individuals to react in a timely manner to incidents that affect their business and reputation.

Fortunately we already have the Machine Learning technology necessary to implement sentiment analysis even using pure PHP code.

Read this article to learn more about how you can implement your own sentiment analysis tools in your PHP own applications.
Thijs FerynThe ElasticSearch cat APIs (23.8.2015, 18:29 UTC)
I like ElasticSearch, it’s a great piece of open source technology. Although it was built as a Lucene based search
Davey ShafikGuzzleHttp VCR (22.8.2015, 22:30 UTC)

A few days ago I pushed out a very small library to help with testing APIs using Guzzle: dshafik/guzzlehttp-vcr.

<script async src="//" charset="utf-8">

This is a simple middleware that records a request’s response the first time it’s made in a test, and then replays it in response to requests in subsequent runs.

It does this by returning a Guzzle \GuzzleHttp\HandlerStack with either the \Dshafik\GuzzleHttp\VCRHandler middleware, or the GuzzleHttp\Handler\MockHandler added. The first will record the responses to JSON files, while the latter will be pre-loaded with those responses and will return them when requests are made.

It’s important to understand that the responses are returned in order regardless of whether it is the same request being made.

The purpose of this library is to just make it easier to create and update your tests for API clients.

Usage is simple, just call Dshafik\GuzzleHttp\VCRHandler::turnOn() passing in the storage location before running the test, and pass in the handler as a guzzle client option:

View this code snippet on GitHub.

You can pass in the handler when instantiating the \GuzzleHttp\Client, or when making the individual requests — if you use the same instance for the individual requests it will re-use the same JSON file for storage, otherwise if you pass in unique instances (with unique storage files) it will create individual ones. I recommend passing in the handler to the constructor, but ensuring that you use a new instance (of the middleware, and the client) for each test.

View this code snippet on GitHub.

Hopefully folks find this useful, do let me know if you do. If you have issues, please report them and pull requests are welcome!

I’ll be releasing a new Akamai library which uses dshafik/guzzlehttp-vcr next week (probably) so look out for that if you want to see it’s use in a real project.

LinksRSS 0.92   RDF 1.
Atom Feed   100% Popoon
PHP5 powered   PEAR
ButtonsPlanet PHP   Planet PHP
Planet PHP