Learning Computer Programming

I post articles, tips, tricks, techniques, algorithms etc. related to C++ Programming. Many of the things that I discuss also applies to other programming languages.

Total indexed: 25 posts
Average post: Every 22 Days

Blogarama.com  >  Software Blogs  >  Programming Blogs  >  Learning Computer Programming

Designing Your Own Lightbox in Javascript

In nowadays web 2.0 world use of Lightbox is very common. While Lightbox, fancybox (similar to the former) are great scripts and have wide uses, creating a script similar to these is never a bad idea. If you learn, read on else use of one of those scripts, they’re great and easy-to-use.

For those of you who haven’t heard about the script or don’t know what they do, see the following image:

Chances are, you might surely have seen it somewhere or the other. These scripts are generally used to display some content in kind of like a dialog box (modal one, for those of you who're geeks) while the rest of the content gets blackened. Looks great? Yes it does!

Okay, for those of you still here I wanna confess that I didn’t put enough time knowing how those scripts actually work. I just got an idea myself the other day and thought it just might work. This is not to say that I myself have invented some new way, it’s just that I don’t know how those scripts work but I know one way that gives similar results.

As you can see from the above image, there is not much to a simple Lightbox clone, we have a (1) Blackening effect (2) The content box.

  1.  

    Blackening Effect: For this I’ll create a “div” element on the fly and set its properties such that it has a black color and some transparency, a large z-index means floats on top of the rest of the content and back content (with normal z-index) cannot be interacted with anymore. We’ll fill the current screen with this “div” which will require us to place this element at the topmost and leftmost coordinates relative to the current viewable area. This will be (0, 0) when the page isn’t scrolled at all.

     

    We’ll also have to size the element to have it span the whole viewable area of the browser.

     

    These two things will make sure that no matter where we have scrolled in a page and whatever be the window size, this black overlay element always covers the current viewport.

     
  2.  
  3.  

    2. Content Box: A nicely styled box with a close button is all we need. We’ll place it at the center of the screen. Since we have calculated the topmost and leftmost coordinates relative to the current viewport and we also have the current viewport’s dimension, we can easily position this at the center, no brainer! We’ll give this a z-index larger than the black overlay element such that this is at the top of everything.

     

    Besides this, we’ll also have to take care that these two elements move along with the page in case user tries to scroll the page when the our lightbox is open. This will make sure that (1) black overlay element always fills the screen (2) content box is always at the center.

     

Sounds pretty simple? Well, it is! It’ll call this Blackbox, you may call it whatever you feel like. Here is the code ( Demo here):


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Blackbox - A very simple Lightbox clone</title> <script type="text/javascript">
/*
 * Script: Blackbox (very simple Lightbox clone)
 * Author: Arvind Gupta ([email protected])
 * Date: 14-Nov-09
 * Copyright: 2009 Arvind Gupta  * You may freely use this script wherever
 * you want and in whatever way you wish
 * but please don't remove this note.
 *
 */ // OBJECTS // Black overlay element
var darkbox;
// Content box
var content; // FUNCTIONS
function init()
{ // Set "onScroll" event handler window.onscroll = scroll_box;
} function open()
{ // Create elements darkbox = document.createElement('div'); content = document.createElement('div'); // Style them with the existing ids darkbox.id = 'darkbox'; content.id = 'content'; // FILL CONTENT BOX // Have the close button content.innerHTML = '<a style="position: absolute; top: -30px; right: -30px; text-decoration: none;" href="javascript:close();"><img style="border: none;" src="fancy_closebox.png" /></a>'; // The main content content.innerHTML += '<div id="main_content"><h1>Hello</h1><p>Hello World!<br /> How is this looking?</p></div>'; // Add these elements to the body document.body.appendChild(darkbox); document.body.appendChild(content); // Calciulate coordinates and such var pos_top = document.documentElement.scrollTop var pos_left = document.documentElement.scrollLeft; var screen_width = document.documentElement.clientWidth; var screen_height = document.documentElement.clientHeight; // Place the "darkbox" element and give it the size darkbox.style.top = pos_top + 'px'; darkbox.style.left = pos_left + 'px'; darkbox.style.height = screen_height + 'px'; darkbox.style.width = screen_width + 'px'; // Now place the content box at the center content.style.left = (pos_left + (screen_width / 2.0) - (content.offsetWidth / 2.0)) + 'px'; content.style.top = (pos_top + (screen_height / 2.0) - (content.offsetHeight / 2.0)) + 'px';
} function scroll_box ()
{ // If "Darkbox" open if(darkbox != null) { // Find new topmost, leftmost position w.r.t the current viewport // Also find new window size var pos_top = document.documentElement.scrollTop var pos_left = document.documentElement.scrollLeft; var screen_width = document.documentElement.clientWidth; var screen_height = document.documentElement.clientHeight; // Positions elements accordingly darkbox.style.top = pos_top + 'px'; darkbox.style.left = pos_left + 'px'; darkbox.style.height = screen_height + 'px'; darkbox.style.width = screen_width + 'px'; content.style.left = (pos_left + (screen_width / 2.0) - (content.offsetWidth / 2.0)) + 'px'; content.style.top = (pos_top + (screen_height / 2.0) - (content.offsetHeight / 2.0)) + 'px'; }
} function close()
{ // Delete elements document.body.removeChild(darkbox); document.body.removeChild(content);
}
</script> <style>
#darkbox { position: absolute; top: 0px; left: 0px; opacity: 0.6; filter:alpha(opacity=60); background: #000;
} #content { position: absolute; z-index: 1001; background: #fff; border: 10px solid #000; width: 500px; height: 300px;
}
#content #main_content { overflow: auto; width: 500px; height: 300px;
} </style>
</head> <body onload="init();">
<a href="javascript:open()">Open Box</a>
</body>
</html>

Related Posts:

  •  

    A Simple Pong Game using JavaScript

     
  •  
  •  

    Moving (Positioning) an Image Using JavaScript 

     
  •  
  •  

    Creating a Simple Countdown Timer Using JavaScript II...Using getElementById() Method

     
  •  
  •  

    Creating a Simple Countdown Timer Using JavaScript

     
  •  
  •  

    Creating a Simple HTML Form Validation System Using JavaScript

     
Read full post >>

Happy Diwali

A Simple Pong Game using JavaScript

Having the knowledge of moving images using JavaScript, we’ll be creating a small Ping Pong game as an example for this post.

Today we’ll learn to do a few new things in JavaScript:

1. Executing some code every specified time interval (for game loop).
 2. Tracking and using mouse movements.
 3. Attaching code (function) to events.

Game Theory

As you should be knowing, in this game there is one ball and two paddles at two ends. One is user-controlled the other, for this example, is CPU controlled. User has to move the paddle in order not to let the ball pass through, CPU also has to do the same thing. Whoever’s side the ball passes through looses the game.

There are a few objects which can interact with each other, these are ball, paddles, walls. Let’s see the various interactions that can take place between these:

  1.  

    Ball Hitting Upper/Lower Wall – Ball will bounce off.

     
  2.  
  3.  

    Ball Passing Through Either Side – Player or CPU, depending on whose side ball passed through, will loose the game.

     
  4.  
  5.  

    Ball Hitting Paddle – It’ll bounce off

     

We’ll need to take care of these events:

  1.  

    Page Load – Game objects will be initialized

     
  2.  
  3.  

    Game Start – Mouse click on the player paddle will start the game.

     
  4.  
  5.  

    Mouse Movements – Inside the game area (a div), the paddle will follow the y-position of the mouse. Paddle however should not get past the boundaries.

     
  6.  
  7.  

    CPU Paddle – The paddle will follow the ball by moving up/down depending the relative position of the ball. We’ve added a little intelligence by only moving the paddle while ball is coming towards it. This will make the movement as well as the game look more real.

     

Code

NOTE: Put two files ball_small.png , paddle.png (Right-Click "Save As") in the same directory the script is in.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Pong Game In JavaScript</title> <style>
#box
{ width: 500px; height: 300px; margin: auto; border: 5px solid #ccc; position: relative; overflow: hidden;
} .ob
{ position: absolute; border: 0px;
}
</style>
<script type="application/javascript"> // CHANGE THESE, IF REQUIRED
var Speed = 5; // Speed of ball (pixels/step)
var CPUSpeed = 5; // Speed of CPU Paddle (pixels/step) // Short references to objects
var paddle1;
var paddle2;
var ball;
var box;
var msg; // For internal use
var dx, dy; // Speed in x and y directions
var ballX, ballY; // x and y positions of ball
var playerY; // y position of player paddle (x fixed) var cpuY; // y position of CPU paddle (x fixed)
var iID; // To store ID of set interval used to clear it when required // Attach a function to onLoad event
window.onload = Init; // INITIALIZE GAME OBJECTS
function Init()
{ // Make short refrences to objects paddle1 = document.getElementById('paddle1'); paddle2 = document.getElementById('paddle2'); ball = document.getElementById('ball'); box = document.getElementById('box'); msg = document.getElementById('msg'); // Initial values ballX = (box.offsetWidth / 2) - (ball.offsetWidth / 2); ballY = (box.offsetHeight / 2) - (ball.offsetHeight / 2); cpuY = (box.offsetHeight / 2) - (paddle2.offsetHeight / 2); playerY = (box.offsetHeight / 2) - (paddle1.offsetHeight / 2); dx = dy = Speed; paddle1.style.left = 20 + 'px'; paddle1.style.top = playerY + 'px'; paddle2.style.left = box.offsetWidth - (20 + paddle2.offsetWidth) + 'px'; paddle2.style.top = cpuY + 'px'; ball.style.left = ballX + 'px'; ball.style.top = ballY + 'px'; // Show message msg.innerHTML = '<h2>Click on Paddle to Start Game.</h2>';
} // START GAME
function Start()
{ // Attach a function to onmousemove event of the box box.onmousemove = MovePaddle; // Call 'GameLoop()' function every 10 milliseconds iID = setInterval('GameLoop()', 10); msg.innerHTML = '';
} // MAIN GAME LOOP, CALLED REPEATEDLY
function GameLoop()
{ // MOVE BALL ballX += dx; ballY += dy; // See if ball is past player paddle if(ballX < 0) { clearInterval(iID); Init(); box.onmousemove = ''; msg.innerHTML = '<h2>You Loose!<br/>Click on Paddle to Re-Start Game.</h2>'; } // See if ball is past CPU paddle if((ballX + ball.offsetWidth) > box.offsetWidth) { clearInterval(iID); Init(); box.onmousemove = ''; msg.innerHTML = '<h2>You Win!<br/>Click on Paddle to Re-Start Game.</h2>'; } // COLLISION DETECTION // If ball hits upper or lower wall if(ballY < 0 || ((ballY + ball.offsetHeight) > box.offsetHeight)) dy = -dy; // Make x direction opposite // If ball hits player paddle if(ballX < (paddle1.offsetLeft + paddle1.offsetWidth)) if(((ballY + ball.offsetHeight) > playerY) && ballY < (playerY + paddle1.offsetHeight)) dx = -dx; // If ball hits CPU paddle if((ballX + ball.offsetWidth) > paddle2.offsetLeft) if(((ballY + ball.offsetHeight) > cpuY) && ballY < (cpuY + paddle2.offsetHeight)) dx = -dx; // Place ball at calculated positions ball.style.left = ballX + 'px'; ball.style.top = ballY + 'px'; // MOVE CPU PADDLE // Move paddle only if ball is coming towards the CPU paddle if(dx > 0) { if((cpuY + (paddle2.offsetHeight / 2)) > (ballY + ball.offsetHeight)) cpuY -= CPUSpeed; else cpuY += CPUSpeed; paddle2.style.top = cpuY + 'px'; }
} // TO MOVE PLAYER PADDLE ON MOUSE MOVE EVENT
function MovePaddle(e)
{ // Fetch y coordinate of mouse var y = (e.clientY - (box.offsetTop - document.documentElement.scrollTop)); // Here, (box.offsetTop - document.documentElement.scrollTop) will get the relative // position of "box" w.r.t to current scroll postion // If y below lower boundary (cannot go above upper boundary -  // mousemove event only generated when mouse is inside box if(y > (box.offsetHeight - paddle1.offsetHeight)) y = (box.offsetHeight - paddle1.offsetHeight); // Copy position playerY = y; // Set position paddle1.style.top = y + 'px';
}
</script>
</head> <body bgcolor="#fff">
<h1 align="center">Pong Game Example in JavaScript</h1> <div id="box">
<img class="ob" id="paddle1" src="paddle.PNG" onclick="javascript: Start()"/> <img class="ob" id="paddle2" src="paddle.PNG" />
<img class="ob" id="ball" src="ball_small.PNG" /> </div>
<div id="msg" align="center"></div>
</body>
</html>

