Archive for the ‘Programming’ category

Minimal server online status checker (HTML/JavaScript)

07/02/2012

Starbuck, noooooo!

Above is an example of a nifty server status script I have been using in a recent project.

Here is the base code for monitoring a web server:

<img src="http://site-to-check.com/online.png" alt="status" onerror="this.src='files/offline.png'" />

The setup is:

  • An online icon (online.png) on the remote server you want to see the status of.
  • An offline icon (offline.png) on the server that is going to show the status page.

If the image on the remote server fails to load, the onerror event is triggered and the javascript rewrites the image tag to show the offline image. You can use relative or absolute paths for the offline image. This snippet is fully compatible with all major browsers, including Internet Explorer down to version 5.5!

Demo
Click here for a demo.

Resources
Below are the images I use, found on Clker, an excellent online clipart resource.

Online
Offline

Participate
If you find this useful or have any suggestions for improving it, feel free to write in the comments!

Collect visitor stats using any image with the Piwik Tracking API

10/11/2011

Piwik is an open source web analytics system in PHP and a great alternative to Google Analytics.

It offers simplified tracking via an image tracking code:

<!-- Piwik Image Tracker -->
<img src="http://example.org/piwik/piwik.php?idsite=1&rec=1" style="border:0" alt="" />
<!-- End Piwik -->

In some scenarios, you might not want to expose that you are using Piwik analytics, or would like to avoid loading unnecessary resources.

Let’s use the Piwik Tracking API to turn any image into a tracker. This is useful for websites, newsletter stats and email signatures alike.

Prequisites

You need to have a Piwik install running with administrative access. Apache is required to get a “nice” image url.

Step 1 – Setup Piwik

Create a new website in Piwik, which will contain your stats for the image. Make note of the new site ID (Visible in Settings > Websites)

Create a new user and give that user admin rights to the website. Make note of the token_auth for that user. (Under Settings > Users)

Step 2 – Get the PiwikTracker.php Tracking API

You can obtain this file by going to the following URL (Replace example.org with your piwik install path)

http://example.org/piwik/index.php?module=SitesManager&action=downloadPiwikTracker&idSite=$IDSITE&piwikUrl=http://example.org/piwik/

You can also find a copy of the file here.

Step 3 – Build the tracking code
Pick an image you’d like to use, name it stats.png and put it in a folder on your web server. I am going to use this “thumbs up” clipart. Also put PiwikTracker.php in this folder.

Now, create the file stats_t.php. (Base code below) Change line 3 and 4  to your own site id and the token_auth of the user you created in step 2. Also set your Piwik URL at line 10. If you want to distinguish between multiple tracking images, you can change line 22 to have a different message. That means you can track any number of images using one site in Piwik.

<?php
    //Set the id of your piwik site here
    $idSite = 1;
    $token_auth = 'your user token here';

    //Load Piwik Tracker
    require_once 'PiwikTracker.php';

    //Set the URL path to your Piwik Installation
    $t = new PiwikTracker($idSite,'http://example.org/piwik');

    //Auth to allow for more API functions
    $t->setTokenAuth($token_auth);

    //Set correct IP (Should be users, not the web server issuing the request)
    $t->setIp($_SERVER['REMOTE_ADDR']);

    //Set referrer (if applicable)
    if(isset($_SERVER['HTTP_REFERER']))
       $t->setUrl($_SERVER['HTTP_REFERER']);

    $t->doTrackPageView('Image viewed');

    $im = imagecreatefrompng("stats.png");

    //For transparency (Alpha blending)
    imagealphablending($im, true);
    imagesavealpha($im, true);

    //Set header
    header('Content-Type: image/png');
    //Output image
    imagepng($im);
    //Unload image
    imagedestroy($im);
?>

You can set many more visitor details, refer to the reference.

Create a .htaccess file in the same folder. We will use this to rewrite the URL so that we can still use a .png extension for the file. When stats_t.png is called, Apache will instead load stats_t.php , which will run the tracking code.

RewriteEngine On
RewriteRule stats_t.png stats_t.php

Your folder structure should now look like this:

Verify that your image is displayed properly in a web browser by navigating to stats_t.png

Verify that Piwik recorded the visit correctly. If it did not, make sure you have entered $token_auth and $idSite correctly.

Step 4 – Display your new tracking image anywhere

Now you can include your image anywhere, like this:

<img src="http://khromov.se/email2/stats_t.png" alt="thumbs up" />

