Making a simple math captcha using jquery

I wanted to write a simple Captcha that I could easily integrate into my own scripts that would work with or without Javascript. My first approach was to find open-source that I could pretty much just copy and paste into my code with little modification. All the cookie-cutter Captcha scripts I found were so bloated with extra code and were either only client-side (Javascript) or server-side (PHP), that I decided to create something from scratch. What I came up with is a script that uses Ajax for a smoother user experience (no browser reload on submit), but also works if the user has Javascript disabled for progressive enhancement (or graceful degradation).

Captcha Field
The following code section goes into your HTML form to create the Captcha section. To set the values of the fields to be added, use PHP rand() function to get a different random value each time the page is loaded (1st number is random number 1-4, and 2nd number is random number from 5-9 for easy use).

<input id="num1" class="sum" type="text" name="num1" value="<?php echo rand(1,4) ?>" readonly="readonly" /> +
<input id="num2" class="sum" type="text" name="num2" value="<?php echo rand(5,9) ?>" readonly="readonly" /> =
<input id="captcha" class="captcha" type="text" name="captcha" maxlength="2" />
<span id="spambot">(Are you human, or spambot?)</span>

Custom validation Mathod
Method basically gets the random values from the form, the total value entered by the user, adds them together and compares. If the two numbers don’t equal the total, then it returns an error. Otherwise it returns the result.
$.validator.addMethod('captcha',
function(value) {
$result = ( parseInt($('#num1').val()) + parseInt($('#num2').val()) == parseInt($('#captcha').val()) ) ;
$('#spambot').fadeOut('fast');
return $result;
},
'Incorrect value, please try again.'
);

Advertisements

WordPress – custom form submission redirect to 404 page.

I found many people having this problem in WP. The problem was caused by the “global” parameter. Obviously, WP has something important internal reserved for that parameter.

Global variable

Global variable is a variable that is accessible in every scope, in PHP it works ONLY for the same page and the file that are included after. However, some predefined variables, known as superglobals are always accessible in whole site. Both of global and superglobal variable can be redefined or overwrite it’s value.

When developing a WordPress Plugin and or Theme, sometimes you use the PHP global variable. That’s okay, but it’s HIGHLY RECOMMENDED that you not use variable name that are already defined by WordPress. Why?  Because it may break your other code that may intended to use WordPress variable.

Here is the lists of WordPress Reserved Variable, the left side is variable name, and the right side is the type

$_template_file = string
$require_once = boolean
$posts = array
$post = object
$wp_did_header = boolean
$wp_did_template_redirect = NULL
$wp_query = object
$wp_rewrite = object
$wpdb = object
$wp_version = string
$wp = object
$id = integer
$comment = NULL
$user_ID = integer
$cat = string
$paged = integer
$error = string
$m = integer
$p = integer
$post_parent = string
$subpost = string
$subpost_id = string
$attachment = string
$attachment_id = integer
$name = string
$static = string
$pagename = string
$page_id = integer
$second = string
$minute = string
$hour = string
$day = integer
$monthnum = integer
$year = integer
$w = integer
$category_name = string
$tag = string
$tag_id = string
$author_name = string
$feed = string
$tb = string
$comments_popup = string
$meta_key = string
$meta_value = string
$preview = string
$s = string
$sentence = string
$fields = string
$category__in = array
$category__not_in = array
$category__and = array
$post__in = array
$post__not_in = array
$tag__in = array
$tag__not_in = array
$tag__and = array
$tag_slug__in = array
$tag_slug__and = array
$ignore_sticky_posts = boolean
$suppress_filters = boolean
$cache_results = boolean
$update_post_term_cache = boolean
$update_post_meta_cache = boolean
$post_type = string
$posts_per_page = integer
$nopaging = boolean
$comments_per_page = string
$no_found_rows = boolean
$order = string

How browsers work

