knightly

Blog Archives

Abbywinters.com is hiring!

If you’re looking for a new challenging and exiting Senior Webdeveloper position. Don’t look any further. If you already think you have the job of your dreams. Think again!

abbywinters.com (NSFW) is one of the largest and most ethical, highly rated, well designed, and successful erotic websites in the world today. abbywinters.com is the WINNER of the AVN 2011 Awards for Best Membership site!

And we are looking to hire a new talented webdeveloper to expand our small team. What would you think about joining our small Agile team of highly qualified professionals?

You will be creating sexy, exiting and game changing experiences for the web, work for one of the industry leaders. And just be part of an awesome company. Some of the jobs key elements are:

  • Implementing development projects
  • Leading informal mentoring during day-to-day work
  • Contribute to design of development projects
  • Track, reduce, and prevent technical debt in Web Development projects


Motivated by principles of social responsibility, we deliver provocative media by embracing imagination, creativity and emerging technologies. Our models, customers and business partners are inspired by our fervid passion.


Our experienced staff use state-of-the-art content production facilities to produce 10 shoots a week from concept to finished art, utilizing the most advanced digital capture, post production and delivery systems in the world.


You will be working directly with our Web Dev Manager, Lead developer and colleagues in the web dev team. We need each individual to contribute for us to continue as a pioneer in our industry.


If you posses a “Can do” attitude. Would like to work in the center of Amsterdam. And are able to identify your self in the criteria below. You might want to head over to our career portal for a more detailed description.

Technical competencies – Required

  • High level of skill with PHP 5
  • High level of skill with Object Oriented Programming
  • High level of skill with HTML/CSS
  • High level of skill with JavaScript
  • High level of skill with Internet Applications
  • Moderate level of skill with Unit Testing and Test Driven Design
  • Moderate level of skill with MySQL
  • Moderate level of skill with Windows XP operating system
  • Experience with the GNU/Linux operating system
  • Competent with Revision Control systems (Subversion)
  • Bachelor of Science in Computer Science, or equivalent experience
  • Zend Certified Engineer, or equivalent experience
  • At least 5 years experience in Web Application Development


Technical competencies – Desired

  • Moderate level of skill with the Apache HTTP server
  • Good understanding of the Model-View-Controller pattern
  • Good understanding of the ActiveRecord Object-Relational-Mapping pattern
  • Familiarity with Agile software development practices (Scrum)
  • E-commerce
  • Agile development experience

Jquery unrecognized expression error

While doing some front end work yesterday. I got trapped by a jQuery issue. Well not JQuery specific. The issue was actually triggered by some other hand crafted code. Every time i would click a link inside my grid view firebug would throw an error.

uncaught exception: Syntax error, unrecognized expression: .

And the markup that triggered the error was


Nothing wrong there right? And it actually took my quite some time to figure this one out. It would be nice to have a tool that can tell you there are multiple click events assigned to a element? But for now it was just some manual searching and testing.

The issue was caused by an other snippet of Javascript code inside another .js file. This piece of code attached a click event to every div inside a grid td. Which may be a bit to greedy.