Related Posts:

  •  

    Moving (Positioning) an Image Using JavaScript

     
  •  
  •  

    Creating a Simple Countdown Timer Using JavaScript II...Using getElementById() Method

     
  •  
  •  

    Creating a Simple Countdown Timer Using JavaScript

     
  •  
  •  

    Creating a Simple HTML Form Validation System Using JavaScript

     
Read full post >>

Moving (Positioning) an Image Using JavaScript

In this post we’re going to learn how we can move an image around using JavaScript. We’ll have four control links (Left, Right, Up, Down) that’ll move the image.

Reading along you’ll learn:

  1. What the absolute and relative positions do
  2.  
  3. How some JavaScript function can be invoked automatically on page load
  4.  
  5. How JavaScript can be used to manipulate the “style” properties of elements
  6.  
  7. How JavaScript can be used to change these properties

Okay, now let’s start!

THEORY

We’re going to have the following elements in the page:

  1. A container (div)
  2.  
  3. An image
  4.  
  5. Control links

Container

The container would be styled to have a size of 500px by 300px. It’d have position: relative which makes anything inside to be positioned with respect to this container. It’s done to make the image move independent of the placement of the container. We’ll also make the overflows from the container to be “hidden”.

Image

The image would be given position: absolute which means it can be positioned with absolute (left (x), top (y)) values. Normally images (like other elements) are positioned, aligned, wrapped accordingly with other elements. The absolute position however, gives us the power to place the image (or other element) freely.

Control Links

Control Links  will be used to invoke the functions to move the image in the respective directions.

Misc.

The functions being called by the Control links will manipulate the position of the image using one document.getElementbyId() function.

This function is used to reference elements in the document uniquely by using their IDs (which are supposed to be unique for each element). The style properties of elements are referenced as:

document.getElementById(<ID>).style.<STYLE-NAME>

We’ll be using the onload event of the body element to invoke the Init() function initially on page load.

<body onload="javascript:Init()">

WORKING

When the page loads, the function Init() is getting called which sets the initial position of the image.

When a control link is clicked, the respective coordinate (x or y) is modified and the new value is set in the following line:

document.getElementById('img1').style.left = x + 'px';

document.getElementById('img1').style.top = y + 'px';

CODE

 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JavaScript: Moving an Image</title>
<script type="application/ecmascript"> // --CHANGE THESE IF REQUIRED--
// Initial x-position of image
var x = 200;
// Initial y-position of image
var y =100;
// Pixels to move in each step
var inc = 10; function Init()
{ document.getElementById('img1').style.left = x + 'px'; document.getElementById('img1').style.top = y + 'px';
}
function moveRight()
{ x += inc; document.getElementById('img1').style.left = x + 'px';
} function moveLeft()
{ x -= inc; document.getElementById('img1').style.left = x + 'px';
} function moveUp()
{ y -= inc; document.getElementById('img1').style.top = y + 'px';
} function moveDown()
{ y += inc; document.getElementById('img1').style.top = y + 'px';
}
</script> <style>
#box
{ width: 500px; height: 300px; position: relative; margin: 20px auto 0px auto; border: 5px outset #000; overflow: hidden;
} .image
{ position: absolute; z-index: 100;
}
</style>
</head<body onload="javascript:Init()">
<div id="box"><img class="image" id="img1" src="ball.png"/></div>
<a href="javascript:moveLeft()">Left</a>
<a href="javascript:moveUp()">Up</a>
<a href="javascript:moveDown()">Down</a>
<a href="javascript:moveRight()">Right</a>
</body>
</html>

NOTE: An image with name "ball.png" must be there in the same directory as this file for the above ocde to work "as-is".

Related Posts:

  •  

    Creating a Simple Countdown Timer Using JavaScript II...Using getElementById() Method

     
  •  
  •  

    Creating a Simple Countdown Timer Using JavaScript

     
  •  
  •  

    Creating a Simple HTML Form Validation System Using JavaScript

     
Read full post >>

Image Generation Using PHP

In one of the previous posts about CAPTCHA Image Generation we made use of PHP’s image generation functions but didn’t discuss about them. So, if you had any problems or just want to know more, read on.

Creating and outputting images from PHP is very simple and easy. And since PHP supports images in a number of different formats you can very easily generate images in various formats such as JPEG, PNG, GIF etc. Generating  images involves the following steps:

  1. Creating a canvas.

  2. Drawing

  3. Outputting the image.

Now, let’s look at each of the steps in detail.

Creating a Canvas

Creating a canvas is very easy, just use the following function:

resource ImageCreateTrueColor int $width int $height )

The capitalization doesn’t matter as with any function in PHP.

If you want your canvas to have some background color (default is black) you can use the following function:

bool ImageFill resource $image int $x int $y int $color )

Where color is to be first allocate using the following function:

int ImageColorAllocate resource $image int $red int $green int $blue )

You can also use an existing image as base canvas for your new image, in that case create your image using the following function:

resource ImageCreateFromJPEG string $filename )

Images in other format can also be used, for PNG →  ImageCreateFromPNG (), GIF → ImageCreateFromGIF ().

Drawing

After having set up the canvas, let’s draw something on it, say, a rectangle. The rectangle drawing function with its argument list is:

bool ImageRectangle resource $image int $x1 int $y1 int $x2 int $y2 int $color )

For allocating color use the ImageColorAllocate() function.

The following will create a square of size 10px X 10px having a blue border:

$img ImageCreateTrueColor(20, 20);
$blue ImageColorAllocate($img00255);
ImageRectangle($img, 0, 0, 10, 10$blue);

You can browse the complete list of drawing (GD) functions in PHP here .

Some of the common ones are:

  1. bool ImageLine ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color )
  2. bool ImageEllipse resource $image int $cx int $cy int $width int $height int $color 
  3. bool ImageArc resource $image int $cx int $cy int $width int $height int $start int $end int $color )

I think we should also discuss a little about one function, to draw text on out image, it’s called the ImageString() function having the following form:

bool ImageString resource $image int $font int $x int $y string $string int $color )

Example:

$img ImageCreateTrueColor(100, 100);
$red ImageColorAllocate($img25500);
ImageString($img7, 10, 10'Text'$red);
ImageString($img, 510, 30'Smaller Text'$red);

The above lines will draw two string of text and the first one will have a bigger font size. Higher number fonts (for $font) are bigger.

All done,now we have a completed image that just needs to be sent to the browser. For this we first need to tell the browser what type of content we’re going to send and the data (image) itself. The following two lines will do this:

header('Content-Type: image/png');
ImagePNG($img);

Similarly you can output image in other formats also, just replace ImageJPEG with ImageGIF or ImagePNG etc. and the content-type header to image/gif or image/png accordingly.

After having output the image there is one more thing we should take care of-freeing up the resources. You know images can take up significant amount of resources which may affect the server and other scripts running on it, so always use the following function:

bool ImageDestroy resource $image )

The following example code illustrates all, what we have learnt:

<?
/********************************************************
 * DESCRIPTION: Exmple program to illustrate            *
 *              image generation using PHP.             *
 * AUTHOR:      Arvind Gupta                            *
 *              (http://www.arvindgupta.co.in)          *
 * DATE:        21-Mar-09                               *
 * WEBSITE:                                             *
 * http://learning-computer-programming.blogspot.com/   *
 ********************************************************/
// Set width and height
$width 200;
$height200;
// Create canvas
$img ImageCreateTrueColor($width$height);
// Allocate colors
$gray ImageColorAllocate($img200200200);
$red ImageColorAllocate($img25500);
$green ImageColorAllocate($img02550);
$blue ImageColorAllocate($img00255);
// Fill background color
ImageFill($img00$gray);
// Draw
ImageRectangle($img55, ($width 5), ($height 5), $red);
ImageLine($img5, ($width 5), ($height 5), $red);
ImageEllipse($img, ($width 2), ($height 2), ($width 10), ($height 10), $green);
ImageArc($img, ($width 2), ($height 2), ($width 40), ($height 40), 180 360$blue);
ImageArc($img, ($width 2), ($height 2), ($width 60), ($height 60), 180$green);
ImageString($img7, ($width 2) - 50, ($height 2) - 10'Image Created'$red);
ImageString($img7, ($width 2) - 30, ($height 2) + 10'Using PHP'$green);
// Output
header('Content-Type: image/png');
ImagePNG($img);
// Free-Up
ImageDestroy($img);
?>

NOTE: You need to enable the “gd2” extension from “php.ini” for all this to work. See Installing/Configuring Image Support in PHP for more information.

Okay, end of this post. Keep checking back for more.

Read full post >>

How CAPTCHA Works? And a Simple Script in PHP

[For this post I'm presuming that you are familiar with CAPTCHA, if not please read this  Introduction to CAPTCHA ]

Today we are going to see how CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) works and how it minimizes automatic sign-up of form s . We will also be creating a simple CAPTCHA script in PHP to illustrate this.

Basically CAPTCHA works in the following manner:

  1. Create Random Value: Some random string is generated, random values are often hard to guess and predict.

  2. Generate an Image: Images are used as these are generally a lot harder to read for computers while being nice and readable to humans. This is also the most important step as simple text in images can be read (and CAPTCHA cracked) quite easily. To make it difficult for them, developers employ different techniques so that the text in the image becomes hard to read for computers. Some create zig-zag lines for background while others twist-and-turn individual characters in the image. Possibilities are many and new techniques are being developed all the time as crackers are always into finding ways to break them.

  3. Store it: The random string generated (which is also in the image) is stored for matching the user input. The easiest way to do so is to use the  Session variables .

  4. Matching: After the above step, the CAPTCHA image is generated and shown on some form which we want to protect from being abused. The users fills in the form along with the CAPTCHA text and submits it. Now we have the following:

    1. All submitted form data.

    2. CAPTCHA string (from form), input by user.

    3. CAPTCHA string (real one, generated by us), from session variable. Session variable is generally used as it can keep stored values across page requests. Here, we needed to preserve stored values from one page (form page) to another (action page-that receives form data).

  5. If both match, it's okay otherwise not, in that case we can give the user a message that the CAPTCHA they had entered was wrong and their form could not be submitted. You could also ask them to verify it again.

The following image might illustrates this better:


How CAPTCHA is Generated and Matched

From the above image it's quite clear that when someone requests the form page, the CAPTCHA text is generated and sent back to requesting user, but only in the form of an image. If the requester is a human he'd not have much difficulty reading the image and inputting the text when asked but if it's a bot it might face difficulties guessing whats in the image. In the next step when we match the string generated and the one the user had input, we can restrict automated form submissions.

The following is the code that does this, it'll just output the CAPTCHA image to the browser when the script is requested:

<?php
/********************************************************
 * File:        captcha.php                             *
 * Author:      Arvind Gupta (www.arvindgupta.co.in)    *
 * Date:        12-Mar-2009                             *
 * Description: This file can be embedded as image      *
 *              to show CAPTCHA/                        *
 ********************************************************/
// The number of characters you
// want your CAPTCHA text to have
define('CAPTCHA_STRENGTH', 5);
/****************************
 *        INITIALISE        *
 ****************************/