The browser main functionality is to present the web resource you choose, by requesting it from the server and displaying it on the browser window. The resource format is usually HTML but also PDF, image and more. The location of the resource is specified by the user using a URI (Uniform resource Identifier).

The way the browser interprets and displays HTML files is specified in the HTML and CSS specifications. These specifications are maintained by the W3C (World Wide Web Consortium) organization, which is the standards organization for the web.

Browsers’ user interface have a lot in common with each other. Among the common user interface elements are:

  • Address bar for inserting the URI
  • Back and forward buttons
  • Bookmarking options
  • A refresh and stop buttons for refreshing and stopping the loading of current documents
  • Home button that gets you to your home page

Strangely enough, the browser’s user interface is not specified in any formal specification, it is just good practices shaped over years of experience and by browsers imitating each other. The HTML5 specification doesn’t define UI elements a browser must have, but lists some common elements. Among those are the address bar, status bar and tool bar. There are, of course, features unique to a specific browser like Firefox downloads manager.

The browser’s high level structure

  • The user interface – this includes the address bar, back/forward button, bookmarking menu etc. Every part of the browser display except the main window where you see the requested page.
  • The browser engine – the interface for querying and manipulating the rendering engine.
  • The rendering engine – responsible for displaying the requested content. For example if the requested content is HTML, it is responsible for parsing the HTML and CSS and displaying the parsed content on the screen.
  • Networking – used for network calls, like HTTP requests. It has platform independent interface and underneath implementations for each platform.
  • UI backend – used for drawing basic widgets like combo boxes and windows. It exposes a generic interface that is not platform specific. Underneath it uses the operating system user interface methods.
  • JavaScript interpreter. Used to parse and execute the JavaScript code.
  • Data storage. This is a persistence layer. The browser needs to save all sorts of data on the hard disk, for examples, cookies. The new HTML specification (HTML5) defines ‘web database’ which is a complete (although light) database in the browser.

layers

It is important to note that Chrome, unlike most browsers, holds multiple instances of the rendering engine – one for each tab,. Each tab is a separate process.

The rendering engine

The responsibility of the rendering engine is well… Rendering, that is display of the requested contents on the browser screen.

By default the rendering engine can display HTML and XML documents and images. It can display other types through a plug-in (a browser extension). An example is displaying PDF using a PDF viewer plug-in. We will talk about plug-ins and extensions in a special chapter. In this chapter we will focus on the main use case – displaying HTML and images that are formatted using CSS.

Rendering engines

Our reference browsers – Firefox, Chrome and Safari are built upon two rendering engines. Firefox uses Gecko – a “home made” Mozilla rendering engine. Both Safari and Chrome use Webkit.

Webkit is an open source rendering engine which started as an engine for the Linux platform and was modified by Apple to support Mac and Windows. See http://webkit.org/ for more details.

The main flow

The rendering engine will start getting the contents of the requested document from the networking layer. This will usually be done in 8K chunks.

After that this is the basic flow of the rendering engine:

flow

The rendering engine will start parsing the HTML document and turn the tags to DOM nodes in a tree called the “content tree”. It will parse the style data, both in external CSS files and in style elements. The styling information together with visual instructions in the HTML will be used to create another tree – the render tree.

The render tree contains rectangles with visual attributes like color and dimensions. The rectangles are in the right order to be displayed on the screen.

After the construction of the render tree it goes through a “layout” process. This means giving each node the exact coordinates where it should appear on the screen. The next stage is painting – the render tree will be traversed and each node will be painted using the UI backend layer.

It’s important to understand that this is a gradual process. For better user experience, the rendering engine will try to display contents on the screen as soon as possible. It will not wait until all HTML is parsed before starting to build and layout the render tree. Parts of the content will be parsed and displayed, while the process continues with the rest of the contents that keeps coming from the network.

Main flow examples

webkitflow

Webkit main flow

image008

Mozilla’s Gecko rendering engine main flow

Parsing – general

