Archive for 'Development'

Creating a basic captcha with Imagick

I hate captcha systems, truly, madly, deeply. But spammers force us to create and use them.
Writing captcha systems can be very easy. You need a randomly generated image, a hard to read font, and finally basic server side coding knowledge. I use PHP cos it’s well documented and extremely easy to use, but you can use any other server side language you want. On which ImageMagick can be used of course.
So, let’s list what we want to do:

  • Create a random string
  • Display it as an image
  • Check whether the user entered the string correctly

That’s all.

Creating random string with PHP
This is the easiest. PHP already has a function which creates new random string each second. Yup, that’s the time() function. But the created string has only numbers. To fix that, we encrypt it with some sort of built-in encryption function. That can be md5, sha1, anything. I use md5 now cos that’s which popped in my mind on the first place.
The second thing we want to solve is to not make the user to enter 32 characters, but only 5. Again, PHP’s string manipulation knowledge comes handy, I use substr(). So let’s see our code:

$rand = md5(time());
$str = substr($rand, 0 , 5);

That simple. We now have a 5 characters long completely random string.
 

Pushing the random string in an image, using IMagick
 
If you followed my IMagick related posts, you should know that annotating an image with IMagick is simpler than confusing a snail with a mirror. The only difference is that now we’ll have in the image our random string, not a fixed variable’s value. Yeah, that’s dynamic image.
I’ll also use a hard to read font, because using DirectX even a 5-year-old can create a captcha reading software if we use a common font.
You may ask how will the server side code which checks whether the captcha is correct or not will know the user entered the correct code or not. That’s solved with sessions. We start our session in the image generator script, and set the shortened version of our random string in a session variable.
So, when the image is loaded in your HTML, the session variable will get the 5 character long random string as value. The session variable will be checked on the page which checks the user input, if matches the value which was entered by the user, we know it’s human. No, we hope it’s a human.
So, the code to generate the dynamic captcha image:

session_start();
$rand = md5(time());
$str = substr($rand, 0 , 5);
$_SESSION['captcha'] = $str;

$font = '/path/to/your/hard2read/font.ttf';

$image = new Imagick();
$draw = new ImagickDraw();
$pixel = new ImagickPixel( 'white' );
$image->newImage(100, 27, $pixel);
$draw->setFont($font);
$draw->setFontSize( 25 );
$draw->line( $x, $y, $x1, $y1 );
$image->annotateImage($draw, 10, 20, 0, $str);
$image->setImageFormat('png');
header('Content-type: image/png');
echo $image;
a captcha image created with IMagick

We save the above code as captcha.php and try to load it. If everything went well, we should see an image like the one on the left.
 
The HTML form for our captcha
 
If you can’t do this by your own, you shouldn’t mess with captcha verification. But just for the sake of the example:

captcha image

Now the server side script which checks the user input. I write something very basic, don’t validate or sanitize anything. When you write your own user input verifier code, you should validate every single bit of your users’ input, don’t trust em!

session_start();
/*Check if every field has been filled in*/
if (!empty($_POST['uname']) && !empty($_POST['upass']) && !empty($_POST['captcha'])){

/*Check if the CAPTCHA image value matches the user input*/
    if ($_SESSION['captcha'] != $_POST['captcha']){
        echo 'You failed the CAPTCHA verification. Try again.';
    }else{
         echo 'Congrats! Everything is cool!';
    }

}else{
echo 'You missed to fill in some fields. Try again.';
}

And we’re done.

To play with the example you can do it here.
To download the files which were created through this post, click here.

A social network’s UI - simple yet effective with JavaScript

Some website’s user interface (UI) can be a pain to use. That’s because some areas are hard to read, nonsense pages exist or simply there’s so much graphic on the site, the forms and texts are basically hidden from the eye.
OK. I elaborate a bit cos not even me understand what I meant.
For example, the login and registration pages. Usually there are 2 input fields on a login form, or at least 3 on registration forms; and webmasters dedicate full pages for these forms. I really think these pages’ existence is not needed at all and should be incorporated in a website’s structure.
Other thing is, the help pages. I encountered a lot of sites where when clicking those little question marks, I was sent to a dedicated page where there was one single, short sentence. For the cow’s sake, why? Wouldn’t be cooler to just have that sentence included in little bulb and which appears only when the user hovers over the question mark?

A social network has hundreds of thousands of visitors and I think these annoyances should be excluded from the site’s structure. How? Simple: with javascript.

So, first we set a goal: to push all the reg/login forms in one single page and display as much help content as possible using mouse controlled tool-tips.

First we had to decide whether we develop every javascript function from scratch or we better use a framework. The first option is time consuming and usually the result is not so cool as in the case of a framework. We rapidly decided we’ll use a framework. Now let’s decide which framework to use. There are some basic things which should be considered: the framework’s size, it’s functionality, it’s acceptance and finally whether is still developed or not.
As far as I considered JQuery is the smallest in size (when compressed), it’s used even by Google, developers from all around the world write plugins for it and is still developed. So, our choice is: JQuery.