// Tell PHP we're going to use
// Session vars
session_start();
// Md5 to generate the random string
$random_str md5(microtime());
// Trim required number of characters
$captcha_str substr($random_str, 0, CAPTCHA_STRENGTH);
// Allocate new image
$width = (CAPTCHA_STRENGTH * 10)+10;
$height 20;
$captcha_img =ImageCreate($width$height);
// ALLOCATE COLORS
// Background color-black
$back_color ImageColorAllocate($captcha_img000);
// Text color-white
$text_color ImageColorAllocate($captcha_img255255255);
// Line color-red
$line_color ImageColorAllocate($captcha_img25500);
/****************************
 *     DRAW BACKGROUND &    *
 *           LINES          *
 ****************************/
// Fill background color
ImageFill($captcha_img00$back_color);
// Draw lines accross the x-axis
for($i = 0; $i <
$width; $i += 5)
    
ImageLine($captcha_img, $i, 0, $i, 20, $line_color);
// Draw lines accross the y-axis
for($i = 0; $i < 20; $i += 5)
   
ImageLine($captcha_img, 0, $i,
$width, $i , $line_color);
/****************************
 *      DRAW AND OUTPUT     *
 *          IMAGE           *
 ****************************/
// Draw the random string
ImageString($captcha_img552$captcha_str$text_color);
// Carry the data (KEY) through session
$_SESSION['key'] = $captcha_str;
// Send data type
header("Content-type: image/jpeg");
// Output image to browser
ImageJPEG($captcha_img);
// Free-Up resources
ImageDestroy($captcha_img);
?>

Okay, this it for this, in the next one we'll integrate this CAPTCHA script into one form and see how it works. Till then goodbye!

Read full post >>

Generating XML Feeds (RSS, Atom) Using PHP

RSS/ATOM feeds are very common these days and almost all Content Management Systems (CMS) can generate it. But in the case when you want to generate it yourself or just want to learn how you can, read on!

Both RSS and ATOM feeds are written in eXtensible Markup Language (XML) standard markup. Not just standard markups, you also need to be sure of what and how you put data in those markup elements (tags). For all this refer to the feed specifications of RSS and ATOM . XML itself is very strict and the standard specifications makes it even harder to generate valid feeds. And moreover, why re-invent the wheel when we can have it – ready-made.

The solution I'm referring to here is, to use a third-party Library – Universal FeedWriter. FeedWriter is a PHP class written by Anis uddin Ahmad that can dramatically  ease-off feeds (both RSS and Atom) generation. You can download this library from  here .

Every feed should have at least the following data:

  1. Feed title
  2.  
  3. URL(of the website whose feed is it)
  4.  
  5. Description
  6.  
  7. Item
  8.  
    1. Title
    2.  
    3. Date
    4.  
    5. URL (of the item, sometimes called permalink)
    6.  
    7. Description (body of the item)
    8.  

The RSS feed for this will look something like:

<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:wfw="http://wellformedweb.org/CommentAPI/">
<channel>
<title>RSS Title</title>
<link>URL of Website</link>
<description><![CDATA[Description]]></description>
<language>en-us</language>
<pubDate>Sat, 07 Mar 2009 06:55:15 +0530</pubDate>
<item>
<title>Item Title</title>
<link>Item URL (Permalink)</link>
<pubDate>Sat, 07 Mar 2009 06:55:15 +0530</pubDate>
<description><![CDATA[Item Description]]></description>
</item>
</channel>
</rss>

Using FeddWriter abstracts working with and generating XML tags manually, you just tell FeedWriter what kind of Feed (RSS/Atom and version) you want; give it the data you want your feed to have and you’re done! The following code snippet shows you how exactly:

<?php
// Include the class
include("FeedWriter.php");
// Creating an instance of FeedWriter class.
// The parameter tell what type of
// feed you want.
$MyFeed = new FeedWriter(RSS2);
// Setting feed elements
$MyFeed->setTitle('My RSS Feed');
$MyFeed->setLink('http://www.example.com');
$MyFeed->setDescription('Test feed generated by Universal FeedWriter.');
$MyFeed->setChannelElement('pubDate'date(DATE_RSStime()));
// Create a FeedItem.
$Item $MyFeed->createNewItem();
// Add elements to the feed item.
$Item->setTitle('Item Title');
$Item->setLink('http://www.example.com/item1.html');
$Item->setDate(mktime(10,20,0,3,6,2008));
$Item->setDescription('Item Description. Can contain <b>HTML</b>.');
// Now add the item to the feed.
$MyFeed->addItem($Item);
// Now genarate the feed.
$MyFeed->genarateFeed();
?>

So you see how easy it is to generate a feed with the data we had.

Feeds generally don’t just have one item so let’s see something more real. The following code will generate a feed having ten items:

<?php
include("FeedWriter.php");
$MyFeed = new FeedWriter(RSS2);
$MyFeed->setTitle('My RSS Feed');
$MyFeed->setLink('http://www.example.com');
$MyFeed->setDescription('Test feed having Ten Items.');
$time mktime(10100352009);
$MyFeed->setChannelElement('pubDate'date(DATE_RSS$time));
for(
$i=0$i<10$i++)
{
    
$Item $MyFeed->createNewItem();
    
$Item->setTitle('Item' . ($i 1) . ' Title');
    
$Item->setLink('http://www.example.com/item' . ($i 1) . '.html');
    
// Have different dates for each item
    // Each will have one day gap for the
    // publishing time
    
$Item->setDate($time - ($i * (24 * (60 60))));
    
$Item->setDescription('Item ' . ($i+1) . ' Description.');
    
$MyFeed->addItem($Item);
}
$MyFeed->genarateFeed();
?>

One thing to note here is why we are using the feed’s generation time to be same as  that of the latest item rather than the current time when it is generated well, it’s because the feed gets updated only as and when new items are added (remains same at other time) and at the very same time. Therefore just because the feed is being generated dynamically at each request doesn’t mean it is “generate” at that time.

Read full post >>

Geany - A Good Web Development Editor (IDE)

Geany Homepage

Last year I finally made a switch to GNU/Linux as my operating system and had been in search of a good editor for my web development. In Windows I used Dreamweaver for the purpose and was quite happy with it. It could can easily highlight PHP, HTML, JavaScript and other codes of some other languages related to web. It can also do some Auto-Completion – a feature I think is a must-have. I also liked the fact that it (version MX) was reasonably light on system resources.

When I switched to Linux, I tried Bluefish, Komodo Edit, Netbeans IDE. Bluefish (ver 1.0.7) had  a  bad syntax highlighting feature besides other things I found to be quite irritable (working with PHP files, at least). Komodo Edit and Netbeans stood out especially Komodo Edit, in terms of functionality, usability and other small-small things. But still these were not what I was looking for. I wanted something good in terms of functionality but at the same time light on resources (Komodo Edit took about 15 seconds to load). I wanted something that had a good balance between features and memory footprint.

Geany is small (source package is about 2.2 MB), light on resources and at the same time loaded with functionality and ease of use for the size. Geany does not have all the features of a full-fledged IDE (like for example Komodo Edit) but it has got many of the important ons. And it's not just PHP and web development that you can use it for, it has support for a good number of languages (programming, scripting etc). But as I've only used it for web development, I'm strictly talking in that context throughout.

Here are some of the features I find very helpful:

  1.  

    AutoComplete: For functions(inbuilt as well as user-defined), variables, classes etc. Inbuilt functions are shown with their argument list-very useful. And there's but only a few functions I couldn't find in its database. Just type in a few characters and it shows a nice drop-down list of suggestions, select one and it shows the function's parameters list and their types. TIP: By default you need to type in at least three characters for it to give you suggestions for AutoComplete(ion) but it can be changes from Edit-> Preferences-> Edit(Side-Tab)-> Completions(Tab). I personally have set it to be 1.

     
     
  2.  
  3.  

    Compile and Make: You can't “make” a PHP script but compile is damn good a feature. Now forget refreshing the browser. NOTE: Can only check syntax errors.

     
     
  4.  
  5.  

    Code-folding: Another useful feature especially for lengthy scripts.

     
     
     
  6.  
  7.  

    Auto-Closing: Can close (X)HTML tags, parenthesis, curly braces, quotes etc. for you. Check Edit->Preferences->Edit(Side-Tab)->Completions(Tab) for settings.

     
  8.  
  9.  

    Sidebar: These are many tabs in the sidebar but one of them particularly stands ot. The one which displays “Symbols” in the document-variables, functions, classes, objects, constants tec. This one reminds me of the commercial IDEs such as Visual Studio. Just click on something to find its declaration.

     
     
  10.  
  11.  

    Sessions: Just like Firefox can restore sessions of open tabs(websites), Geany can restore session of files. If I'm working on, say, ten files and I decide to go take a bath. I can close and shutdown my PC because Geany will open all the files for me the next time I run it. Great!

     
  12.  
  13.  

    Pre-defined Comments: Whether you want to insert copyright note or license information or just function information. Just right click and and got to “Insert Comments” menu, you have them just a click away! There also exist a  feature for inserting current date and time, for that go to “Insert Date” from the right -click menu. Useful!

     
     

     
  14.  
  15.  

    Windows Version: Don't want to switch to Linux yet! No problem! Just download the windows version (needs GTK libraries installed)

     
  16.  
  17.  

    In spite so many useful features there is one more thing I expect Geany to do – better support for HTML files. Look, PHP and HTML go hand-in-hand and I'd have loved to have HTML preview feature like Dreamweaver has. We often embed PHP in HTML pages and Dreamweaver works perfectly well for these kind of pages. This is where I miss my old Dreamweaver the most.  I'm not saying this is Geany's short-coming as it's designed not just for web development, but when you do web development you'll  feel it's missing.

     

Some might wonder why I'm always mentioning Dreamweaver. This is because unlike some of the editors I've used, it isn't just restricted to HTML pages-it can handle dynamic content as well. Web development isn't just HTML or PHP or ASP, it's a mix which Dreamweaver handles quite well. It's a great HTML editor as well as it's a quite-great PHP editor, this is what I love about it.

Geany Homepage
Geany Download Page

Read full post >>

Generating XHTML MP (WAP 2.0) Pages From PHP

Maybe you guys know that I've been working on a service called MyWapBlog.com which lets peoples create/manage mobile blogs using their mobile phones. In the course of the development I've learnt great deal about mobile websites and their dynamic generation, and I'm sharing a bit of it here in this post.

How do you generate dynamic (X)HTML Pages using PHP? Simple:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"  dir="ltr">
<head>
<title>Sometitle</title>
</head>
<body>
<h1>Hello</h1>
<p><?php echo date('h:i A, j-M-y'); ?></p>
</body>
</html>

And if you look at XHTML MP pages, their source look like the following:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
...
...

So you see these pages have a different document type and some other differences. So will the following code work and generate a valid WAP 2.0 page?:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Sometitle</title>
</head>
<body>
<h1>Hello</h1>
<p><?php echo date('h:i A, j-M-y'); ?></p>
</body>
</html>

The answer is “NO”? Why? Because XHTML MP pages needs to be served with a different Content-Type than what is generated by .PHP files. Normally when you runa s PHP script and it outputs something, the content is served with Content-Type: text/html

What is Content-Type?

It is a header (information about a particular resource) returned to browser when it requests something from a server. When you request an image, the server return the image with the header image/png, image/jpeg etc. letting the browser know how the returned content is to be interpreted.

PHP scripts can return contents of any type (using the header() function), from text to images and PDFs to ZIPs. And therfore if we want to generate  XHTML MP pages, it can even do that without doubt.

So what we need to do is, just change the above code a bit adding a new line at the top so that the whole code look like the following:


<?php header("Content-type: application/vnd.wap.xhtml+xml; charset=UTF-8");?>

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Sometitle</title>
</head>
<body>
<h1>Hello</h1>
<p><?php echo date('h:i A, j-M-y'); ?></p>
</body>
</html>

This will tell the browser that the content we are going to serve is of the type XHTML MP. We always use the charset UTF-8 for these pages, which is also told to the requesting browser.

Now the big question is, why we didn't do this for normal HTML pages. Why didn't we have to tell the browser that content is of the type “text/html” when it was so? Because PHP does it for us! Yes whenever we output anything from PHP scripts, the PHP interpreter outputs the default header (text/html) automatically. Just as the PHP  interpreter finds anything in the script that needs to be output, it first generates a header, the outputted content follows. For example in the first script, the very first line (very first character “<”) needs to be output to the browser. So before that, the PHP interpreter sends a content type header (default – text/html).

