Accessing backend system…

We're sorry, but your session has expired due to inactivity. Please use your browser to refresh this page and log in to our system again.

Message goes here.

Message goes here.

Message goes here.

LOGIN / REGISTER
VIEW BASKET
SEARCH:
 
php|architect logo
 
SERVICES
  • MAGAZINE
  • PHP|TEK 2012
  • CODEWORKS 2011/12 TOUR
  • BOOKS
  • TRAINING
  • ADVERTISE
 
CHANNELS
  • NEWS
  • PODCAST
  • DEVELOPMENT
  • OPINION
  • WRITE

Creating RRD graphs in PHP

Posted by Joshua Thijssen on February 23, 2011
IN News ·Uncategorized
Tags: php · rrd
 

Related Posts:

  • php|tek’s Call for Papers is Closing Soon
  • Finding Exactly Where You Are
  • Geolocation: Easier Than It Looks
  • Building the Backside – Part 1
  • Mobile Dashboards Made Easy – Part 2

RRDTool LogoYou may not be familiar with the term RRD graph, but if I show you one, you probably recognize them instantaneously. They are used to plot all kind of data against time in a very easy way which is why they are used a lot in all kind of applications. Even though many consider RRD as a library to create graphs, it is actually more than that: it’s a complete system to store aggregated data in a very efficient way.

What is RRD?

RRD stands for Round Robin Database. It is a database for collecting all kinds of data against time. The “round robin” stands for the fact that only a certain amount of “data points” can be stored. When we reach the end of the database, it will wrap back to the begin again. This  means that RRD database files will never grow in size.

Every RRD works with a “step rate”, which tells us how far the data points are located from each other. Normally this is 300 seconds (5 minutes) so all data is stored in a 5 minute interval. This doesn’t mean you only can add data every 5 minutes though. You can add as much data into the RRD and at any time you like. The RRD will combine this data into a data point. If you have a default step rate of 5 minutes but you add some data every minute to your RRD, it will average these 5 values into 1 data point. As you can image, RRD’s are not really for storing actual data, but just for graphical and statistical usages.

Getting the extension

Before we can do something useful with RRD, we need to install the RRD extension. If you are running on CentOS you are in luck. The RPMForge repository provides a php5-rrdtool package which you can install with “yum install php5-rrdtool”. On a Debian or Ubuntu system there is no default package but it’s very easy to build from the source.

If you cannot build the extension or you cannot find anything working, no fear. You can still use the command line version of RRDTool to try all examples.

Our RRD example

The best way to get acquainted with RRD is to actually create one. Suppose you want to display some statistics of users that have logged into our web-application and we want to see the number of failures that have occurred, for instance, when a user has entered a wrong password. We want to view this data in a daily graph, a weekly graph, a monthly graph and maybe a yearly graph as well.

Creating our database file

As said, RRDtool is more or less a “database” so we much define some kind of “schema”. In order to do this, we can use the “rrd_create” function (or the “rrdtool create” command line version). There are two different things we need to configure: the data sources and the round robin archives. The data sources tells you what to store whereas the round robin archives tells you how to store it.

Setting up data sources

The data sources describe the actual data we want to store. In our case we want to store 2 kind of data points: the number of succeeded log-ins, and the number of failed log-ins. We call them “success” and “failed” respectively. These data sources are “ABSOLUTE” types, which means the data is reset after every point collection. There are other types, depending on the type of data you want to store.

Furthermore, we need to specify a “heartbeat”. This means that when no data source is recorded in this amount of time, RRD will consider the data point as “unknown” (which is something different than 0!).

The last 2 items we have to specify is the lower and upper boundary of the data source. If we would have data source that is given in percentages (for instance, your server’s used disk space in percentage), we could specify an lower limit of 0, and an upper limit of 100. Since we deal with log-in attempts, we can only specify the lower boundaries. We set the upper boundary to ‘U’ (unknown).

Setting up the RRA

Now that we know WHAT to store, we must tell RRD how to store the data. As said, data is stored in a cyclic (round robin) way so we must define the amount of room we want to use. We want to have 4 different graphs: daily, weekly, monthly and yearly. This however does not mean we need to have 4 RRA’s. RRD can decide which RRA’s it will use to graph data.