Toggle elements with JQuery
Hiding elements with JQuery is more than simple. First you have to include the jquery framework in your head element, then 3 simple javascript lines:

$("button").click(function () {
$("p").toggle();
});

Of course, it’s always better to put your functions in $document.ready to assure they will work only when the page is fully loaded.
What the above means: if you click a button element, toggle the paragraph element. Simple yet effective. You can ready more about toggle() here.
Another cool way is to animate the toggle effect. In this case the code will look something like this:

$("a.THE_SHOW_LINK").click(function(){
$("div#DIV_TO_HIDE").animate({
height: "180px"
})
.animate({
height: "200px"
}, "fast");
});
$("a.THE_HIDE_LINK").click(function(){
$("div#DIV_TO_HIDE").animate({
height: "0px"
}, "fast");
});

The element with the DIV_TO_HIDE id has to have null height, no display and hidden overflow specified in your CSS, that will be toggled to 180 pixels. An example of the above can be seen here: http://tester.devoracles.com/jquery_examples.html. Feel free to play with it.
Using the above two functions of JQuery you can safely hide forms which normally have dedicated and useless pages.

Tips with JQuery
Another annoyance is when you click a help link and you’re taken to a page where there’s only one line of content. Here comes in help JTip, developed by Cody Lindley. Please click the following link and have a look: JTip.
As you see, when you roll over the links or the question marks, you get some tips. Neat tips. The content of these tips are loaded from those useless pages I talked about, those with one line of content. The annoyance is gone: I’m not taken to those useless pages.

Next post: A social network and the user generated content

Building a social network - The beginning

We didn’t even finish the blog post aggregator and publisher service, we’ve been hired to develop a social network service. I can’t say too much about it yet, but basically is a mash-up between some infamous services like Digg, Facebook, Orkut and I could continue…
My first reaction when heard about what do we have to do was that why the World needs another social network. There are so many and seemingly the market is overfilled with these kind of services. Then I was explained that this won’t be just another social network, it has a good idea behind it (which I still don’t know). We’ll see. I really hope it won’t be like twitter.com… somehow I don’t get why that service is good. But that’s just me.

So, in these series I will explain each and every step we’ve taken to develop a website which can run even if it takes 1 million hits per day, what security measures we’ve taken and how did we solve some of the UI things.

Next post of the series: A social network’s UI - simple yet effective

Tune in, it might be interesting.

CSS taken to extreme - The sprite

No, not the drink nor a fairy. I talk about a CSS technique which has been borrowed from the game developers if I’m not mistaken, but correct me if I’m wrong; since games appeared first and not CSS I guess this is the situation. The sprites in computer graphics are images which are moved across the screen to form a larger scale image. Uhh, I don’t understand! Read further and I explain.

In short, what’s this all about: I’m almost sure everybody realizes that nowadays every website has in its structure some kind of image, either for navigation, for background, for borders, anything, but today a website can’t look like back in ‘95, so the images has been brought on the scene to make the websites look better. The images which appear in the layout of a website are controlled by CSS. So, let’s say you have a website which has a cool background, every link has its own background image, you have cool borders, rounded corners. How would you do that in CSS? Somehow like this:

#bg{
background:url(bg_img.jpg) repeat-y center;
}

#wrap{
margin: 0 auto;
width:700px;
background:url(wrap_bg_img.jpg) repeat-y center;
}

.home a{
display:block;
width:25px;
height:25px;
background:url(home_bg_img.jpg) no-repeat center;
}

.about a{
display:block;
width:25px;
height:25px;
background:url(about_bg_img.jpg) no-repeat center;
}

As you see above, each element has its own image. Each image is, let’s say 3kb. So what happens when someone loads this page? The end-users’ browser will open 4 connections to the webserver, and will request each image one-by-one. So, there is time spent to open and close these connections. In addition, there is 12kb of data requested.
What if I say, you can resolve all this by opening one single connection and transfer only 6kb of data, and every image will be transferred to the browser so your page will look like you’d have transferred all the images separately?

Follow please this link: Ask.com’s sprites.
What do you see? A bigger image which contains all the images which are used on Ask.com. In one single file they transferred all the images, thus minimizing server impact and minimizing the amount of transferred data. These are the sprites has been invented for. Cool, isn’t it?

So, how to use these sprites in our own life? It’s extremely simple: you dump all the images you want to use in one single image file, then you move that image as you want, using CSS.
Using an example is easier to explain, so let’s see that example.

sprite example | Devoracles.com

The image file I will use is the one you see on the left. I will create a link and if you hover over it you will see another image as the link’s background, same applies if you click it.