Therefore, when we had to output our content with a different header we had to make sure that it is done before PHP does it automatically. Two headers  cannot be valid.

This is it for this post, do check back soon for more new posts. Till then, good bye!

Read full post >>

Custom Tags Parsing Using Regular Expressions

In the last post, we had created a simple custom tag parsing script using PHP string functions. In this post, we are going to continue our discussion on custom tag parsing but rather using Regular Expressions. Here we will see how regular expressions can used to parse strings, we will also see where to and where not to use Regular Expressions. Before continuing, I expect that you have a working knowledge of Regular Expressions if not please first check out this websites .

Let us first create the previous custom tag parsing script using expressions:

<form name="form1" method="get" action="">
  <p>
    <!-- textarea should display previously wriiten text --> 
    <textarea name="content" cols="35" rows="12" id="content"><? if (isset($_GET['content'])) echo $_GET['content']; ?></textarea> 
  </p>
  <p>
    <input name="parse" type="submit" id="parse" value="Parse">
  </p>
</form>
<?
if(isset($_GET['parse'])) 
{
    
$content $_GET['content'];
    
//convert newlines in the text to HTML "<br />" 
    //required to keep formatting (newlines)
    
$content nl2br($content);
    
    
//PHP function 'eregi_replace' replaces all occurences of the expression with the one mentioned 
    //'\\1' is the string matched (one in parentheses '()' in the regular expression
    //it's a 'eregi_replace' thing not PHP's 
    
$content eregi_replace('\.b\.(.+)\./b\.''<strong>\\1</strong>'$content);
    
$content eregi_replace('\.i\.(.+)\./i\.''<i>\\1</i>'$content); 
    
    
//now the variable $content contains HTML formatted text
    //display it
    
echo '<hr />'
    echo 
$content;
}
?>

 But should we use regular expressions here, answer is NO, because, first regular expressions run slower and they add a fair bit of complexity where the same thing could have been done easily using just string functions.

The reason for me staring this post with something contradicting to the theme of the post is because people tend to avoid regular expressions thinking that the same thing can be done otherwise (I just gave them one more chance!). Well it may be case sometimes but in many other cases where complex string manipulation is required with efficiency there is but one choice, regular expressions. The next example will illustrate this.

For this example we will parse ‘*’ (asterisk) and ‘_’ (underscore) for bolding and italicizing text (as in Google Talk / IM applications). The following text:

Hello *World*. Hello _World_.

Will be parsed and displayed as:

Hello World. Hello World.

It is quite obvious that both tags’ start and end tags are the same. Now let us see how this can be implemented (using regular expressions).

<form name="form1" method="get" action="">
  <p>
    <!-- textarea should display previously wriiten text --> 
    <textarea name="content" cols="35" rows="12" id="content"><? if (isset($_GET['content'])) echo $_GET['content']; ?></textarea> 
  </p>
  <p>
    <input name="parse" type="submit" id="parse" value="Parse">
  </p>
</form>
<?
if(isset($_GET['parse'])) 
{
    
$content $_GET['content'];
    
//convert newlines in the text to HTML "<br />" 
    //required to keep formatting (newlines)
    
$content nl2br($content);
    
    
//match anything between the tags but not the tag itself 
    //otherwise '*hello* world *hello*'
    //will be print 'hello* world *hello' in bold
    //and not 'hello(in bold) world hello(again in bold)' 
    
$content eregi_replace('\*(.[^*]+)\*''<strong>\\1</strong>'$content);
    
$content eregi_replace('\_(.[^_]+)\_''<i>\\1</i>'$content); 
    
    
//now the variable $content contains HTML formatted text
    //display it
    
echo '<hr />'
    echo 
$content;
}
?>

If we try to implement this using string functions it will take quite a lot more lines of extra coding but I leave that to you.

Previous Posts:

  •  

    Basic “Custom Tags” Parsing Script

     
  •  
  •  

    Simple File Uploading Script in PHP 

     
  •  
  •  

    Creating a Simple Countdown Timer Using JavaScript II

     
  •  
  •  

    Creating a Simple Countdown Timer Using JavaScript 

     
  •  
  •  

    Evaluating/Executing PHP Code at Run-Time Using eval() Function

     
Read full post >>

Basic "Custom Tags" Parsing Script

Today we are going to create a basic Custom Tags parsing script that will parse special symbols (tags) in text for formatting purpose. Just like writing <b>BOLD</b>, a web browser parses it as “BOLD” in bold letters, same way our script will parse tags created by us. One very popular example of custom tag parsing for formatting purpose is, BBCode which most of the bulletin boards use to let users format their posts.

This will be a basic example of parsing custom tags so we will only be parsing two tags. One will convert the enclosing text into bold and other will be used for italics. After understanding the basic idea, you can easily add more tags according to your needs and can also use it wherever necessary. One of its good use will be in Shout Boxes that we had designed a few months back.

Though many would like the use of Regular Expressions for parsing, we will not be using them here. For the sake of simplicity, we will be using only the basic string manipulation functions available in PHP.

If you look at the code below, you can see an array (2D) holding our custom tags. Here we’ll be having four information for each tag. Start tag, end tag (both defined by us), HTML start tag and HTML end tag. To make this more clear, let’s suppose we want to parse the text “[b]Text[/b]” so that it’s displayed as “Text” in bold. Our start (custom) tag will be [b], end tag will be [/b], HTML start tag will be <b> and HTML end tag will be </b>.

As we will be parsing two different custom tags, we have eight elements in the array. If you want to add more tags, add four elements for each tag, just like the way the others are. No need to change anything else.

The code:

<form name="form1" method="get" action="">
  <p>
    <!-- textarea should display previously wriiten text --> 
    <textarea name="content" cols="35" rows="12" id="content"><? 
if (isset(
$_GET['content'])) echo $_GET['content']; ?></textarea> 
  </p>
  <p>
    <input name="parse" type="submit" id="parse" value="Parse">
  </p>
</form>
<?
if(isset($_GET['parse'])) 
{
    
$content $_GET['content'];
    
//convert newlines in the text to HTML "<br />" 
    //required to keep formatting (newlines)
    
$content nl2br($content);
    
    
/* CUSTOM TAGS
    -----------
    */ 
    //For Tag 1
    
$tag[0][0] = '[b]';
    
$tag[0][1] = '[/b]'
    
$tag[0][2] = '<strong>';
    
$tag[0][3] = '</strong>'
    
//For Tag 2    
    
$tag[1][0] = '[i]';
    
$tag[1][1] = '[/i]'
    
$tag[1][2] = '<i>';
    
$tag[1][3] = '</i>'
    
//count total no. of tags to parse
    
$total_tags count($tag); //2 for now 
    
    //parse our custom tags adding HTML tags instead
    //which a browser can understand
    
for($i 0$i<$total_tags$i++) 
    {    
        
$content str_replace($tag[$i][0],$tag[$i][2],$content); 
        
$content str_replace($tag[$i][1],$tag[$i][3],$content); 
    }
    
    
//now the variable $content contains HTML formatted text
    //display it
    
echo '<hr />'
    echo 
$content;
}
?>

The code is pretty straightforward. Isn’t it!

Previous Posts:

  •  

    Simple File Uploading Script in PHP 

     
  •  
  •  

    Creating a Simple Countdown Timer Using JavaScript II

     
  •  
  •  

    Creating a Simple Countdown Timer Using JavaScript 

     
  •  
  •  

    Evaluating/Executing PHP Code at Run-Time Using eval() Function

     
  •  
  •  

    Blogger: Changing Templates without Loosing Widget

     
Read full post >>

Simple File Uploading Script in PHP

PHP is undoubtedly the best programming language when it comes to web programming. It gives us so many features and capabilities, a few of which we’ve discussed already. So continuing with that, today we’ll see how we can use a few lines of code to create a script that’d allow file uploading right from the web browser. File upload feature is definitely useful kinds of website but at the same time very much vulnerable to malicious attacks as well. So use it with a LOT of precautions!

For this example, we’ll need a front-end web page that’ll accept the file from the user and a backend script to process and store the file. Let’s look at the codes of each:

upload.html:

 <html> <body> <form action="upload_file.php" method="post" enctype="multipart/form-data"> <label for="file">Filename:</label> <input type="file" name="file" id="file" /> <br /> <input type="submit" name="submit" value="Submit" /> </form> </body> </html> 

Here we have a HTML form that calls the script on submission. The method of data sending should be “POST” and there should be and enctype as “multipart/form-data” which means we can upload binary form data. The input type “file” opens the File Input Box that’d let the user browse for the file. The submit button “Upload” submits the form as usual.

upload_file.php:

<?php if ($_FILES["file"]["error"] > 0)     echo "Error:: " $_FILES["file"]["error"] . "<br />"; else {     if (file_exists($_FILES["file"]["name"]))     {         echo $_FILES["file"]["name"] . " already exists. ";     }     else     {         move_uploaded_file($_FILES["file"]["tmp_name"], $_FILES["file"]["name"]);         echo "File <b>" $_FILES["file"]["name"] . "</b> uploaded successfully!";     } } ?>   

Just like we had POST form data in $_POST[] and GET data in $_GET[] array same way to have files sent to script we use $_FILES[] array.

  •  

    $_FILES["file"]["error"]: Tells us if there is any error in uploading. Note that “file” the first string index of the array is the name of the “File” input type from the HTML form.

     
  •  
  •  

    $_FILES["file"]["tmp_name"]: All the files sent to any script is stores in a temporary directory by PHP, this tells us the location of that temporary file.

     
  •  
  •  

    $_FILES["file"]["name"]: It tells us the name of the file on the users’ computer.

     
  •  
  •  

    move_uploaded_file(): As files sent to scripts are just stored temporarily, we have to save it to some place, for this we use this PHP function. It’s first parameter is the temporary file location and second is the place we need to store the file and with what name. We are storing it to the same directory the script is in and with name same as on the users’ computer.

     

NOTE: This is just meant for example purpose and you shouldn’t have this on your server as it is an open invitation to hackers/spammers. If you need upload facility on your website in all the cases you should have some kind of  authentication system that'd only allow registered users to upload anything. you should also accept only certain file types. you wouldn't like someone uploading/running spamming script off your server. Would you? there may be a few other precautions that you may need to take depending on the purpose you intend to use the script for.

Previous Posts:

  •  

    Creating a Simple Countdown Timer Using JavaScript II

     
  •  
  •  

    Creating a Simple Countdown Timer Using JavaScript 

     
  •  
  •  

    Evaluating/Executing PHP Code at Run-Time Using eval() Function

     
  •  
  •  

    Blogger: Changing Templates without Loosing Widget

     
Read full post >>

Finally a Blogging Platform for the Mobile Web (WAP)

Most of the time I browse internet for reading blogs, checking emails etc. I do it on my cell phone. One day I thought why not create a mobile website or better yet blog, and started searching around. What did I find? Well, nothing much useful. In this big world and yet bigger web, to my disappointment, I couldn’t find any website offering free blogs like we do on the normal (desktop) web. Moreover, those that offered mobile websites, I just didn’t like their service. You just have to spend so much time to just have a single page up!

What I had in my mind was a service that’d offer free blogs, let me register it from the mobile phone, let me post from the mobile phone, in other words a service that’d let me operate the whole thing right from the mobile phone itself. Days passed and then, rather than me wanting these services I thought of offering them to others instead, of course for FREE. Therefore I took a nearly a month off and created what I wanted myself. Here it is MyWapBlog.com (You need a mobile phone to access it. Not accessible form desktop browsers except Opera, and FireFox with addon )

A picture is worth a thousand words, here area a few of them:


 MyWapBlog.com Homepage


 Registration Page - You'll get your blog at your-name.mywapblog.com


After registration/logging in you'll see your dashboard like shown above


 Your blog looks like this using the "Default-2" theme


 You can choose between the three themes available now for your blog's layout. More themes will be added soon.