Each RRA is defined in the following format:

RRA:cf:xff:steps:rows

The “cf” stands for “consolidation function” and can be either AVERAGE, LAST, MIN, MAX. It defines how the data points get aggregated. AVERAGE will average the points, LAST will store the last point, MIN will store the lowest point found and MAX the highest. The xff should be set to 0.5, and “steps” decide how many points get consolidated, “rows” is the amount of points it will store eventually.

I’ve decided to create 3 RRA’s: one stores the single 5-minute samples for a period of 1 day (12 points per hour times 24 hours = 288 points), one stores 1 hour samples (12 points) for 1 week (24 * 7 points) and one stores 1 day (288 points) samples for a year (365 points).

Off course, we could have stored each 5-minute point for a period of 1 year, but we would have to store 12 * 24 * 365 = 105120 points! By storing in a consolidated way, we have an efficient way of storing the data while we still maintain enough information for plotting our graphs.

<?php

$options = array(
 "--step", "300",            // Use a step-size of 5 minutes
 "--start", "-6 months",     // this rrd started 6 months ago
 "DS:success:ABSOLUTE:600:0:U",
 "DS:failure:ABSOLUTE:600:0:U",
 "RRA:AVERAGE:0.5:1:288",
 "RRA:AVERAGE:0.5:12:168",
 "RRA:AVERAGE:0.5:228:365",
 );

$ret = rrd_create("login.rrd", $options, count($options));
if (! $ret) {
 echo "<b>Creation error: </b>".rrd_error()."\n";
}

?>

Updating your data

RRD must collect data on fixed intervals. We should have a separate system like a cronjob that collects the amount of data and updates the RRD accordingly. If we don’t update on time (as specified by the heartbeat), we get unknown points (which causes empty spots in our graphs later on). The next snippet will “simulate” login successes and failures ranging back from 180 days ago until now:

<?php
  // Fetch current time
  $now = time();

  // Simulate last 180 days of login, with a step of 5 minutes
  for ($t=$now - (3600 * 24 * 180); $t<=$now; $t+=300) {
    $success = rand(0, 10);
    $failure = rand(0, 5);
    $ret = rrd_update("login.rrd", "$t:$success:$failure");
  }
?>

Graphing

Now we have arrived at the coolest part of RRD: the graphing of the data. I create 4 basic graphs. Each graph shows the successful attempts in green, and on top I’ve specified the failed attempts. There are many different ways of graphing the data (as lines, different shades, surfaces etc) and almost every aspect of the graph is customizable.

<?php

create_graph("login-hour.gif", "-1h", "Hourly login attempts");
create_graph("login-day.gif", "-1d", "Daily login attempts");
create_graph("login-week.gif", "-1w", "Weekly login attempts");
create_graph("login-month.gif", "-1m", "Monthly login attempts");
create_graph("login-year.gif", "-1y", "Yearly login attempts");

echo "<table>";
echo "<tr><td>";
echo "<img src='login-day.gif' alt='Generated RRD image'>";
echo "</td><td>";
echo "<img src='login-week.gif' alt='Generated RRD image'>";
echo "</td></tr>";
echo "<tr><td>";
echo "<img src='login-month.gif' alt='Generated RRD image'>";
echo "</td><td>";
echo "<img src='login-year.gif' alt='Generated RRD image'>";
echo "</td></tr>";
echo "</table>";
exit;

function create_graph($output, $start, $title) {
  $options = array(
    "--slope-mode",
    "--start", $start,
    "--title=$title",
    "--vertical-label=User login attempts",
    "--lower=0",
    "DEF:success=login.rrd:success:AVERAGE",
    "DEF:failure=login.rrd:failure:AVERAGE",
    "CDEF:tsuccess=success,300,*",
    "CDEF:tfailure=failure,300,*",
    "AREA:tsuccess#00FF00:Successful attempts",
    "STACK:tfailure#FF0000:Failed attempts",
    "COMMENT:\\n",
    "GPRINT:tsuccess:AVERAGE:successful attempts %6.2lf",
    "COMMENT: ",
    "GPRINT:tfailure:AVERAGE:failure attempts %6.2lf",
  );

  $ret = rrd_graph($output, $options, count($options));
  if (! $ret) {
    echo "<b>Graph error: </b>".rrd_error()."\n";
  }
}