If you would like more information please see the official documentation of the Tracking API.

Let me know if this helped you out or if you have any suggestions or improvements!

Update: Now includes referrer tracking. If the image is used on a page, you will see what page it is used on. (See line 19 and 20 of stats_t.php)

PHP function for obfuscating e-mail addresses and phone numbers using Javascript.

04/10/2011

Update 2012-12-23

The technique below is now available as a WordPress plugin. Check out the Email Obfuscate Shortcode plugin!

Here’s a short snippet that I have been using in various PHP projects to protect e-mail addresses and phone numbers against being harvested for spam purposes. It uses Javascript to scramble some text and output it as a self-contained piece of Javascript. It’s compatible with all major browsers (and IE5.5 and up). The idea is based on this ruby snippet, so head over there if you want to read more about the way it works!

safe_text() snippet

function safe_text($text)
{
    if(mb_detect_encoding($text, 'UTF-8', true))
        $text = utf8_decode($text);

    $ret = '
<script type="text/javascript">// <![CDATA[
                    var t=[
                ';
    $chars = str_split($text);

    $enc[] = rand(0,255);

    foreach($chars as $char)
    {
        $enc[] = ord($char)-$enc[sizeof($enc)-1];
    }

    $ret .= join(',',$enc);
    $ret .= '
                ]; for (var i=1; i<t.length; i++) { document.write(String.fromCharCode(t[i]+t[i-1])); }
// ]]></script>';

    return $ret;
}

To output the Javascript anywhere (it’s entirely self-contained), simply run:

echo safe_text('bob@examplecorp.com');

Update: Thanks to Fredrik for a fix that makes this function multibyte safe! It now also works with special characters like å,ä,ö and similar.

15 web design resources that will save you time and improve your designs!

25/03/2010

I have been doing quite a lot of creative work recently in the domain of web design (get it, “domain”, har har!) , and I’d be happy to share some of the great web sites and applications that have helped me make better and cleaner design and code jobs. I have divided the sites into six categories, so take your pick and dig in!

If you have any suggestions of your own, I’d be happy to hear them, leave a comment and be heard!

Cliparts and photos

image 

Sxc.hu – Royalty free photography
Sxc.hu, or stock.xchng, is the little brother of  iStockphoto. They offer royalty-free photography for non-commercial use, and an option to contact the authors for use in commercial application using a very relaxed license. My experience with the people there has been great as a whole, highly recommended and great array of photographs, but also clip art.

image 

clker.com – public domain clip art
Clker.com offers public-domain clip art uploaded by users. Great site for any smaller images that you might need, such as bullets and icons.

Compatibility

image

Common font list
When designing a page, you need to make sure you use a font that is visible to and looks visually similar for every viewer, and degrade gracefully in the cases where the font is not present on the viewers computer. This useful webpage displays common font families that work over a wide array of browsers and operating systems.

Inspiration

image

BrowserShots
BrowserShots has lost its glory days as the go-to site for making sure your web pages look equal across all browsers due to its increasingly long rendering waiting time and restrictions, and with IETester mentioned below, you can verify that your page runs properly on all major browsers.

But BrowserShots has introduced a fantastic gallery of web designs, and this is a place where you can find great inspiration.

image

ColorSchemer gallery and ColourLovers palette gallery
Finding the correct colors for your site can be a surprisingly difficult challenge, but when browsing these galleries, this becomes a fun experience. The idea is that you pick a scheme, which contains roughly 3-8 colors, and then try to base your design around these. If you try it, you’ll find a surprisingly clean and beautiful site looking back at you when you are finished. Using schemes with multiple variation of the same color (like this one) has worked the best for me.

image

Web Design From Scratch
A great resource for articles about the philosophy behind, and practical application to modern web design.

Applications/Add-ons

image

Sizer
Sizer is a small application which allows you to easily resize your browser (or really, any) window to see your web pages (hopefully) degrade in a graceful manner. Simple and easy, yet invaluable.

image

Firebug (Firefox add-on)
Firebug is a great web developer tool built as a Firefox add-on. I have barely scraped the surface of this great tool, but it has been very helpful so far.

image 

IETester
Your web design and CSS looks great in the latest versions of Firefox, Chrome, Opera and IE? You’re not done yet! Unfortunately, a large portion of people still use Internet Explorer 7 and 6 (*shudders*) and this tool will help you make sure your design stays true to its form. (although it probably won’t until you spend an hour trying to figure out why IE6/7 doesn’t handle inline block  properly, which brings us to…)