While I’ve sorted most of the bugs that I could find in ten-days testing period, there might (sure) still be quite a few of them. Therefore, the only thing I’d like to ask for is to use the Feedback Form (on Dashboard Page) a lot!

Thanks a lot for reading! Go get your Free Wap Blog Now!

Read full post >>

Designing a Simple HTML Code & Preview Tool (Online)

With online CMSs everywhere and craze of blogging like never before, we see some sort of online HTML editors everywhere. Ever blogged or posted in some forum? Most of them have it! These editors let you write, format, preview and tinker with the HTML code before publishing anything. Most of them have a nice UI to format everything much like the desktop applications like NVu, Dreamweaver etc. these online editors also let you manually change or write HTML code that can be previewed without leaving the page.

Well what we are going to design today is a scaled down version (say simple) of these kinds of editors. It’d let you write (or paste) HTML code and preview how it’d look. What it wouldn’t let you do is to format or change anything while in the preview mode. We will be using HTML, JavaScript and a little inline CSS.

Basic Theory

If you look at the HTML editors used by Blogger and Wordpress, they have two modes, Code and Compose. In code mode HTML code is displayed which can also be edited. On the other hand in compose mode, preview of the code is displayed which can be edited/formatted using its GUI. Interesting thing here is that both the mode displays in the same place, giving a feeling that the same code box is changing to the Compose box.

For our purpose, we can use a HTML textarea for code view and an iframe for preview. Iframe is the simplest way of showing HTML preview that could also be made to work in edit mode, therefore letting us format things using the UI and see the code in code view.

Working

From the staring both the textarea and the iframe are placed in the page. Textarea is be styled to be visible (display: block;) and the iframe to be invisible (display:none;). When you type in some code in the code view (textarea) and switch to preview mode, a JavaScript function is called that makes the textarea invisible an the iframe visible. It also places the code (form the textarea) as HTML for the iframe, which in turn displays the code as it’d in a browser. Again when you switch back to code view, textarea is made visible again and the iframe invisible. If we give both the textarea and iframe the same look, it’d give the feeling that the same box is being used to show code as well as preview.

The button’s value is also changed to reflect which mode we are in and clicking it would result in which view.

Code

 <html> <head> <title>Code & Preview</title> <script language="JavaScript" type="text/JavaScript"> //flag to store current state of view (code or preview) var flag=1; //var to store code forom the textarea var val1=''; function changeMode() { //store code from the textarea val1=document.form1.code.value; //check which view we are in if (flag==1)//code view { //set textarea to be invisible //notice how style property is accessed document.getElementById('code').style.display = "none"; document.getElementById('preview').style.display = "block"; //give the iframe the HTML code to display //note how an iframe's properties are accessed //is's because an iframe is a seperate window itself document.getElementById("preview").contentWindow.document.body.innerHTML=val1; //rename the button document.getElementById('submit').value = "Code"; flag=2; } else { document.getElementById('preview').style.display ="none"; document.getElementById('code').style.display ="block"; document.getElementById('submit').value = "Preview"; flag=1; } } </script> </head> <body> <form name="form1" method="post" action=""> <p id="textb"> <iframe style="display: none" id="preview" width="600px" height="300px" scrolling="auto"></iframe> <textarea style="display: block;width:600px; height:300px" name="code" id="code"></textarea> </p> <p> <input id="submit" type="button" name="Submit" onClick="changeMode()" value="Preview"> </p> </form> </body> </html> 

Previous Posts:

  •  

    Creating a Simple Countdown Timer Using JavaScript II

     
  •  
  •  

    Creating a Simple Countdown Timer Using JavaScript 

     
  •  
  •  

    Evaluating/Executing PHP Code at Run-Time Using eval() Function

     
  •  
  •  

    Blogger: Changing Templates without Loosing Widgets

     
  •  
  •  

    How Do I Color-Highlight PHP Source Codes

     
Read full post >>

Creating a Simple Countdown Timer Using JavaScript II...Using getElementById() Method

Speaking of yesterday’s post, it had the following problems:

1. It could not easily be embedded into an existing page.
2. It could not be placed wherever we wanted it to be nor it could be aligned or styled easily.
3. Rather than updating the same number to countdown it showed a series of numbers as countdown proceeded.

Well all these problems can easily be solved by one of JavaScript’s powerful method getElementById(). This is documents’s method which can be used to access HTML entities within JavaScript with the help of their IDs (which is unique).

For example we can access the HTML entity and its values etc. with the ID one as:

document.getElementById("one") 

 The HTML object may be defined like below:

<p id="one">some text</p>

You get!

OK, how can this be used to solve our problems, let’s see.

As we know, the HTML entities such as <p>,<div>, <span> etc. can be placed anywhere very easily. They can also be styled and aligned perfectly. So if we could print the timer in one of these, it’d be the most efficient technique. How? Using getElementById().

The body of tags such as <p>, <div> or <span> can be accessed via JavaScript as:

document.getElementById("one").innerHTML 

 e.g.: If we execute the following code:

document.getElementById("one").innerHTML="hello!!";

 it’d be same as having the following HTML tag:

<p id="one">hello!!"</p>

 This way two of our problems have been solved. What about the third one? It too has been solved, if you look closely.

For example when you write:

document.getElementById("one").innerHTML="First";

 

 And then:

document.getElementById("one").innerHTML="Second";

The <p> would be displayed as having the text “Second”.

OK, below is the completed code:

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>JavaScript Countdown Timer</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <script language="JavaScript" type="text/JavaScript"> //to store timeout ID var tID; function tickTimer(t,id) { //if time is in range if(t>=0) { document.getElementById(id).innerHTML=t; t=t-1; tID=setTimeout("tickTimer('"+t+"','"+id+"')",1000); } //stop the timeout event else { killTimer(tID); document.getElementById(id).innerHTML="Time Out!!"; } } //function to stop the timeout event function killTimer(id) { clearTimeout(id); } </script> <!--style the ID --> <style> #timer { background: #000; color: #fff; font-size: 20px; } </style> </head> <!--pass the id to timer has to attached to --> <body onLoad="tickTimer(9,'timer')" onUnload="killTimer(tID)"> <p>Timer: <span id="timer"></span></p> </body> </html> 
 

It depends on what you intend regarding which tag you should use to place to timer. If you want it to be inline with some text use <span><p> would make it to be in a different paragraph.

So in this post we saw a very powerful method getElementById() which can be used to access HTML objects and manipulate them. Check back for more!

Previous Posts:

  •  

    Creating a Simple Countdown Timer Using JavaScript 

     
  •  
  •  

    Evaluating/Executing PHP Code at Run-Time Using eval() Function

     
  •  
  •  

    Blogger: Changing Templates without Loosing Widgets

     
  •  
  •  

    How Do I Color-Highlight PHP Source Codes

     
  •  
  •  

    Web Scraping: Gathering "Related Searches" Keyword Data From Google Search Results

     
Read full post >>

Creating a Simple Countdown Timer Using JavaScript

Some JavaScripting today! We are going to create a simple countdown timer using JavaScript. What’s the use? Umm, I really am not creative enough to find any of its perfect use but it could be used somewhere, sometimes…and there is no harm in learning something even when there seems to be no potential use of it. Who knows maybe you’d need it sometime to add creativity to your web pages. Of course some of the techniques that we are going to use will be needed at many times, so you won’t wanna miss this!

This time , let’s start off with the code first:

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>JavaScript Countdown Timer</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <script language="JavaScript" type="text/JavaScript"> //to store timeout ID var tID; function tickTimer(t) { //if time is in range if(t>=0) { document.writeln(t); t=t-1; tID=setTimeout("tickTimer('"+t+"')",1000); } //stop the timeout event else { killTimer(tID); document.writeln("<br /> <font color='#ff0000'>Time Out!</font>"); } } //function to stop the timeout event function killTimer(id) { clearTimeout(id); } </script> </head> <body onLoad="tickTimer(10)" onUnload="killTimer(tID)"> </body> </html> 

 Now let’s analyze the code:

1. We have created two functions tickTimer() and killTimer().
2. We have defined two event handlers onLoad and onUnload which’d call the respective functions at respective events.

When the code above (as a web page) is executed, it’d proceed as:

1. First the onLoad event calls tickTimer function with the initial time, the countdown timer has to be ticked down form. 

2. The function displays the initial time remaining, does some calculations and calls a method setTimeout().

3. The setTimeout function now calls the function passed, every 1000 milliseconds 1 second). On setting the timeout event this method returns a unique ID which would be used to stop the timeout event when needed (onUnload or when timer has ticked down to 0).

One thing you may get confused with is how without loop or anything as such, are we able to count the timer down. Answer is, because JavaScript is an event driven language. First, we are defining a body onLoad event to make a call to some function as the web page is loaded. Second, we are defining a timeout event that would call the function itself (recursive call) every one second indefinitely until the timeout event is cleared. We are clearing the timeout either when the countdown timer reaches 0 or when the page gets unloaded (onUnload).

Had JavaScript not been an event driven language, we’d need to have a loop to check when a second has elapsed and update the variable accordingly. Luckily we don’t have to!

But as it is, can we embed or place the above timer in a web page the way we want, styled and perfectly aligned. Or how about a single number getting counted down rather than showing all the numbers as the countdown proceeds. We’ll see that in the next post!

Previous Posts:

  •  

    Evaluating/Executing PHP Code at Run-Time Using eval() Function

     
  •  
  •  

    Blogger: Changing Templates without Loosing Widgets

     
  •  
  •  

    How Do I Color-Highlight PHP Source Codes

     
  •  
  •  

    Web Scraping: Gathering "Related Searches" Keyword Data From Google Search Results

     
  •  
  •  

    Web Scraping: Pulling Out Data From Google Search Results

     
Read full post >>

Evaluating/Executing PHP Code at Run-Time Using eval() Function

OK, so today we are going to discuss about one of the interesting functions of PHP. The eval() function. It is interesting in that it can evaluate/execute PHP code from inside scripts. This means, the eval() function can evaluate PHP code at run-time. The code itself in turn may be generated at run-time hence it could be used to execute code that may not initially be a part of the script.

Let’s see some examples:
eval("echo 'hello';"); 

 Which is equivalent to:

echo 'hello'

One more example:

<?php
$n
=10;
$code='';
for(
$i=0;$i<$n;$i++) 
    
$code.="echo $i;";
eval(
$code);
?>

Here the code to be evaluated is generated at run-time too.

The code to be evaluated could be stored somewhere (like in a file or in database) and later can be retrieved and evaluated.

As an example, below I’m providing the source code which would create a page that could be used to run PHP code. It’d provide a HTML textarea for you to type in the code which would then be executed and displayed. Be warned however that this kind of page is extremely vulnerable and an open invitation to hackers as anybody can use it to execute code on the server it is put in. so DON’T put this onto tour or anybody else’s server you have access to. It’d also be advisable to get off the internet before even trying it on your local server and delete the file afterwards. Believe me I’ve experienced hackers trying to access even local servers!

<?php echo "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?".">"?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head>
 <title>Untitled Document</title>
 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> 
 </head>
 <body>
 <h2>Run Script</h2>
 <form name="form1" id="form1" method="get" action=""> 
   <p>
     <textarea name="code" cols="50" rows="15" id="code"></textarea> 
   </p>
   <p>
     <input type="submit" name="Submit" value="Execute!" /> 
   </p>
 </form>
 <p><strong>Output:<br />
   -----------</strong></p>
<?php
if(isset($_GET['Submit'])) 
 {
     
$code=$_GET['code']; 
     
     eval(
$code); 
 }
?>

 </body>
 </html>

 

Previous Posts:

  •  

    Blogger: Changing Templates without Loosing Widgets

     
  •  
  •  

    How Do I Color-Highlight PHP Source Codes

     
  •  
  •  

    Web Scraping: Gathering "Related Searches" Keyword Data From Google Search Results

     
  •  
  •  

    Web Scraping: Pulling Out Data From Google Search Results

     
  •  
  •  

    Creating a Simple Form Validation Script Using JavaScript

     
Read full post >>