?>

Our result should be something like this:

Screenshot of RRD graphs

Conclusion

RRDtool is a really great to generate graphs in a simple way, but don’t get fooled by it’s apparent simplicity. It’s capable of creating very complex graphs if needed. We just scraped the basics which is more than enough to get you started in your own graphs. Unfortunately, the PHP  binding of RRDTool are not really well maintained, but since they are merely a shell around the command line version, they work properly enough to create cool graphs.

More information about RRD and the RRDTool can be found on the main RRD website: http://www.mrtg.org/rrdtool/index.en.html


About the author—Joshua Thijssen is a senior software engineer at Enrise and owner of the privately held company NoxLogic. His programming skills includes (but is not limited to) assembly, C, C++, Java, Perl, Python and PHP and has experience on administering a wide range of operating systems. One of his specialties is fine tuning MySQL databases and queries. His personal blog can be found on http://www.adayinthelifeof.nl
 
 
 

Function Contest

Posted by Beth Tucker Long on February 17, 2011
IN News
Tags: contest · functions · php
 

Related Posts:

  • FTW! Contest Deadline is May 17th
  • Code Jam 2010 Open for Registration
  • php|tek’s Call for Papers is Closing Soon
  • Finding Exactly Where You Are
  • Geolocation: Easier Than It Looks

First Place Blue RibbonCustom PHP functions can solve problems, save you time and now, they can even get you free stuff! How is this possible you may ask? The Westhost PHP Contest! Submit your favorite function, and you could win a System76 laptop, Zend Studio 8.0, or an awesome php|architect book! We’ve even thrown in some classic php|architect t-shirts for the winners as well. So, head on over to the Westhost PHP Contest website and submit your entry by March 15th. There is a 2KB limit, but other than that, there are no restrictions on the functions you can submit. You can even submit functions that are written for a specific library or framework, just let them know that in the description field when you submit your function.

Winners will be judged based on utility, creativity, efficiency, and readability as well as public rating.

Don’t have a function to submit, but still want to participate? Don’t worry, everyone can participate. Visit the Westhost PHP Contest website, and rate the functions that have already been submitted. You can help your favorite function catapult into the lead!


About the author—Elizabeth Tucker Long is the Editor-In-Chief of php|architect magazine as well as a trainer and occasional guest blogger for php|architect. She also runs Treeline Design - http://www.treelinedesign.com, a web development company, and Playlist Event Music - http://www.playlisteventmusic.com, a DJ company, along with her husband, Chris, and son, Liam.
 
 
 

Day Camp 4 Developers #2: Telecommuting

Posted by Cal Evans on February 16, 2011
IN Conference
Tags: Cal Evans · day camp 4 developers · event · on-line
 

Related Posts:

  • CodeWorks 2010 Slides
  • The CodeWorks 2010 early-bird extended to October 4th
  • Friday Webcast "Care and feeding of remote developers"
  • Ten Top PHP people to follow on Twitter
  • Hey Look! Cal Evans is Coming to CodeWorks!

The next Day Camp 4 Developers is just around the corner and I want to hijack php|architect for just a moment to let you know what we have in store.

Day Camp 4 Developers #2: Telecommuting is a 1 day, technology agnostic, on-line conference dedicated to helping developers learn the tools and techniques needed to participate in or manage a distributed team.

We have 5 great speakers and 5 great talks all teaching practical advice that developers need.

Day Camp 4 Developers was created because so many good topics didn’t make it into conferences. Good talks, good topics but because they don’t deal with hard skills. This isn’t a failing of the conferences, they have to pick a wide variety topics that are of interest to a large number of people. Because DC4D is on-line, we don’t have nearly the expenses, so we can afford to tackle a single topic and do so in-depth.

For a complete lineup and all the information you need, visit the website daycamp4developers.com. We how to see you there.

When: Saturday, March 5th, 2011
Where: Online (gotomeeting.com)
How much: $35
Website: daycamp4developers.com