Fixes and hacks for common problems
  image

Google
This might seem like an odd choice at first, but if you’ve ever had a problem, googling will almost always lead to an answer. The great thing about the internet is that chances are great that somewhere, someone has had your exact problem and either asked about it in a forum or given a solution in a blog post, which will usually lead you closer to an answer.

image 

IE PNG Fix
It is fairly common knowledge that Internet Explorer 6 and below does not handle the alpha channel (transparency) for PNG images properly and displays the whole transparent area as a gray box. Resorting to GIF is possible for single-colored background, but for patterned backgrounds your only choice is PNG and this fix (Which is mostly done in CSS) will take care of that.

A quick note: I have noticed that the JavaScript used for tiling images in “IE PNG Fix”, which is called “iepngfix_tilebg.js” seems to break the dropdown functionality of Superfish, which I mentioned earlier. I have been looking at the problem, but haven’t been able to identify the culprit, although I suspect it is related to the way the JS places the image. Unless you absolutely need tiling support, it’s best not to use the JS code, so beware!

image
CSS Sticky Footer
Making a footer that always stays at the bottom of the page, moves with JavaScript and  works over all major browsers is a surprisingly difficult task, but CSS Sticky Footer takes care of it. It requires you to import a fairly large CSS file, but it shouldn’t break your layout too much, aside from a margin that needs fixing here and there.

Coding
 image

CodeIgniter PHP Framework
CodeIgniter is a great framework for easily making web applications in PHP. The features I have enjoyed so far is the fantastic database handling using Active Record, the interesting Model-View-Controller approach (which was new to me) and the great performance I get from my applications. If you want to know what the hype is about, check out this video tutorial entitled “Create a blog in 20 minutes”!

image

Suckerfish JavaScript/CSS menu system
Another thing that seems like there should be a myriad of online, but is surprisingly difficult to find is a menu that works over all browsers, is completely free, simple to use and can be used in commercial applications. Look no further, Suckerfish is what you have been waiting for! And it degrades nicely to CSS-only under environments without JS too!

Bored? Try my hellish Image Maze web game!

21/09/2009

imagemaze_level1The beginning…

Level-based/hacker web games have been around for a long time now. The usual premise is that you land on a page using your browser, and with the help of the information on this page are supposed to reach the “next level”, ie. the next page, with yet another mystery, and so on. This is accomplished by either manipulating the URL through the hints you have received, or inputting a password in a form on the page.

I’ve always thought it was a great concept and have played quite a few of them in my days. (Although I’m having a real time finding them right now, maybe I’m using the wrong search terms – if you remember any of these classics, feel free to post the link to them in the comment section!)

But you’re not here for them, no you’re in for my very own Image Maze. So head on over to
http://fs.shrtl.com/imagemaze/ and you’ll soon notice that you have been bumped to
http://fs.shrtl.com/imagemaze/first – “first” being the level name, and your task is to find the next level, for example, if you were to guess that the next level is called “brownie”, you simply go to http://fs.shrtl.com/imagemaze/brownie/ and check it out. Now you’re on your own!

The game contains six levels, which quickly go from very simple to sucker hard, each level has a very vague hint on what to do to find the next level name, and features some of the photos I’ve taken over the years. Once you’ve finished all of the levels you’ll get a unique code, post it in the comment section if you want to brag about your accomplishment! 🙂

I’ve assembled a bunch of hints if you get stuck, but don’t peek unless you’re absolutely lost – because just like Hint Coins in Professor Layton, it ruins the experience! In order to view the hints, simply mark the text in the black boxes below.

Hints:
Level 1 – What kind of extra information does an image carry when used in HTML?
Level 2 – Now would probably be a great time to check out the HTML code!
Level 3 – Woah, that’s quite a big image – but why?!
Level 4 – What usually causes an image to now be shown?
Level 5 – Your browser won’t help you solve this one, there’s a secret inside the image.
Level 6 – This one is kind of like the last one, only the other way around.

In other news…
ticketbastard

Small logo improvement suggestion to account for actual company policy.

The oddball, unstable queue  and booking system employed by Swedish event ticket seller Ticnet stinks. The fact that they have pretty much a monopoly on any larger event doesn’t make things better. I guess I’ll just have to enjoy my Rammstein concert sitting down… in the back… Blargh.