Since parsing is a very significant process within the rendering engine, we will go into it a little more deeply. Let’s begin with a little introduction about parsing.

Parsing a document means translating it to some structure that makes sense – something the code can understand and use. The result of parsing is usually a tree of nodes that represent the structure of the document. It is called a parse tree or a syntax tree.

Example – parsing the expression “2 + 3 – 1” could return this tree:

image009

mathematical expression tree node

Rendering Process

At a high level, most modern browsers carry out the following steps to render an HTML page:

  • Load the HTML
  • Parse it
  • Apply styles
  • Build frames
  • Layout the frames (flow)
  • Paint the frames

1.Load: The browser tries to fetch the page from the specified location. Typically this would be thru a HTTP client. However, a HTML page may also be loaded from a filesystem. Irrespective, the loader fetches the HTML page from its location. The super important concept of Browser Cache comes into play over here – but more on this later. The way the HTML page gets loaded is different from the way the resources get loaded. In WebKit there are two different pipelines – one for loading the page and another for loading resources:(source: http://webkit.org/blog/1188/how-webkit-loads-a-web-page/)

2.Parse: As the stream comes thru from the loader, an HTML parser starts building the DOM (also called a “Content Tree”) – each node here is an HTML element. Now a lot of HTML on the net is broken, and each browser has had to implement its own quirks to parse HTML leading to subtle incompatibilities. HTML 5 however specifies the parsing algorithm. As this gets adopted, the x-browser incompatibilities because of parsing should go away. While parsing, the engine may come across resources (JS, CSS, images, fonts, etc.) When that happens the particular resource is queued for loading and parsing continues. Again, there is more to this, which we’ll tackle later.

3.Compute Styles: The browser provides a default stylesheet. Often the HTML page also has a set of styles specified. These styles need to be applied to the Content Tree. For this purpose, a “Rendering Tree” is built – this essentially consists of elements that are to be rendered. For example an element with display set to none would not appear in this tree (nor would its descendants). Nor would elements like HEAD and SCRIPT. Nodes in the Render Tree represent style information: CSS box model, z-order, opacity are all specified here

4.Construct Frames: Most render-able elements follow the CSS box model: They have height, width, border, spacing, padding, margin and position. For these objects, a rectangular box – called a Frame – is created. Not all objects have a frame – for example the SVG image above does not have a frame. It is put inside an iframe, which has a frame. A frame has all the information on how the object itself is going to be rendered. What is not known however, is how is the element going to be placed w.r.t other elements.

5.Compute Flow: Flow Computation or Layout Computation is about how elements are placed w.r.t each other and is mostly controlled by the CSS Visual Rendering Model. This is typically a recursive process from the root of the tree to leafs. Also, this is typically a lazy process – it is done on a need-basis. Basically when the layout engine determines that an element needs to be laid out (for example a newly added Node), it marks it as such by setting a dirty bit. The actual layout is done only when some method is called which requires the new information. Most browsers do flow calculation at a higher resolution than what any display would have. This is to support zooming – when the user zooms in or out, the objects can be drawn correctly on the screen without requiring any extra steps other than mapping the coordinates to real pixels.

6.Paint: Once the engine knows exactly where the objects need to be drawn, comes the process of actually rendering the objects on the screen. This process – called Painting – is described in agonizing detail in Appendix E of the CSS 2.1 Spec. This is basically a Tree walk from the root of the Rendering tree, where each node is asked to paint itself. The actual rendering is abstracted out thru a Graphics Engine which is responsible for actually turning on the pixels and things like hardware acceleration.

Writing Your Own jQuery Plugins

jQuery is great. It’s cross-browser, easy to learn, and makes adding interactivity to your website a breeze. It also comes with plenty of plugins to do almost whatever you need it to do.

But what if you can’t find just the right plugin to suit your needs? Or you’re just looking to keep your project DRY by combining some oft-used functionality into one nice, neat package? The solution might be to roll your own plugin to meet exactly your needs.

Writing your own jQuery plugin isn’t as hard as it might seem at first. This tutorial will go through the process of writing a simple plugin, adding some options, and even perform a callback.
Setting Up

We’ll start with the old chesnut of programming tutorials, a “Hello, World!” plugin. Before we can do anything, we need to establish our file and link it to our HTML document. First, we’ll create our plugin file and put it in the “js” directory of our website. It’s traditional to start our filename with “jquery,” followed by the actual plugin name, so we’ll call this “jquery.hello-world.js”.

folder

Next, we’ll need to make sure our plugin file, as well as it’s jQuery core big brother, are linked in our HTML file, so place the following two lines at the bottom of your HTML document, just before the closing body tag:

The jQuery Plugin Structure

jQuery comes with all the necessary hooks to build your plugin file easily. But we still want to be mindful of good JavaScript practices, and make sure we keep everything inside a local scope. We’ll start with the very basic shell of a traditional jQuery plugin:

(function($) {
$.fn.helloWorld = function() {
// Future home of "Hello, World!"
}
}(jQuery));

Let’s take a quick moment to understand what’s going on. By including everything in the (function() {}) self-enclosed JavaScript pattern, we’re making sure that all the variables in our plugin will stay safely outside of the global namespace. We don’t want to cause any collisions with any other JavaScript used on the page, after all.

The other thing you might notice is that we’re defining our plugin as if jQuery was in it’s “no-conflict” mode. Again, we’re seeking to avoid colliding with other JavaScript on the page, and thus we want to make sure that our plugin isn’t reliant on the default $, which could be used by another library.

Finally, $.fn is jQuery’s way of allowing you to define your plugin, which we’ve named helloWorld. With all of our pieces in place, let’s actually do something!
Making Our Plugin Do Something

For our plugin, we’re going to do something pretty silly, but also simple enough for our demonstration purposes, and that is to change all the text for the acted upon elements with (what else?) the text “Hello, World!”.

(function($) {
$.fn.helloWorld = function() {
this.each( function() {
$(this).text("Hello, World!");
});
}
}(jQuery));

When we’re invoking the plugin by attaching it to a jQuery selector, the object we’re acting upon is already a jQuery object, so we don’t need to wrap it in the $(this) structure you’re used to. However, once we start looping through each instance of the matching selector, we use the $(this) structure as we would any time we ran our selectors through $.each().

We would invoke the plugin as you’re already familiar, like so:

$(document).ready( function() {
$('h2').helloWorld();
});

We’re not quite done yet. While our plugin technically works, it’s living in its own little isolated world. That is, if you try and chain another jQuery action onto it, nothing’s going to happen because our plugin has led to a dead end. To fix this, be sure to return the results of the plugin as it loops through the DOM elements:

(function($) {
$.fn.helloWorld = function() {
return this.each( function() {
$(this).text("Hello, World!");
});
}
}(jQuery));

And congratulations! You’ve just written you’re first jQuery plugin!

Well, we could start by just adding an argument. Let’s take our plugin above, and instead of hard-coding the text into the plugin, we can replace it with a variable and pass that along when we invoke the plugin.

(function($) {
$.fn.helloWorld = function( customText ) {
return this.each( function() {
$(this).text( customText );
});
}
}(jQuery));

which we now use as the parameter of our plugin:

$(document).ready( function() {
$('h2').helloWorld('¡Hola, mundo!');
});

$.extend method:

(function($) {
$.fn.helloWorld = function( options ) {

// Establish our default settings
var settings = $.extend({
text : 'Hello, World!',
color : null,
fontStyle : null
}, options);

return this.each( function() {
// We'll get back to this in a moment
});
}
}(jQuery));

Now we have a settings object that, when the plugin is invoked devoid of any parameters, will use what we’ve established as the default text. We also have two other properties of our settings object, “color” and “fontStyle”, that have no default beyond null. For this plugin, we don’t need to establish any color or font style beyond what is laid out in our CSS, but they’re there for the overriding if we want. We just have to make use of them:

return this.each( function() {
$(this).text( settings.text );

if ( settings.color ) {
$(this).css( 'color', settings.color );
}

if ( settings.fontStyle ) {
$(this).css( 'font-style', settings.fontStyle );
}
});

Fortunately, our plugin can now handle color, fontStyle requests:

$('h2').helloWorld({
text : 'Salut, le monde!',
color : '#005dff',
fontStyle : 'italic'
});

How can I execute PHP code on my existing myfile.html page?

When a web page is accessed, the server checks the extension to know how to handle the page. Generally speaking if it sees a .htm or .html file, it sends it right to the browser because it doesn’t have anything to process on the server. If it sees a .php extension (or .shtml, or .asp, etc), it knows that it needs to execute the appropriate code before passing it along to the browser.

Here is the problem: You find the perfect script, and you want to run it on your site, but you need to included PHP on your page for it to work. You could just rename your pages to yourpage.php instead of yourpage.html, but you already have incoming links or search engine ranking so you don’t want to change the file name. What can you do?

First let me preface this by saying that if you are creating a new file anyway, you may as well use .php. This is to help people who have existing .html pages they need to execute PHP on.

The way to execute PHP on a .html page is to modify your .htaccess file. This file may be hidden, so depending upon your FTP program you may have to modify some settings to see it. Then you just need to add this line for .html:

AddType application/x-httpd-php .html
Or for .htm
AddType application/x-httpd-php .htm

If you only plan on including the PHP on one page, it is better to setup this way:


AddType application/x-httpd-php .html

This code will only make the PHP executable on the yourpage.html file, and not on all of your html pages.

Things to watch out for:

  • If you have an existing .htaccess file, add this to it, do not overwrite it or other settings may stop working! Always be very careful with your .htaccess file and ask your host if you need help
  • Anything in your .html files that starts with <? will now be executed as PHP, so if it’s in your file for some other reason (an XML tag for example) you will need to echo these lines to prevent errors.For example:

INSERT … ON DUPLICATE KEY UPDATE Syntax

If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, an UPDATE of the old row is performed. For example, if column a is declared as UNIQUE and contains the value 1, the following two statements have identical effect:

INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=c+1;

UPDATE table SET c=c+1 WHERE a=1;

The ON DUPLICATE KEY UPDATE clause can contain multiple column assignments, separated by commas.

With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row, and 2 if an existing row is updated.

INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6)
ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b);