So, a live example:

Try to click it, hover over it. You will notice a nice, smooth transition between the images, no waiting between the image loads.
The style used which manages to make use of the sprite is this:

.sprite a{
display:block;width:25px;height:25px;background:url(http://devoracles.com/images/sprite.png) no-repeat;
}
.sprite a:hover{
background-position: -27px 0;
}
.sprite a:active{
background-position:-54px 0;
}

How can sprites be in your favor? Well, they will speed up your website, considerably because of two factors: less time spent with opening/closing connections, then a single file will be much smaller than many small files. So you will save bandwidth.

Have questions? I’m here to answer them.

jQuery : Error: $(document).ready is not a function — Sure!

This error message appears only if another framework is in conflict with the almighty jQuery. For example You try to use Prototype/Scriptaculous for Lightbox but you also need Thickbox for something else, which requires jQuery.

Since no framework is compatible with another framework, you have to find a workaround to get things working.

And here comes jQuery in your help. The jQuery team was smart enough to realize that there will be conflicts between frameworks, especially the $ will cause massive headaches since it’s the basic of each framework. $ is the shortcut for the word “jQuery”

So, they invented jQuery.noConflict();. This will let you to replace the $ with the word jQuery, in all your code. So, when you need to call this: $(document).ready(function(){ … You simply replace the $ as I said above: jQuery(document).ready(function(){ …, don’t forget to call jQuery.noConflict(); before this.

So, when you use the noConflict() function, your code should look something like this:

<head>
  
  
  
</head>

World saved again, now you can use 2 frameworks together.

Vertical text with Imagick

Creating vertical text over an image is extremely simple with Imagick. The text created with Imagick can be used for example as a watermark over an image or any other thing you can think of.

It’s very important to understand that the created object is just an image and that you can not have any text before the below code block and which will be sent to browser output. This includes white-space, page brake or any type of text.

The vertical text is obtained with annotateImage() since it’s 4th parameter of the function is to set the degree of the text. 0 degrees is horizontal text, 90 degrees is vertical text, that simple.

Let’s see the code:

$image = new Imagick();
$draw = new ImagickDraw();
$pixel = new ImagickPixel( 'white' );
$image->newImage(25, 150, $pixel);
$draw->setFontSize( 20 );
$image->annotateImage($draw, 0, 0, 90, 'Devoracles.com');
$image->setImageFormat('png');
header('Content-type: image/png');
echo $image;

The above’s result is what you see below.

As you see it’s extremely simple to create vertical text with Imagick, either if you’re a novice or a pro.

If you have any related question, feel free to ask.

Managing PDF files with Imagick

Many doesn’t know, but with Imagick anyone can manage PDF files. As far as I know you can’t create one, but this function can be extremely useful to create a screenshot of a PDF file on the server’s side.

First of all, the PDF file you just created has to be loaded in Imagick, either the whole document or only one page from it, then you can output it as any type of image, let’s see how to do it:

$pdf = new imagick( 'your.pdf' );
$pdf->setImageFormat( "gif" );
header( "Content-Type: image/gif" );
echo $pdf;

Be aware that you can not output anything else before this code block neither a whitespace or text. Nothing. Also, you can specify any image format you wish as Imagick can output almost any image format.

Look at the above code block. The first line says:

$pdf = new imagick( 'your.pdf' );

If you would like to select a specific page to output from the PDF, just specify the page number as it follows:

/*This would select the cover page: */
$pdf = new imagick( 'your.pdf[0]' );

/*and this the actual 1st page: */
$pdf = new imagick( 'your.pdf[1]' );

Now you should get the idea, if you don’t, feel free to question me.

The last thing I show you is how to create a thumbnail of a PDF. There is no too much difference, the only one is that before outputting the image we resize it using thumbnailImage():

$pdf = new imagick( 'your.pdf' );
$pdf->setImageFormat( "gif" );
$im->thumbnailImage( 200, NULL );
header( "Content-Type: image/gif" );
echo $pdf;

I used ‘NULL’ to preserve the image’s aspect ratio.

As always, if anything is unclear, feel free to question me.

Conditions in HTML

If you are a developer, you know that in ANY programming language there are conditions which can be used to decide what action to perform if a given criteria applies. This applies to all programming languages, Javascript, ASP, PHP, C, bash, and even HTML. Not sure though if I can say HTL is a programming language.
Anyway, let’s see what HTML conditions are used for and how to work with them.
First, let’s note that Internet Explorer is the *only* browser which can work with them. Not sure why, but only the guys from Microsoft thought HTML should be a bit more complicated and more useful.

The markup is extremely simple, I could say rudimentary: you know HTML comments. When you place something between the <!– –>, that’s a comment. It will appear in the source but browsers will not output or execute it. But Internet Explorer tries to execute it.

To start a HTML condition, you have to use the same markup, but spice up with a condition, like this:

<!–[if something]>

Foo bar text

<![endif]–>

In the above case if the condition is applicable, the the paragraph from the example will be shown in the source. Why only in the source? Because there are two types of conditional comments: first what you saw above, it’s named hidden conditional comment and the second which is, well, revealed conditional comment. Yeah, Microsoft has unimaginable imagination.
A revealed conditional comment would look like this:

<![if something]>

Foo bar text

<![endif]>

Notice that I didn’t put the hyphens in in front of the if statement, nor to the end of the block.

What can you use this new knowledge for? Well, almost nothing. Since only IE knows what to do with these comments, it can be used for browser detection, to load separate stylesheets for different browsers, or such. More than that, even with IE you hit the wall, since the only valid feature is the “IE” word. I explain this with a code:

<![if IE 7]> <link rel=”stylesheet.css” media=”all” href=’stylesheet.css” /> <![endif]>

The above example will load a stylesheet if the browser is IE 7, or you could use the following code:

<![if IE]> <link rel=”stylesheet.css” media=”all” href=’stylesheet.css” /> <![endif]>

to load a stylesheet if the browser is some kind of Internet Explorer.

As You see I always used only the IE word in my example, and that’s why I said that this code has this only feature. You can’t use anything else, like [if NS] or [if DO] only and only [if IE ...].

Should you learn this? I think you shouldn’t. We have much better things to do than to learn something which is absolutely not crossbrowser.

Then why did I write this post? Because next time you’ll see an if statement in a HTML comment, at least you will know what it is.

XHTML Strict incompatible with target attribute: FALSE


Clients… I had to create a website… XHTML Strict… AND opening all links in a new tab/window.
No probs, there’s the target attribute of the anchor elements! But not in XHTML Strict!
W3 states clearly that target attributes should be forgotten and avoided. Why, I have no idea, but if you want to create XHTML Strict pages, you can forget about the target attribute.

So let’s hack with Javascript this rule! Rules are set to have something to brake, that’s what we’ll do now. This is very simple code, basically a single function which loops through the document and adds to all the anchor elements the “target=’_blank’” attribute. As it’s created with Javascript, the XHTML validators should not observe. I think they won’t observe, so first check it out somewhere.

So, the Javascript code to open links in new window/tab while maintaining the XHTML Strict compliance is:

function open_in_new_tab() {
if (!document.getElementsByTagName){
return;
/*If the browser doesn't support DOM, do nothing*/
}
var anchors = document.getElementsByTagName("a");
/*Select all the 'a' tags, anchors*/
for (var i=0; i<anchors.length; i++) {
var links = anchors[i];
if (links.getAttribute("href")){
/*every anchor with 'href' attribute will get a new attribute,
only those with 'href' attribute set because we don't want
to mess with the section anchors, for example*/
links.target = "_blank";
}
}
}
window.onload = open_in_new_tab;
/*finally load the function on page load*/

And the word is saved again.

Javascript pop-up windows and parent page refreshing

This subject is quite interesting and i was searching for examples for long. Then I managed to do something, true that only by combining many examples i’ve found.

Let’s see the code then I’ll try to explain everything.

function popUp(URL) {
window.open(URL, 'WindowName', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=300,height=400');
}
window.onload = popUp("http://example.com");

The above function will pop-up window which will contain the page you put as value in the popUp function. I’ve put http://example.com, you put whatever you like, but preferably from your own domain if you want to have access to the pop-up’s DOM. You can play with the toolbar,scrollbars,location variables till hurts, basically they define how the popped up window will look and act. I wrote the above script so to pop the window up when the page loads (window.onload) , if you don’t like that and the fact that this even is blocked by most pop-up blockers, you can put a HTML button or link somewhere in the page, like this:

Pop Up the window

As I said before, there’s a slight issue with the stuff if you use the window.onload, specifically that your pop-up much likely will be blocked by pop-up blockers. You don’t want that, and even if it succeeds to pop-up, it’s annoying for the visitor, so just don’t do it, please.

OK, now let’s see the the parent window refreshing. Prent window is the page which pop-up up the small window. The pop-up window is the child. Usually, we use the parent refresh if we want to transfer a variable from the pop-up to the parent. The script which has to be placed in the child, popped up window is the following script:

function Parent() {
  window.opener.location.href = window.opener.location.href;
  if (window.opener.progressWindow){
    window.opener.progressWindow.close()
  }
  window.close();
}

and the button or link which closes and refreshes the parent window is

Click here to close this window and refresh the parent

A working example is situated here. It’s a loop so if your pop-up blocker doesn’t block the first pop-up, most likely you’ll get annoyed in no time.

And I think that was all. You can also transfer variables from one window to other, but that’s for another day… so, the show is over… there’s nothing to see here, pass over please.