$('.admin .gridbg tr td span').click(function() {

And my link was in a nested td inside the grid. And also contained a span tag. So it was actually firing off two click events. From which one failed. Fixing it after that was easy. Either make the first click binding less greedy. Or change the markup of my second grid. I choose the last one.


Jquery & PHP doing simple image slicing

Today i was in need of a basic image slicer. An there must be a million of these things out there. But i wanted to see how hard / easy it would be to create this myself.

Conclusion. It’s not that hard when using the jquery library. which is becoming my Javascript framework of choice.



I started with a div.

Then i added the placeholder for the to be scaled image. And a div that will represent the slicer borders.

The next thing to do is setup the scaling canvas. So let’s make it draggable and resizeable.

// Create a draggable / scalable slicer
       $(function() {
            $('#image_slicer')
            .draggable({containment:'#image_slicer_canvas'}) // constraint
            .resizable();

            // set the slicer canvas size
            resizeCanvas(
            	$('#image_slicer_image').width(),
            	$('#image_slicer_image').height()
            );
       });

The only thing we need now is a bit of javascript to handle the slice action. I used a sample form to do the posting to the slicer.php script

// handle slicer actions
       $('#image_slicer').resizable({
   	      stop: function(event, ui) {
   	          var pos = $('#image_slicer').position();
   	          // width, height, left, top
   	          $('#scaler_width').val($('#image_slicer').width());
      	      $('#scaler_height').val($('#image_slicer').height());
        	  $('#scaler_left').val(pos.left);
        	  $('#scaler_top').val(pos.top);
   	      }
       });

The result is a nice red dotted line (square) on top of the image. The dotted area is draggable and resizeable.
When the right slice is selected just hit the slice button and PHP/GD will do the rest.

$width  = $_POST['width'];
$height = $_POST['height'];
$left   = $_POST['left'];
$top    = $_POST['top'];

// read source image
$src = imagecreatefromjpeg('images/sample.jpg');
$dest = imagecreatetruecolor($width, $height);

imagecopy($dest, $src, 0, 0, $left, $top, $width, $height);

header('Content-Type: image/jpeg');
imagegif($dest);

imagedestroy($dest);
imagedestroy($src);

That’s all. All files can be downloaded here

Drag & drop Uploads with XMLHttpRequest2 and PHP Revised

A while back i wrote a post where i explained how to implement the new XMLHttpRequest2 object. The main point of the post was to use sendAsBinary() so we can stream file uploads from the client to the server.

The post i made showed some code snippets to make this possible. And the Javascript part is all fine and dandy. But last week i had an interesting mail conversation with Jean-Pierre Vincent about the memory consumption on the server side of things.

The result of some testing revealed the server would need at least the amount of memory equal to the file size. For small files this is no problem. But with bigger files this becomes a problem. Although i couldn’t reproduce Jean-Pierre’s results. I wasn’t very happy with the test results.

Upload 2.8 MB file results in 3.1 MB memory usage
Upload 29 MB file results in 30 MB memory usage

A bit more testing revealed that file_put_contents() was the culprit. Which seems logical if you think about it. It reads the file into memory and dumps it again. Not very elegant for big files. Besides we are trying to stream files. So why should we read them completely in to memory? We shouldn’t :)

Jean-Pierre decided to go with the DataForm object to solve the issue. I still want to look into that. But have not found any information about. Besides that i knew the problem was on the server side. So i rewrote the receive() method to be less memory intensive. The results are considerably better then before.

Upload 2.8 MB file results in 0.4 MB memory usage
Upload 29 MB file results in 0.4 MB memory usage

The memory usage was measured with memory_get_peak_usage(). And the new code is posted below:

public function receive()
{
    if (!$this->isValid()) {
        throw new Exception('No file uploaded!');
    }

    $fileReader = fopen('php://input', "r");
    $fileWriter = fopen($this->_destination . $this->_fileName, "w+");

    while(true) {
        $buffer = fgets($fileReader, 4096);
        if (strlen($buffer) == 0) {
            fclose($fileReader);
            fclose($fileWriter);
            return true;
        }

        fwrite($fileWriter, $buffer);
    }

    return false;
}

Drag & drop Uploads with XMLHttpRequest2 and PHP

I finally had some time to read through my ever growing list must read items and play with some new software. While reading up on the new Firefox 3.6 i noticed it came with the new XMLHttpRequest [2] object based on the new file API. And according to the new specs. This would allow for easy file uploads. Now there’s been some examples [2] on the web already. But i just wanted to get my hands dirty.

The new XMLHttpRequest object makes is possible to send files in a few different formats. The most important being the binary format. The code for sending a request with XMLHttpRequest2 looks the same as the previous version. Except for sendAsBinary() in this case.

var xhr = new XMLHttpRequest();

fileUpload = xhr.upload,
fileUpload.onload = function() {
    console.log("Sent!");
}

xhr.open("POST", "upload.php", true);
xhr.sendAsBinary(file.getAsBinary());

So let’s set things up for drag & drop. We need a div that will be the main drop point. And we need some event listeners to catch the drag * drop events. Let start by creating the drop zone. For this we use two simple divs. The outer div will listen for the drag & drop events. And the inner will catch the files.

Now let’s create our upload code.

var upload = {
    setup : function() {},
    uploadFiles : function() {event}
}
window.addEventListener("load", upload.setup, false);

The setup method will set all event listeners for drag & drop. And register the upload handler.

var container = document.getElementById('container');
var drop = document.getElementById('drop');

container.addEventListener("dragenter", function(event) {
        drop.innerHTML = '';
        event.stopPropagation();
        event.preventDefault();
    },
    false
);

container.addEventListener("dragover", function(event) {
        event.stopPropagation();
	event.preventDefault();
    },
    false
);

container.addEventListener("drop", upload.uploadFiles, false);

As you could see above. the uploadFiles() method gets a event returned from the drag & drop action. This is where the new file APi comes in play. To get to the file property we access the dataTransfer object.

var files = event.dataTransfer.files;

The actual uploading is easy as cake.

for (var x = 0; x < files.length; x++) {

    var file = files.item(x);
    var xhr = new XMLHttpRequest();

     fileUpload = xhr.upload,
     fileUpload.onload = function() {
         console.log("Sent!");
    }

    xhr.open("POST", "upload.php", true);

    xhr.setRequestHeader("Cache-Control", "no-cache");
    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    xhr.setRequestHeader("X-File-Name", file.fileName);
    xhr.setRequestHeader("X-File-Size", file.fileSize);
    xhr.setRequestHeader("Content-Type", "multipart/form-data");

    xhr.sendAsBinary(file.getAsBinary());
}

That's it for the client side. There is however a small problem on the receiving side. When handling uploaded files in PHP we expect the $_FILES array to be populated. This is not the case when streaming files from the client to the server. To get the needed file information we set some headers on the client side X-File-Name and X-File-Size. And since the $_FILES are is empty. We need an other way to get the file contents. So we will use php://input streams for that.

The contents of upload.php look like this:

require_once('Streamer.php');

$ft = new File_Streamer();
$ft->setDestination('data/');
$ft->receive();

With setDestination() the destination path for the uploaded files is set. And recieve() listens for any incoming files. Most of the magic is done in the recieve() method. So here's the code.

public function receive()
{
    if (!$this->isValid()) {
        throw new Exception('No file uploaded!');
    }

    file_put_contents(
        $this->_destination . $this->_fileName,
        file_get_contents("php://input")
    );

    return true;
}

I am impressed! This promises a lot of good. And offers some interesting options. Let's hope all browsers implement this gem. I still have one issue though. I can't get this to work in firefox under linux. The drag & drop events do not seem to function properly with files being dragged from the desktop. anybody know why?

If you interested in the complete code. you can find it here

**Small update**
http://lenss.nl/2010/09/drag-drop-uploads-with-xmlhttprequest2-and-php-revised/

0x.vc URL shortener service

Having a hard time getting to sleep tonight. And was browsing my domain list. when i realized i still have this very short domain name that is just sitting there collecting dust. And since these URl shortener services are so hot lately i decided to roll my own.

So three hours, a bit of code and a short domain name later i present : 0x.vc (it’s shorter) It’s probably still full of holes and prone to XSS attacks. So be careful!

The URL shortening service is offline!

XSS vulnerability on Dutch bank websites

My wife just send me a link to security.nl. Pointing to an article about XSS vulnerability in Dutch banking websites. And since i am from the Netherlands. I thought to check this out a bit.

security.nl states that a “security researcher” found XSS bugs in most of Dutch websites. With a link that seems to point to the “researchers” blog. I don’t know about you. But i personally don’t trust websites that i never seen before. Let alone “researchers” that have absolutely no credibility in the scene. However the XSS bugs are real. But is this really something to write about? Showing an alert box on a screen shot seems very lame to me. I wonder if this is even exploitable at all?

One good point is that at least one bank responded in time and fixed the bug.

Animated loader on form submit

In one of our sites we load content of a third party travel organization. And some of these calls can take some time. But when the pages are loading nothing really happens to the browser state. This is confusing for the users of the website. So i decided to add some animated preloader images. Just to show the users the site is still doing stuff.

This however confronted me with a small problem. The preloader images are supposed to show up when a form is submitted. And this is exactly what’s causing the problem. In my first attempt i created the image object when the form was submitted. On submit a JavaScript function was called. This function created the image object and displayed it.

function loader() {
	var loaderImg = new Image();
        loaderImg.src = 'some/image/url/';
}

This however resulted in an image displayed that had no active animation. This happens i think because the image is not fully loaded when the user hits submit on the form. So to fix this i had to load the images before the page was completely rendered.

var loaderImg = new Image();

window.onload = function() {
        loaderImg.src = 'some/image/url';
}