About the author—Cal Evans is a veteran of the browser wars. (BW-I, the big one) He has been programming for more years than he likes to remember but for the past [redacted] years he's been working strictly with PHP, MySQL and their friends. Cal regularly speaks at PHP users groups and conferences, writes articles and wanders the net looking for trouble to cause. He blogs on an "as he feels like it" basis at Postcards from my life.
 
 
 

Check it out, tek 11 schedule is up!

Posted by Cal Evans on February 14, 2011
IN Conference
Tags: community · Conference · php · tek11
 

Related Posts:

  • phpDay 2010
  • php|tek’s Call for Papers is Closing Soon
  • php|architect Announces the First Annual Impact Awards
  • Open source life style
  • PHP tours Europe in fall

All of us here at php|architect have been working like monkeys (some more like monkeys than others) to get all the details of the tek11 schedule on-line. We are happy to say that everything is now on-line and in place. Now only do we have the schedule page up but now all the author pictures and biographies are up along with complete descriptions of the talks.

tek11 will continue the five year tradition of the PHP community gathering in Chicago to share ideas and inspiration. Last year, a great time was had by all and this year will be no different. Get your ticket today and make sure you are there in May!


About the author—Cal Evans is a veteran of the browser wars. (BW-I, the big one) He has been programming for more years than he likes to remember but for the past [redacted] years he's been working strictly with PHP, MySQL and their friends. Cal regularly speaks at PHP users groups and conferences, writes articles and wanders the net looking for trouble to cause. He blogs on an "as he feels like it" basis at Postcards from my life.
 
 
 

PHP in the Cloud – New Options for Application Hosting

Posted by Joel Clermont on February 7, 2011
IN News
Tags: cloud computing · hosting · PaaS
 

Related Posts:

  • First look at Orchestra.io
  • Google releases skipfish

PHP LogoPHP developers today have a few tried and true ways to publish their applications: shared hosting, virtual private servers or dedicated servers. Each of these options bring a variety of trade-offs, such as price, reliability, ease of use, level of control and amount of expertise required. Perhaps you work at a company where you have people dedicated to the vital task of deployment or perhaps you have to wear the deployment hat in addition to the developer hat. If you’re anything like me, you may love writing code and tests, but groan at the prospects of compiling Apache or getting a database cluster configured.

Enter the newcomer to the world of PHP deployment options: Platform as a Service (PaaS). You may be rolling your eyes at the introduction of yet another buzzword and acronym, but before you dismiss it, consider how it might fit in to your application hosting strategy. I’ve heard Platform as a Service described as a “layer above the cloud,” that is, it builds on the existing cloud infrastructure, like Amazon’s EC2, but abstracts away all the setup and maintenance tasks of running an entire server. As David Coallier described it to me, the goal is to “deploy apps, not servers.”

In addition, the goal of Platform as a Service is to make your application environment scalable, reliable and affordable. If your site gets extremely popular in a short period of time, the infrastructure is already there to dynamically allocate more resources to keep your site running at acceptable levels of performance. When the popularity dies down, the environment scales back automatically as well and, best of all, you only pay for the resources you need.

Services like this have existed for some time in the Ruby world, but now we have two new providers offering Platform as a Service for PHP applications. The first is PHPFog. While currently in private beta, I got access to the service and have had a couple weeks to play around with it in preparation for a presentation at the Milwaukee PHP Users Group this month. PHPFog meets all the goals I described above, but didn’t stop there. For one, they provide a git repo for you to publish to when you want to deploy. Deploying your application to their environment is as sample as “git push”. They also provide post-deploy hooks for additional customization. Another interesting feature is that they provide a library of application templates for such projects as WordPress, Drupal, Joomla and even frameworks like Zend Framework, CakePHP and Kohana. You’re not limited to these options, however, so you can deploy any type of project or code that you would like. These templates simply provide an easy way to jump start a project on their end.

Another new option for PHP Platform as a Service hosting is Orchestra. Built by the talented team at echolibre, Orchestra was just announced on the first of this month and is not yet in a private beta. I reached out to the team though and got a walkthrough via Skype from David Coallier. It shares a lot of functionality with PHPFog, but they also have provided some unique functionality that is quite useful. For example, while they also offer git deployment, instead of providing you a new repo to push to, they hook in to your existing public or private repo and automatically pull from it. It is customizable though, so don’t worry that you might accidentally deploy code not ready for prime time. They monitor the specific branch in your repo that you use for production-ready code. If you prefer to deploy from SVN or manually over SSH, they make that available as well. Orchestra also allows you to add features to your hosting environment. Perhaps you want to talk use a specific type of database, you want to make memcache available to your application or you want to integrate with an automated browser-testing solution like SauceLabs; those will be available as “add-ons.”