Blogger: Changing Templates without Loosing Widgets

The other day when I was trying to change the Template of this blog I faced a rather disheartening problem. Blogger said that all the Widget along with their data will be lost when changing to a third-party template. As you can see I have a link list (big one) on the sidebar, it has links to all my posts so far (>180!), man could I afford to loose that? Of course NOT!

Good thing was switching to one of the templates provided by Blogger wouldn’t make me loose those widgets. Bad thing is I don’t like those templates. Those are all too old, excessively used everywhere and 2-column ones.

So what did I do to save my widgets when changing to a third party Blogger template? Read along to know…(this might look like a crappy landing page that’d sell you something, believe me its NOT!)

If you too are facing the same problem you can take these steps to save your widgets:

STEPS:

1. Start off by going to Layout-> Edit HTML then click on Expand Widget Template check box.

2. Search for <b:widget in the template code and copy the widget section code.
 e.g.:

...
<div id='sidebar-wrapper'>
 <b:section class='sidebar' id='sidebar' preferred='yes'>
<b:widget id='HTML1' locked='false' title='Search this Blog' type='HTML'>
 <b:includable id='main'>
 <!-- only display title if it's non-empty -->
 <b:if cond='data:title != &quot;&quot;'>
 <h2 class='title'><data:title/></h2>
 </b:if>
 <div class='widget-content'>
 <data:content/>
 </div>
<b:include name='quickedit'/>
 </b:includable>
 </b:widget>
 <b:widget id='LinkList1' locked='false' title='Recent Posts' type='LinkList'>
 <b:includable id='main'>
<b:if cond='data:title'><h2><data:title/></h2></b:if>
 <div class='widget-content'>
 <ul>
 ...

Do it as many times as needed to copy all the widgets. Paste them one after to other in Notepad. You can leave the unnecessary ones such as Header, Blog (There is a widget for this too, shows the posts) etc. the code of which would look something like below:

No need to copy these:

  • <b:widget id='Header1' locked='true' title='For Testing Purpose (Header)' type='Header'>
  •  
  • <b:widget id='Blog1' locked='true' title='Blog Posts' type='Blog'>

3. Now copy the new template code by opening the XML file in another Notepad. Paste it in Blogger deleting the old template code.

4. Find the following line in the newly pasted template code:

...
<div id='sidebar-wrapper'>
 <b:section class='sidebar' id='sidebar' preferred='yes'>
[--PASTE WIDGETCODE HERE--]

5. Paste all the widget codes previously copied there right after the <b:section line.

6. Save the template.

7. If you had not copied some unnecessary widget codes from the original template, Blogger might ask you to confirm their deletion. Confirm this and SAVE the template.

8. Done!

Doing this you’d save existing widget from getting deleted when switching template but the widgets will NOT be arranged or placed in any meaningful manner (they’d all be in a sidebar). To re-arrange them in the manner you want just go to Layout-> Page Elements and drag drop the widgets as required, click save. You’re done!

Previous Posts:

  •  

    How Do I Color-Highlight PHP Source Codes

     
  •  
  •  

    Web Scraping: Gathering "Related Searches" Keyword Data From Google Search Results

     
  •  
  •  

    Web Scraping: Pulling Out Data From Google Search Results

     
  •  
  •  

    Creating a Simple Form Validation Script Using JavaScript

     
  •  
  •  

    Deigning a Simple HTML Menu-Bar Using CSS

     
Read full post >>

How Do I Color-Highlight PHP Source Codes

If you’ve been a regular reader of this blog you might have wondered how I highlight PHP code using different colors. Your prompt answer would be, using some software. Well not exactly as PHP has built-in feature for highlighting source code. And of course I use that.

Here are some of the different methods that you can use to highlight PHP source code, you may use any one of them depending upon what your intended purpose is.

1. If have set-up PHP as explained in Configuring Apache Web Server and PHP then you can just name your PHP files like “filename.phps” to tell PHP to highlight and show the file upon request and not execute it. You can use this method when you want to link the highlighted source from some web page. You cannot, however, embed source code into web pages using this method.

2. You can use the following function to highlight any PHP (.php) script file:

highlight_file('filename.php')

You just have to pass the filename to this function and PHP will highlight and output the code to the browser.

Main benefit with this is you can embed source code into your web pages wherever you want.

e.g.:

<?php
echo "<h1>Blah Blah Blog</h1>"
 echo 
"<h2>Highlighting PHP Source Code</h2>"
 echo 
"<p>blah blah blah!!</p>"
 echo 
"<p>Write anything you want and embed source code (highlighted)</p>"
 echo 
"<p>Embedded source code is listed below:</p>"
highlight_file('highlight_file.php'); 
?>

3. There are times when you just want to highlight a single line of code which can be done using:

highlight_file('string here')

It could be used when you have lost of unrelated lines of code to highlight. In other words, when the codes are not together but are sprinkled throughout the page. For this you don’t have to create any files to be highlighted, just use this function with thee source code string.

e.g.:

<?php
echo "<h1>Blah Blah Blog</h1>";
echo 
"<h2>Highlighting PHP Source Code</h2>";
echo 
"<p>First String: <br />";
highlight_string("<?php echo \"<h1>Blah Blah Blog</h1>\"; ?>");
echo 
"<br />Second String: <br />";
highlight_string("<?php foreach($keywords as $keyword) ?>");
echo 
"</p><p>blah blah blah blah <br />blah blah blah</p>";
echo 
"<p>Third highlighted String: <br />";
highlight_string("<?php if(isset($s)) ?>");
echo 
"<p>Notice how many unrelated code strings are here. The best way to format them in this condition is to use ";
highlight_string("<?php highlight_string(\"string\"); ?>");
echo 
"function </p>";
?>

Which would show up like below:

One interesting thing that you can play with, regarding syntax highlighting is the “php.ini” file. Look for these lines in that file:

; Colors for Syntax Highlighting mode. Anything that's acceptable in
 ; <span style="color: ???????"> would work.
 highlight.string = #DD0000
 highlight.comment = #FF9900
 highlight.keyword = #007700
 highlight.bg = #FFFFFF
 highlight.default = #0000BB
 highlight.html = #000000

Here, as you can see, the colors for highlighting different parts of the code are defined. You can change these to alter the colors that are use for highlighting. Colors are in HEX RGB format (same as HTML color code).

NOTE: If you don’t seem to be able to see the source code highlighted you might need remove the ";" (semi-colons) from the starting of each of the "highlight." line so it looks like the above code:

; Colors for Syntax Highlighting mode. Anything that's acceptable in
 ; <span style="color: ???????"> would work.
;highlight.string = #DD0000
;highlight.comment = #FF9900
;highlight.keyword = #007700
;highlight.bg = #FFFFFF
;highlight.default = #0000BB
;highlight.html = #000000

If only “.phps” PHP source files are not getting highlighted, you’ll need to set-up PHP as described in Configuring Apache Web Server and PHP .

Previous Posts:

  •  

    Web Scraping: Gathering "Related Searches" Keyword Data From Google Search Results

     
  •  
  •  

    Web Scraping: Pulling Out Data From Google Search Results

     
  •  
  •  

    Creating a Simple Form Validation Script Using JavaScript

     
  •  
  •  

    Deigning a Simple HTML Menu-Bar Using CSS 

     
  •  
  •  

    Blogger: Method to Add ‘Link to This Post’ Widget on Your Posts 

     
Read full post >>

Web Scraping: Gathering "Related Searches" Keyword Data From Google Search Results

You might first want to read Basic Web Scraping: Pulling Out Data From Google Search Results .

In the other Basic Web Scraping post we created a Simple Web Scraper that retrieved Google’s Search Result Pages for some keyword and scraped the “Number of Pages” indexed for the keyword. That was a good starting point in learning web scraping, that’s why in this post we’re going to extend that scraper to return one more information, “Related Keywords”.

Actually, Related Searches is a bunch of keywords that Google displays at the bottom of search result pages. These are not displayed all the keywords that you search for, but only for keywords that are somewhat broad. These “related Searches” are the keywords that Google has evaluated to be related with the one searched for.

To scrape this, we’d first need to analyze the HTML code of Google Search Result. We need to find out where the Related Searches block is in the code, typically it’d like:

<h2 class=r>Searches related to:<b> computer programming</b></h2><table border=0 cellpadding=0 cellspacing=0 style="margin-top:6px"><tr style="font-size:84%"><td style="padding:0 30px 6px 0" valign=top><a href="/search?hl=en&client=firefox-a&rls=org.mozilla:en-US:official&hs=lS4&q=computer+programming+schools&revid=92395746&sa=X&oi=revisions_inline&resnum=0&ct=broad-revision&cd=1">computer programming <b>schools</b></a></td><td>&nbsp;</td><td style="padding:0 30px 6px 0" valign=top><a href="/search?hl=en&client=firefox-a&rls=org.mozilla:en-US:official&hs=lS4&q=computer+programming+careers&revid=92395746&sa=X&oi=revisions_inline&resnum=0&ct=broad-revision&cd=2">computer programming <b>careers</b></a></td><td>&nbsp;</td><td style="padding:0 30px 6px 0" valign=top><a href="/search?hl=en&client=firefox-a&rls=org.mozilla:en-US:official&hs=lS4&q=computer+programming+languages&revid=92395746&sa=X&oi=revisions_inline&resnum=0&ct=broad-revision&cd=3">computer programming <b>languages</b></a></td><td>&nbsp;</td><td style="padding:0 30px 6px 0" valign=top><a href="/search?hl=en&client=firefox-a&rls=org.mozilla:en-US:official&hs=lS4&q=computer+programming+c%2B%2B&revid=92395746&sa=X&oi=revisions_inline&resnum=0&ct=broad-revision&cd=4">computer programming <b>c++</b></a></td><td>&nbsp;</td></tr><tr style="font-size:84%"><td style="padding:0 30px 6px 0" valign=top><a href="/search?hl=en&client=firefox-a&rls=org.mozilla:en-US:official&hs=lS4&q=computer+programming+information&revid=92395746&sa=X&oi=revisions_inline&resnum=0&ct=broad-revision&cd=5">computer programming <b>information</b></a></td><td>&nbsp;</td><td style="padding:0 30px 6px 0" valign=top><a href="/search?hl=en&client=firefox-a&rls=org.mozilla:en-US:official&hs=lS4&q=basic+computer+programming&revid=92395746&sa=X&oi=revisions_inline&resnum=0&ct=broad-revision&cd=6"><b>basic</b> computer programming</a></td><td>&nbsp;</td><td style="padding:0 30px 6px 0" valign=top><a href="/search?hl=en&client=firefox-a&rls=org.mozilla:en-US:official&hs=lS4&q=computer+programming+for+dummies&revid=92395746&sa=X&oi=revisions_inline&resnum=0&ct=broad-revision&cd=7">computer programming <b>for dummies</b></a></td><td>&nbsp;</td><td style="padding:0 30px 6px 0" valign=top><a href="/search?hl=en&client=firefox-a&rls=org.mozilla:en-US:official&hs=lS4&q=game+programming&revid=92395746&sa=X&oi=revisions_inline&resnum=0&ct=broad-revision&cd=8"><b>game</b> programming</a></td><td>&nbsp;</td></tr></table>

Remember our goal here is to find out certain footprint or consistent block in the code (which always will be on every page we request), out of which the needed data (Related Searches) can be pulled out.

Here, we can safely assume it to be:

<h2 class=r>Searches related to:

and

</td></tr></table>

 So if we do a search for the above block in the code, we can easily pull the required information.

Now, we can follow the following steps to scrape the required information:

  1. Retrieve the required page.
  2.  
  3. Look for the consistent part of code that uniquely encloses or identifies the required information. Scrape that block.
  4.  
  5. Pull the required data out.

Following is the code listing:

<html>
<head>
<title>Google Result Scraper</title>
</head>
<body>
<p align="center" style="font-size:500%"><font color="#0000FF">G</font><font color="#FF0000">o</font><font color="#FFFF00">o</font><font color="#0000FF">g</font><font color="#00FF00">l</font><font color="#FF0000">e</font>  
  <font size="2"><br />Result Scraper</font></p>