That statement is identical to the following two statements:

INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=3;
INSERT INTO table (a,b,c) VALUES (4,5,6)
ON DUPLICATE KEY UPDATE c=9;

File/folder Permission

Note that mode is not automatically assumed to be an octal value, so strings (such as “g+w”) will not work properly. To ensure the expected operation, you need to prefix mode with a zero (0):

chmod("/somedir/somefile", 755); // decimal; probably incorrect
chmod("/somedir/somefile", "u+rwx,go+rx"); // string; incorrect
chmod("/somedir/somefile", 0755); // octal; correct value of mode

The mode parameter consists of three octal number components specifying access restrictions for the owner, the user group in which the owner is in, and to everybody else in this order.

// Read and write for owner, nothing for everybody else
chmod("/somedir/somefile", 0600);
// Read and write for owner, read for everybody else
chmod("/somedir/somefile", 0644);
// Everything for owner, read and execute for others
chmod("/somedir/somefile", 0755);
// Everything for owner, read and execute for owner's group
chmod("/somedir/somefile", 0750);

Change File Permission Owner

// File name and username to use
$file_name= "foo.php";
$path = "/home/sites/public_html/sandbox/" . $file_name ;
$user_name = "root";

// Set the user
chown($path, $user_name);

// Check the result
$stat = stat($path);
print_r(posix_getpwuid($stat['uid']));