Platform as a service may not make sense for every site or application, but it’s certainly a welcome addition to the PHP ecosystem. If you’re interested in learning more, I encourage you to visit each site and sign up for early access and more information.


About the author—Joel Clermont is a programmer by day, and often by night. While PHP is his first love, he also regularly works with .NET and the iPhone. He is a founding partner of Orion Group, a Milwaukee web development firm, and also organizes the Milwaukee PHP user group.
 
 
 

Oh now, did we sneak iPods and iPads in our new training promo?

Posted by Marco Tabini on February 1, 2011
IN News ·training
Tags: courses · credits · discounts · iPad · ipod · training
 

Related Posts:

  • Today only: Half off all training!
  • Flash Builder 4 training for PHP developers
  • php|a now accessible from your iPad!
  • New Classes! New Prices!

It’s time to officially kick off our 2011 training season with a bunch of new classes and a great new promo. Plus, we’re reintroducing our credit system which allows you to save even more and get some nice special swag in the process.

Did we say new classes?

Oh, yes, we did. We’re launching three new classes this quarter and are getting ready to introduce even more brand new courses through the rest of 2011; we’re also continuing to revise all our existing courses to ensure that they are up-to-date and on par with the most recent developments.

Right now, we’re introducing these new courses:

  • Essential MySQL provides a thorough introduction to good database programming practices, with a focus on MySQL. Learn how to properly design, query and optimize your databases—a perfect companion to our Essential PHP class.
  • Professional Zend Framework picks up where our Essential Zend Framework leaves off, with a slew of great information on the more advanced aspects of Zend Framework. A must if you want to take ZF to the next level.
  • Professional Flex and PHP Development extends our very popular Essential Flex course for even more great knowledge on building RIAs using Adobe’s popular platform.

Discounts? We got discounts!

We are also reintroducing our popular credit system, with a much simplified structure and better pricing. You can buy credits in blocks of 1, 2, 6 or 10 for a maximum discount of 25 percent over our regular training rates. Credits are good for one year and can be transferred to other users—a perfect way to make our training a painless, fun and very useful perk for all the members of your team and save a bunch in the process.

For the first time, we are also introducing an unlimited training option. This package allows a user to take as many courses as he or she likes during the year. The only limitation is that the pass is non-transferable, non-refundable and the user cannot sign up for two courses that take place simultaneously.

And now, for those iPods and iPads…

We feel so good about our 2011 training program that we’ve decided to bring our popular iPod promotion back. Except, we’re throwing some iPads into the mix, too.

The promotion is simple enough: buy two, six or ten credits, and we’ll put an iPod nano, a 32GB iPod touch or 2 32GB iPod touch in the mail for you. Get the unlimited package, and you will soon be enjoying a brand-new 32GB Wi-Fi + 3G iPad.

Head on over to our redesigned training page for more information, rules and conditions… and maybe grab some credits for yourself today!


About the author—Marco is the keeper of keys and Chief Garbage Collector at Blue Parabola, php|architect's parent company. He can be found on Twitter as @mtabini.
 
 
 

This month's issue

January 2012
Buy · $5 — Subscribe · starts at $35
 

 

Upcoming Training Courses

Course Start Date
Essential PHP 2012-02-03
AJAX Programming with PHP and … 2012-02-10
Essential Zend Framework 2012-02-17
Mobile HTML5, JavaScript and P… 2012-03-02
Professional PHP Development 2012-03-09
 

About us

  • What we do
  • Contact us
  • Write for us

Policies & legal

  • Customer support
  • Privacy policy
  • Refund policy
  • Terms & Conditions

Online Store

  • Magazine
  • Training courses
  • Books

Special sections

  • Codeworks 2011
 

Copyright © 2002-2012 Blue Parabola, L.L.C. — All amounts in USD - WP3