<?php
$s
=$_GET['s']; 
if(isset(
$s))
{
    
//*******F I R S T   P A R T*********
    //Find the number of pages indexed for the searched term 
    //*From previous part
    
echo "<p><i>Search for $s</i></p>";
    
$s=urlencode($s); 
    
$main_data=file_get_contents("http://www.google.com/search?hl=en&q=".$s."&btnG=Google+Search");
    
    
//strip off HTML 
    
$data=strip_tags($main_data);
    
//now $data only has text NO HTML
    //these have to ound out in the fetched data 
    
$find='Results 1 - 10 of about ';
    
$find2=' for';
    
//have text beginning from $find 
    
$data=strstr($data,$find);
    
//find position of $find2
    //there might be many occurence 
    //but it'd give position of the first one, 
    //which is what we want, anyway
    
$pos=strpos($data,$find2); 
    
//take substring out, which'd be the number we want
    
$search_number=substr($data,strlen($find), $pos-strlen($find)); 
    echo 
"Pages Indexed: $search_number";
    
    
    
//********S E C O N D   P A R T******* 
    //Find related searches
    
    
echo "<h3>Related Keywords</h3>";
    
//these have to found out in the fetched data 
    
$find='<h2 class=r>Searches related to:';
    
$find2='</table>';
    
$find3='<table border=0'
    
//have text beginning from $find
    
$data=strstr($main_data,$find);
    
//find position of $find2 
    //there might be many occurence
    //but it'd give position of the first one, 
    //which is what we want, anyway 
    
$pos=strpos($data,$find2);
    
//take substring out, this is the block of data 
    //that we'd fetch required information off of.
    
$related_search_block=substr($data,strlen($find), $pos-strlen($find)); 
    
    
//pull out the required data, stripping off "Searches related to.."
    
$related_searches=strstr($related_search_block,$find3); 
    
//now we only have the keywords, of course formatted as is
    //with tables
    
    //strip off HTML, therefore taking off table and various 
    //other formattings
    
$related_searches=strip_tags($related_searches);
    
//now we have the keywords (plain text) sepearted with  
    //each other using "&nbsp;'
    
    //explode it
    
$keywords=explode('&nbsp;',$related_searches); 
    
//now we a nice array having all the keywords
    
    //print the keywords
    //nicely formatted using <ol> (ordered list) 
    
echo "<ol>";
    foreach(
$keywords as $keyword)
    {
        if(
$keyword!='' && $keyword!=' '
        echo 
"<li>
                $keyword
             </li>"
;
    }
    echo 
"</ol>";    
}
else 
{
?>

<form name="form1" id="form1" method="get" action="">
  <div align="center">
    <p> 
      <input name="s" type="text" id="s" size="50" /> 
      <input type="submit" name="Submit" value="Find Related Keywords" />
    </p>
  </div>
</form>
<p>&nbsp;</p> 
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>
  <?php
}
?> 
</p>
<p align="right"><font size="2">by <a href="http://learning-computer-programming.blogspot.com/">Learning 
  Computer Programming</a></font></p> 
</body>
</html>

 Although this script is not very useful as it is (after all it’s meant for learning purpose) you can make it more useful by extending it. one thing that’d be nice is to hav it search for related keywords and again take each keyword as a base for further searches. This way it’d be able to supply you with many keywords related to the one entered. Best thing is, the keywords will be Googly Related!

Previous Posts:

 
  •  

    Web Scraping: Pulling Out Data From Google Search Results

     
  •  
  •  

    Creating a Simple Form Validation Script Using JavaScript

     
  •  
  •  

    Deigning a Simple HTML Menu-Bar Using CSS 

     
  •  
  •  

    Blogger: Method to Add ‘Link to This Post’ Widget on Your Posts 

     
  •  
  •  

    New Working Method of Making Blogger Title Tags SEO Friendly

     
Read full post >>

Performing Simple String Search Using PHP and MySQL

Here it is, a post after so long!

We see “Search” feature on almost all websites. Some employ third-party tools (like Google Custom Search) while others, mostly CMS based websites, have their own Search feature. The question now is, How do Search Feature Work? Answer is, it (almost always) uses MySQL (or database server’s capability. You all might be knowing that CMSs always store information in databases. So if we can search that we can very well search the whole site!

So today we’re going to employ the feature of MySQL to perform simple searching. As an example we’ll be creating an Online Phonebook to illustrate this.

MySQL’s Simple Search (String Matching) Query

select [coulumn1] from [table] where [column2] like ‘$var%’

(For some of the basic SQL queries refer to MySQL Commands )

we’ll take a simple example to illustrate the above query. Suppose we have a table with the following rows and columns:

               
idcolumn-1 column-2
1catthere is a cat
2dogthere is a dog
3canthere is a cold drink can
4campus i like my college campus

Now look closely what different queries will return:

1. select * from table where column-1 like 'ca%'

            
idcolumn-1 column-2
1catthere is a cat
3canthere is a cold drink can
4campus i like my college campus

2. select * from table where column-1 like 'cam%'

      
idcolumn-1 column-2
4campus i like my college campus

3. select * from table where column-1 like 'd%'

      
idcolumn-1 column-2
2dogthere is a dog

4. select * from table where column-2 like 'cat%'

      
idcolumn-1 column-2
NULLNULLNULL

5. select * from table where column-2 like 'there%'

            
idcolumn-1 column-2
1catthere is a cat
2dogthere is a dog
3canthere is a cold drink can

At this time it is worth noting that, while we can use this method to search for strings whose initial characters (words) are known but impossible to search for words within a string (like in query no. 4).

That’s it, all we need to perform simple search is the above mentioned query!

Below the source code for an Online Phone Book is given, it’d store phone numbers along with names. Its search feature will search names column, hence you can search for phone numbers by name.

<?php
/*Script: Onilne Phone Book with Search Facility
Date: 29-July-08
Copyright 2008 Arvind Gupta
http://learning-computer-programming.blogspot.com/
You are free to modify, change, publish or do whatever with this script
as long as this note is intact. Thank You!*/ 
//connect to MySQL
//provide your 'username' and 'pass'
$db=new mysqli('localhost','-USER-','-PASS-'); 
//if 'save' button was pressed
//user wants to store phone number
if(isset($_POST['save']))

    
$name=trim($_POST['name']);
    
$phno=trim($_POST['phno']);
    
//if data supplied are not empty
    
if(!$name=='' || !$phno=='')
    { 
        
//if this is the first time
        //and database is not craeted
        
if(!$db->select_db('one')) 
            
//create the database
            
$db->query('create database one');
        
//select the databasw to work with 
        
$db->select_db('one');
        
//if table is not craeted, craete it
        
if(!$db->query('select * from phno')) 
            
$db->query('create table phno(id int auto_increment primary key, name varchar(50), phnum varchar(20))');
        
//ready to insert data
        
$db->query("insert into phno (name, phnum) values ('$name', '$phno')"); 
    }
}
//show the form
?>
<html>
<head>
<title>My Phone Book</title> 
</head>
<body>
<h1>My Phone Book</h1>
<h2 style="background: #000; color: #fff;">Store New Phone Number</h2> 
<form name="form2" method="get" action="">
  <p style="background: #000; color: #fff;"><b>Search:</b>
    <input name="search" type="text" id="search"> 
    <input name="searchb" type="submit" id="searchb" value="Search">
  </p>
</form>
<p></p>
<form name="form1" id="form1" method="post" action=""> 
  <table width="250" border="0" cellspacing="0" cellpadding="0">
    <tr>
      <td width="83">Name</td>
      <td width="417"><input name="name" type="text" id="name" /></td> 
    </tr>
    <tr>
      <td>Ph. No.</td>
      <td><input name="phno" type="text" id="phno" value=""></td> 
    </tr>
    <tr>
      <td><input name="save" type="submit" id="save" value="Save" /></td>
      <td><input type="reset" name="Submit2" value="Reset" /></td> 
    </tr>
  </table>
</form>
<h2 style="background: #000; color: #fff;">Previously Stored</h2>
<p>ORDER BY: <a href="?order=new">newest first </a>| <a href="?order=old">oldest 
  first</a> | <a href="?order=az">a-z</a> | <a href="?order=za">z-a</a></p>
</body>
</html> 
<?php
//----DISPALY PREVIOUSLY STORED PH. NUMBERS----
//create the SQL query as per the action
//if any ordering is selected 
$order=$_GET['order'];
if(
$order=='new')
    
$query="select * from phno order by id desc"
elseif(
$order=='old')
    
$query="select * from phno order by id asc";
elseif(
$order=='az'
    
$query="select * from phno order by name asc";
elseif(
$order=='za')
    
$query="select * from phno order by name desc"
//or if user is searching
elseif(isset($_GET['searchb']))
    {
        
$search=$_GET['search']; 
        
$query="select * from phno where name like '$search%'";
    }
else
    
//use the default query 
    
$query="select * from phno";
//if database does not exits
//first time operation
if(!$db->select_db('one')) 
{
    echo 
"<p><i>NONE</i></p>";
    exit;
}
//else
//do the query
$result=$db->query($query); 
//find number of rows
$num_rows=$result->num_rows;
//if no rows present probably when
//searching 
if($num_rows<=0)
    echo 
"<p><i>No Match Found!</i></p>";
//process all the rows one-by-one 
for($i=0;$i<$num_rows;$i++)
{
    
//fetch one row
    
$row=$result->fetch_row(); 
    
//print the values
    
echo "<p><span style=\"font-size: 200%;\">$row[1]: </span> $row[2]</p>";
}
//close MySQL connection 
$db->close();
?>
 

It might now be obvious that we took this phonebook example due to the limitation of “like” query to search for words within a string. That’s not to say it’s not possible. In fact searching within string, even longer ones is very easy and efficient using MySQL’s built-in capability. But we’ll discuss that in some future posts.

Previous Posts:

  •  

    Creating a Simple Form Validation Script Using JavaScript

     
  •  
  •  

    Deigning a Simple HTML Menu-Bar Using CSS 

     
  •  
  •  

    Blogger: Method to Add ‘Link to This Post’ Widget on Your Posts 

     
  •  
  •  

    New Working Method of Making Blogger Title Tags SEO Friendly

     
  •  
  •  

    One More Use of Web Cookies

     
Read full post >>

RevResponse, Offer Freebies to Earn Money

This is sort of a paid review. You don’t normally find me doing this but since I truly liked RevResponse at the first sight, I’m writing this. 

Overview

RevResponse (aff. link) is one-of-a-kind of affiliate network that pays you for promoting Free Magazines, Technical Whitepapers, Software etc the topic of these materials range from Agriculture to Software Development and from Bio-Technology to Transportaion & Logistics. This means most content based website/blogs won’t have much problem finding relevant offers to promote. Since all magazines, whitepapers etc. are free, it’s kind of a Pay-Per-Lead affiliate network. The magazines, that many presume to be SPAM, are not at all spammy rather are really useful and informative. And as those are all free, it means great source of information for your visitors and income for you!

Sign-Up

The Sign-Up (aff. link) process is pretty straightforward and doesn’t require you to fill any lengthy forms once you are done with that, they would contact you within a few days (in my case less that 24-hours) to tell you whether your application is accepted or not. If you have an informative blog/website, you won’t have any problems getting accepted even though your website/blog is on a free host.

Promotional Materials

Image Ads: Basic ads in all standard sizes.

Text Ads: Plain text ads. They also provide pre-written paragraphs. It’d be best if you personalize it.

Flash Widget: Beside normal image based ads they also provide interactive flash widgets. Catches eye and would prove to be useful for your visitors.

Co-Branded Site: Really great, like Amazon’s astore, RevResponse provides you with a customizable website with the same look as your existing website. It is hosted on tradepub.com. It could be customized to create your very own Magazine Catalog.

Earning Potential

If you choose the offers wisely and promote them using genuine reviews, in other words to give genuine value to your visitors, there nothing stopping you from earning, at least, more than traditional advertising (AdSense etc.) they pay between $1.50 - $20 (as far as I’ve heard), which is great. Another great thing is unlike many other networks, RevResponse accepts leads (subscriptions, downloads of the offers you promote) from international visitors too!

Conclusion

Pros:

  • Company behind RevResponse is quite old (since 1996)
  •  
  • Great affiliate managers, support and “personal” feeling. They have a blog and a forum to share and get ideas.
  •  
  • Payment via PayPal and Check.
  •  
  • Accepts international leads.
  •  
  • Offers that you can promote are FREE.

Cons:

  • Net-45 Payment scheme which means you’re paid 45-days after the month you earnings reach $50 (minimum payment threshold)
  •  
  • Web is so cluttered with spam that some people don’t bother for “freebies” anymore

I’d genuinely recommend RevResponse (aff. link) to anyone having a content blog/website. Do check it out!

Read full post >>

Reason For The Lack of Posts These Days...

Today I’ve got a bad news for you guys. It’s that I won’t be able to blog for almost a month. Sorry guys, it’ I know it’s happened in the past but this time I’ve got a pretty good excuse – EXAMS. That’s right my exams starts 10th July and guess what, I haven’t studied much yet! It happens…always happens…

Hope you’d understand my problem, in the mean time you may want to read some of my recent posts that got good readership:

  •  

    Installing Apache and PHP on your PC 

     
  •  
  •  

    Designing a Simple Order Form Application in PHP

     
  •  
  •  

    Designing a Simple “Quote of the Day” Script in PHP

     
  •  
  •  

    Creating a ‘Contact Us’ Form (E-Mail Version) 

     
  •  
  •  

    Designing a Simple ‘Shout Box’ Script in PHP

     
  •  
  •  

    A Complete Note Keeping Application in PHP

     
  •  
  •  

    Creating a Simple Poll Script in PHP

     
  •  
  •  

    New Working Method of Making Blogger Title Tags SEO Friendly

     
  •  
  •  

    Basic Web Scraping: Pulling Out Data From Google Search Results

     

Enjoy!

Read full post >>

Creating Tool-Tip Text for WebPages Using CSS Only

[You might also be interseted in Deigning a Simple HTML Menu-Bar Using CSS ]

All right, so today we are going to use CSS along with some HTML to create Tooltip text for WebPages without using JavaScript. Yeah, you heard it right using only CSS and of course HTML. Do I need to explain what a Tooltip is, BTW? Nah, you guys already know it. I do not think many sites use tooltips or anything of that sort on their websites but in case you do or you just want to learn, read on…

Well, the first thing that I want to tell is that the basic technique I’ll be using to create tooltips is not mine, I saw someone using it for a slightly different purpose, I changes it to suite mine. As I said earlier we’d be using CSS and HTML only, I guess HTML is easier so here it is:

<a href="#" class="tooltip">Hover Here<span>This is the Tool-Tip Text</span></a>

As you can see there is nothing special, a plain simple link but wait what is that <span> for? Good question! Well the text under the <span> tag wouldn’t be visible unless you hover the mouse over the link. When you do so that’d become visible, neatly formatted to look just like a real Tooltip text. But how? You might ask. It has been classified (class="tooltip") to do so.

The heart of all this is the CSS:

 a.tooltip{ /* for postioning the tool-tip box relative to the link */ position:relative; /* no underline needed */ text-decoration: none; } a.tooltip span{ /* tool-tip text will not be visible initially */ display: none; } a.tooltip:hover span{ /* make tool-tip text visible */ display:block; /* for postioning */ position:absolute; top:20px; left:20px; padding: 5px; /* width of the tool-tip box if text is longer, it will be made into two lines */ width:150px; /* style the box to look like a tool-tip box */ border:1px solid #000; background-color:#FFFFAA; color:#000; } 

Now to make it more clear, I’d break the whole code into smaller pieces and discuss what that does:

1. 

a.tooltip { position:relative; }
 

This would make the tooltip (whenever) it appears to be positioned relatively to where the link is.

2.  

a.tooltip span { display: none; }
 

It’d (as you might have guessed) make the tooltip text (or the <span> tag) to be invisible.

3.  

 a.tooltip:hover span { display:block; position:absolute; top:20px; left:20px; padding: 5px; width:150px; border:1px solid #000; background-color:#FFFFAA; color:#000; }
 

This defines what the <span> tag would be when mouse is hovered over the link.

First it’d make the <span> visible (thus the tooltip text) by using display: block;. Next it’d position and style the <span> text to look like a “Real” tooltip.

Easy! Now it is…

Here is the complete code:

 <html> <head> <title>ToolTip Text Example</title> <style> a.tooltip{ /* for postioning the tool-tip box relative to the link */ position:relative; /* no underline needed */ text-decoration: none; } a.tooltip span{ /* tool-tip text will not be visible initially */ display: none; } a.tooltip:hover span{ /* make tool-tip text visible */ display:block; /* for postioning */ position:absolute; top:20px; left:20px; padding: 5px; /* width of the tool-tip box if text is longer, it will be made into two lines */ width:150px; /* style the box to look like a tool-tip box */ border:1px solid #000; background-color:#FFFFAA; color:#000; } </style> </head> <body> <a href="#" class="tooltip">Hover Here<span>This is the Tool-Tip Text</span></a> </body> </html> 
 

Previous Posts:

  •  

    Basic Web Scraping: Pulling Out Data From Google Results

     
  •  
  •  

    Creating a Simple Form Validation Script Using JavaScript

     
  •  
  •  

    Deigning a Simple HTML Menu-Bar Using CSS 

     
  •  
  •  

    Blogger: Method to Add ‘Link to This Post’ Widget on Your Posts 

     
  •  
  •  

    New Working Method of Making Blogger Title Tags SEO Friendly

     
Read full post >>

Basic Web Scraping: Pulling Out Data From Google Search Results

[UPDATE (22-AUG-2009): THIS IS THE NEW WORKING VERSION.]

Today we are going to discuss a bit advanced topic, not in the sense that it’d be difficult to understand (I always try to make things easier anyway) but that you won’t find an apparent use of it. What we are going to do today is what is called Web Scraping. By the way web scraping means retrieving data from web and pulling out useful information out of it for our use. Of course this wouldn’t be the next best web scraper rather it would la a basic foundation on how simple a web scraper can be.

OK let’s kick off guys!

As is obvious we are going to scrape Google’s Web Search Results to retrieve the number of pages indexed for a search term.

To retrieve results for a search term we need the URL, for this fire up your favorite Browser and browse to the Search Engine’s (Google, or whatever) homepage, type in any search query and hit enter.

OK now look at the address bar, in my case I looked like below, your’ should be similar or whatever:

http://www.google.com/search?hl=en&q=learning+c&btnG=Google+Search

 On inspection you can see pour search term in the URL which is ‘URL Encoded’ (changes some character such as spaces to codes). There we have it, you can place any search keyword (urlencoded, very simple with PHP’s in-built function) and fetch that page. But how in a script, you might ask. Because that is what we need.

Well using the following function:

file_get_contents();

[UPDATE: WE'LL BE USING THE FOLLOWING USER-DEFINED FUNCTION INSTEAD. READ COMMENTS FOR MORE INFORMATION:

function my_fetch($url,$user_agent='Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)'
{
    
$ch curl_init();
    
curl_setopt ($chCURLOPT_URL$url);
    
curl_setopt ($chCURLOPT_USERAGENT$user_agent); 
    
curl_setopt ($chCURLOPT_HEADER0);
    
curl_setopt ($chCURLOPT_RETURNTRANSFER1);
    
curl_setopt ($chCURLOPT_REFERER'http://www.google.com/'); 
    
$result curl_exec ($ch);
    
curl_close ($ch);
    return 
$result;
}
 

]

If you have been following this blog for sometime, you might remember we once used it in my Creating a Simple Shout Box in PHP post to fetch contents from a local file. Yeah its beauty is that it can fetch remote (HTTP) files too.

$data = file_get_contents("http://www.google.com/search?hl=en&q=learning+c&btnG=Google+Search");

[UPDATE: NOW USING:

$data = my_fetch("http://www.google.com/search?hl=en&q=learning+c&btnG=Google+Search");

]

Above code will fetch the Google Search Results for the keyword we searched for in the browser, $data will contain the HTML source.

Since we have to scrape the total number of pages indexed for a particular search term (displayed as “Results 1 - 10 of about XXXX …”) we would find some text near that number(XXXX in this case). In this case that text is simply “Results 1 - 10 of about”, its also unique throughout the page hence if we could find it in the code returned we can easily find the needed data. One more thing we can ease off searching by first stripping off HTML from the code returned so that only text remains. This part can be implemented as below:

    $data=my_fetch("http://www.google.com/search?hl=en&q=".$s."&btnG=Google+Search"); 
     
     
//strip off HTML 
     
$data=strip_tags($data); 
     
$find='Results 1 - 10 of about '
     
$find2=' for'
     
//have text beginning from $find 
     
$data=strstr($data,$find); 
     
//find position of $find2 
     
$pos=strpos($data,$find2); 
     
//take substring out, which'd be the number we want 
     
$search_number=substr($data,strlen($find), $pos-strlen($find)); 

Here is the complete code:

<html>
<head>
<title>Google Result Scraper</title>
</head>
<body>
<p align="center" style="font-size: 500%"><font color="#0000FF">G</font><font 
     color="#FF0000">o</font><font color="#FFFF00">o</font><font
     color="#0000FF">g</font><font color="#00FF00">l</font><font
     color="#FF0000">e</font><font size="2"><br /> 
Result Scraper</font></p>
<?php
function my_fetch($url,$user_agent='Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)'
{
$ch curl_init();
curl_setopt ($chCURLOPT_URL$url);
curl_setopt ($chCURLOPT_USERAGENT$user_agent); 
curl_setopt ($chCURLOPT_HEADER0);
curl_setopt ($chCURLOPT_RETURNTRANSFER1);
curl_setopt ($chCURLOPT_REFERER'http://www.google.com/'); 
$result curl_exec ($ch);
curl_close ($ch);
return 
$result;
}
$s $_GET['s']; 
if (isset(
$s))
{
echo 
"<p><i>Search for $s</i></p>";
    
$s urlencode($s); 
    
$data my_fetch("http://www.google.com/search?hl=en&q=" $s "&btnG=Google+Search");
    
//strip off HTML
    
$data strip_tags($data); 
    
//now $data only has text NO HTML
    //these have to found out in the fetched data
    
$find 'Results 1 - 10 of about '
    
$find2 ' for';
    
//have text beginning from $find
    
$data strstr($data$find); 
    
//find position of $find2
    //there might be many occurence
    //but it'd give position of the first one, 
    //which is what we want, anyway
    
$pos strpos($data$find2);
//take substring out, which'd be the number we want 
$search_number=substr($data,strlen($find), $pos-strlen($find));
echo 
"Pages Indexed: $search_number";
}
else
{
    
?>

<form name="form1" id="form1" method="get" action=""> 
<div align="center">
<p>  <input name="s" type="text" id="s" size="50" />
<input type="submit" name="Submit" value="Count" /></p> 
</div>
</form>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p> 
<p>
<?php
}
?>
</p>
<p align="right"><font size="2">by <a
     href="http://learning-computer-programming.blogspot.com/">Learning
Computer Programming</a></font></p> 
</body>
</html>

Wow, our first scarper is completed. It has a nice interface, you type in search phrase click ‘Count’ and there you are. It displays the number of pages that contains that term same as on Google.

Have fun guys and do comment!

P.S.: You might want to read String Manipulation Function in PHP I and String Manipulation Function in PHP II if you are not much familiar with the string manipulation functions we are using in the code above.

Previous Posts:

  •  

    Creating a Simple Form Validation Script Using JavaScript

     
  •  
  •  

    Deigning a Simple HTML Menu-Bar Using CSS 

     
  •  
  •  

    Blogger: Method to Add ‘Link to This Post’ Widget on Your Posts 

     
  •  
  •  

    New Working Method of Making Blogger Title Tags SEO Friendly

     
  •  
  •  

    One More Use of Web Cookies

     
Read full post >>