Wednesday, March 30, 2011

Cricket score update - JSON

Hi

I probably should have got this script done long back. If you have a website or a blog where you want to integrate the score update for CWC 2011, then you just need to use the code given below. In this I am using an JSON API of json-cricket.appspot.com for fetching the details. All you have to is parse the JSON returned. The output will be as follows:


This API has not been tested thoroughly, but it surely returns. Here is the code:

For simple HTML

<html>

<head>
<title>Cricket Score Update</title>
</head>
<body>
<div id="score_board"></div>
<script type="text/javascript">
o={s:function(data){document.getElementById("score_board").innerHTML=data.match + "<br />" + data.score + "<br />" + data.summary;}};

Tuesday, March 29, 2011

Facebook style image collage

Hi,

In Facebook there are various applications which makes a collage of all your friends. The application may be showing your top followers, or friends who are in your same organization and so on. In this post I have created a  PHP script to do exactly the same. But for demo I have used a static array of users to create the collage image, which of course you can convert to a dynamic array fetching data from the database.

First lets see the output:


Everytime you refresh the sequence of users will get shuffled and the angle of rotation of the images are also randomly selected between -10 to +10 degrees. Few prerequisites before using the code is to copy a font file(.ttf) and paste it in the directory of the code. Rename the ttf file to "cfont.ttf". Secondly and most important is to enable you GD library if it is not enabled.

The code to get the above is:

<?php
$im=imagecreatetruecolor(300,300);
$white=imagecolorallocate($im,255,255,255);
$black = imagecolorallocate($im, 100, 100, 100);
imagefilledrectangle($im,0,0,800,500,$black);
$font = 'cfont.ttf';
$users=array();
$users[0]['image']="statham.jpg";$users[0]['name']="Jason Statham";
$users[1]['image']="antonio.jpg";$users[1]['name']="Antonio Benderas";
$users[2]['image']="will_smith.jpg";$users[2]['name']="Will Smith";
shuffle($users);
$marge_left=20;$marge_top=20;$i=0;
foreach($users as $key){
$i++;
$img_element=imagecreatefromjpeg($key['image']);
$angle=rand(-10,10);
$img_element = imagerotate($img_element, $angle , $black);
$text=$key['name'];
imagettftext($img_element, 10,0, 10, 20,$white, $font, $text);
imagecopy($im, $img_element, $marge_left, $marge_top, 0, 0, imagesx($img_element), imagesy($img_element));
$marge_left+=120;
if($i%2==0){
$marge_left=20;
$marge_top=$marge_top + 120;
}
}
header("content-type: image/jpeg");imagejpeg($im,null,100);

Explanation:

Monday, March 28, 2011

Rounded corners without CSS 3 - All browser compatible

Hi,

CSS 3 provides a wide range of design tweaks which change the entire attitude of the website. Most commonly used functionality is rounded corners to any element. In CSS 3 you can create rounded corners to any element. Apart from DIV's if you want to show some images with rounded corners or button, input boxes etc then also this javascript approach can be helpful, depending on your needs. The conventional CSS 3 approach is as follows:

-moz-border-radius:  5px;
-webkit-border-radius: 5px;
-khtml-border-radius: 5px;

But the problem is, few browser does not support it. So one way to achieve this is by using a jQuery plugin. For this you need jquery.corner.js and jquert.min.js. Click here to download the entire source code along with the required JS files.

This is the output you will get:


Explanation:

Sunday, March 27, 2011

Check if email has been read

Hi,

If you are working with newsletters, it is a part of the job to maintain a statistics, of the emails to which the newsletters are send. The statistics may contain, number of bounced mails, number of opened/unopened email and so on. In this post I will explain a method for checking whether an email has been read or not. For checking bounced emails, I hope I will add it as a seperate post.

The idea is very simple. When we are talking of whether an email has been read or not, we basically mean to say  whether the email has been opened or not. For achieving this, following is the technique I have been using in most of my projects.

Assuming we have the following table structure (this is the minimum columns needed, you can change according to your need):



First add a image tag in your email along with the other email contents, and do not mention any size of the image as:

<img src="....." />

The main trick is with the "src" attribute. In the src, instead of using an actual image, enter the path of a PHP file in your server with the full URL of the files as:

<img src="http://localhost/php/ismailopened/opened.php?id=1">

In "?id=1", the value 1 needs to be dynamic. It is the newsletter ID. Now in opened.php I have added the following code:


<?php
if(isset($_GET['id'])){

mysql_pconnect("localhost","root");
mysql_select_db("test");
mysql_query("update newsletter set isopened='1' where id=".$_GET['id']);

Friday, March 25, 2011

Crawling URLs - PHP

Hi,

In this post I will give the source code for crawling the various URL's of a particular webpage. The main things to keep in mind is pattern matching using preg_match() function. For achieving this first I am importing the entire page content of a web URL, and then I am parsing it to extract the various hyperlinks found in the page.

Now in this post I will just show the method of extracting the URL's. But you can implement this logic to do many tasks such as creating a search engine, which stores all the URL's found in a webpage along with it meta data, or you may also use this technique to create a sitemap for your website. More you think, more ways you may find to make this code into use.

So the code is:


<?php
function reqtime($url){
$start=microtime(true);
@file_get_contents($url);
$end=microtime(true);
return number_format($end-$start,2);
}

$body = file_get_contents("http://www.blogger.com/posts.g?blogID=3662517344220871310");
$out = array();
preg_match_all( "/(\<a.*?\>)/is", $body, $matches );
$count=0;
foreach( $matches[0] as $match )
{
$count++;
preg_match( "/href=(.*?)[\s|\>]/i", $match, $href );

if ( $href != null )
{
  $href = $href[1];
  $href = preg_replace( "/^\"/", "", $href );
  $href = preg_replace( "/\"$/", "", $href );

Thursday, March 24, 2011

Checking valid email domain - PHP

Hi,

Validating an email address is not a big deal. Conventionally we use two steps to validate an email address:

Step 1. Just use regular expressions to check whether an email address follows the correct pattern.
Step 2. Then you just send the an email to that email address with a activation link to make sure that the email is valid.

But you can do I more check in between Step 1 and 2, just to make things more sensible. Here is a small mockup code for doing that:

<?php


function validate_domain($email){
$strpos=strpos($email,"@");
$domain=substr($email,$strpos + 1);
if(!@file_get_contents("http://".$domain) && !@file_get_contents("https://".$domain)){
echo $email." Status: <font color='red'>Invalid email domain</font><br/>";
}else{
echo $email." Status: <font color='green'>Valid email domain</font></br>";
}
}

validate_domain("xyz@gmail.com");
validate_domain("xyz@incorrectdomainname.com");
?>


Explanation:

Multipart Email - PHP

Hi,

PHP provides a very simple mechanism for sending emails as compared to other scripting languages. But the problem with emails is, different email client work differently. What I mean to say is, there are many email clients which does not support HTML contents in email. What they do is, they just simply display the HTML tags, instead of parsing them. Now a good solution is to send the emails in plain format. Plain content type is supported by all email clients, irrespective of the fact that whether they support HTML or not.

But the problem with the format of Plain Content type emails, is you cannot create good looking email, with images and hyperlinks, as that will need a HTML content type. So the best solution is to format the email content is such a way that the email clients which support HTML email will show the emails in HTML format and the email client which does not support HTML will show the plain version of the HTML message.

For this you need to use multipart emails. It is very simple. You just need to create two version of the same email. One with the HTML tags and the other without the HTML tags. When you are done doing this, you need to keep few things in mind. Here is an example of multipart email:


<?php
$plain_message_text="This is a plain message:\n\nFor email clients, not supporting HTML\n\nhttp://php-drops.blogspot.com";
$html_message_text="This is a <b>HTML</b> message:<br/><br/>For email clients, supporting <i>HTML</i><br/><br/><a href='http://php-drops.blogspot.com' target='_blank'>PHP Drops</a>";

$notice = "This is a multi-part message in MIME format.";
$boundary = md5(time());

Wednesday, March 23, 2011

Get query execution time in PHP

Hi,

When you perform a Google search, it shows the approximate number of records and the time taken to make that search. e.g.


For a layman, that time may seem to be the time taken for the entire process. But actually its the time taken to generate the search results. So technically, its the time taken to execute the search query. I have used the following technique to do the same. But I am sure that can be many more ways to achieve it.

For this I created a simple table just for demonstration as follows:


Now my objective is to run a query on this table and fetch the time required to run that query using PHP. So this is the code that I have written:

Tuesday, March 22, 2011

Website Security - How to avoid using session variables for logged in users

Hi,

It is a very common practice of storing logged in user details such as username, first name, last name, user id etc in session variables. But even session variables can be vulnerable and easily hacked. I have come up with a strategy of storing user details in runtime without using session variables or cookies. You will find a sample source code at the end of the post.

The idea is very simple. Assuming I have a user table with the following schema and data:


Now when the user is logging in through login.php, first the data is validated with the above table. If user has entered correct credentials, instead of storing the user data in session variables, I am storing them in a separate log table as follows:


with the code:


$is_user=mysql_fetch_array(mysql_query("select * from users where username='".mysql_real_escape_string($_POST['username'])."' and password='".mysql_real_escape_string($_POST['password'])."'"));
if(empty($is_user)){
$message="Incorrect username or password";
}
if(!mysql_fetch_array(mysql_query("select * from user_log where sessid='".session_id()."'"))){
mysql_query("insert into user_log set userid=".$is_user['id'].",sessid='".session_id()."',dt='".date("Y-m-d",time())."'");
}


In the above, after user logs in the session id and the user details along with the current date is stored in the log table as above. In this case I am just storing the userid, but you can add more fields, such as first name, last name etc.

(note: I am not using any encryption for storing password, but it is highly recommended)

This was just half the job. Next is to check whether user is logged in or not. During this checking we will run a query to check whether there are any records with the current session ID. If a match is found the user is valid. This is done by:

Monday, March 21, 2011

Proportionate Text Zoomer - Javascript

Hi,

In this I have made a custom script which can be used in any website to increase or decrease the text size of the entire page. You can find the entire source code at the end of this post. The zoom in and zoom out functionality is performed irrespective of their current font size. e.g. if a span has font size 10 and h1 as 14, then this will make span to 11 and h1 to 15, based on a certain percentage.

This is what the sample page looks like:

In this script you can choose tags whose text needs to be increased/decreased. This is what you have to do in script.js to add a new tag to have the functionality:


  $(".increaseFont").click(function(){  // for increasing font

$('a').each(function(idx, item) {    //adding the funtionality to anchor tag
       size=parseInt(jQuery(this).css("font-size"));
  size++;
  jQuery(this).css("font-size",size + "px")
    });
})

Sunday, March 20, 2011

Cakephp Store procedure + multiple resultset fetch

Hi All,


I have been working on a project which involves huge data. So the idea is to use stored procedures to make the query execution fast. Most tricky part in this, is to fetch multiple-result set from a single store procedure. 


Step 1: Write the procedure which have the multiple select queries.
Step 2 : Make a component within your cake's controller folder(app/controllers/components) and paste the code given below:

function callstoreproc($procname,$paramarr=null)
{
$connstr = ConnectionManager::getInstance();

$conhost = $connstr->config->default["host"];
$conlogin = $connstr->config->default["login"];
$conpassword = $connstr->config->default["password"];
$condatabase = $connstr->config->default["database"];

$mysqli = new mysqli($conhost, $conlogin, $conpassword, $condatabase);

if (mysqli_connect_errno())
{
echo "Connect failed";exit();
}
 $query = $procname;
 if (mysqli_multi_query($mysqli, $query))
{
$i=0;
while (mysqli_more_results($mysqli))
{
if ($result = mysqli_store_result($mysqli))
{

AJAX + JSON

Hi,

JSON is a very lightweight script which is used to store data. It is useful because of its speed. Calling and working with JSON is much faster as compared to XML. This post deals with calling a JSON file via AJAX and parsing it accordingly.

To begin with we have the following json file, student.json with the following content:


{"students": [
        {"Name": "John Smith", "Age": "18", "Gender": "male"},
        {"Name": "Maratha", "Age": "19", "Gender": "female"},
        {"Name": "Rose", "Age": "17", "Gender": "female"},
    ]}

This of course is a sample data which I created manually. Now to call this file via ajax I will be using jQuery. Now I create a new file example.php and make a ajax call to the above "student.json" as follows:


jQuery(document).ready(function(){
jQuery.ajax({
type:"GET",
url: "student.json",
success: function(content){
.............
}
})
})

In the above example I am calling the json file after the entire page has been loaded in the browser. After the ajax call successfully executes, this is what I am doing:


success: function(content){
var students_json=eval("("+content+")");
total_students=students_json.students.length;
for(i=0;i<total_students;i++){
jQuery("body").append("Name: " + students_json.students[i].Name+ "  Age: "+students_json.students[i].Age+"  Gender: "+students_json.students[i].Gender+"<br>");
}
}

"eval()" function is used to convert a string into a JSON script. Next "students" is the name of the main root element. I am first finding the content length of "student", later I am executing a loop and extracting 1 field at a time and displaying the values in the web page. This is the output I get:

Friday, March 18, 2011

Website Security - How storing important information in cookie can be easily hacked

Hi,

This again adds to one of the security measures. Assuming you are storing some very vital information in your websites cookies e.g. transaction id in an e-commerce website.

It will take less than 10 seconds for any hacker to track down your cookies. All he has to do is to copy a code similar to this one:


javascript:alert(document.cookie.split(';').join('\n'))


go to your e-commerce website and paste it in the address bar and hit enter. As soon as he hits the enter button, immediately an alert box shows up listing all the cookies and PHP session id.


I created a simple example.php file with the following:



<?php
session_start();
setcookie("MY_COOKIE","this is the value of the cookie variable");
?>


then I executed example.php. The I copied and pasted "javascript:alert(document.cookie.split(';').join('\n'))" in the address bar and hit enter. This is what I got:



Apart from the above, every browser provides some way or the other to view the cookies and its values of a particular website. This is the fastest way to find out. This is useful for QA guys, while analyzing website.

Hope this helps.


Thursday, March 17, 2011

Object Oriented Javascript

Hi,

OOP is not just limited to PHP, you can implement its concepts to some extent in javascript as well. But before I move on with it in details, the most important thing you need to understand about OOP as fas as Javascript is concerned is the fact, that there are no classes as such, as we have conventionally known. Here the functions are treated as class, which may contain member functions and data members.

Here is the javascript

<script type="text/javascript">
function Person(name)
{
  this.name = name;
  this.getName = getName;
  this.setName = setName;
}
function getName()
{
  return this.name;
}  
function setName(name)
{
  this.name = name;
}
var personObj = new Person('Bob');

Facebook style hyperlinking - with/without javascript

Hi,

If you have seen facebooks hyperlinks, you will notice that most of the hyperlinks work using ajax calls. But what hackers love to do is to switch of javascript from the browser and try things. In case of facebook if javascript is enabled in the browser the page is called via ajax, but if javascript is disabled then also the hyperlinks do not stop working. What they do is instead of the ajax call, the page loads the conventional way i.e. simple href.

I have made a sample code for that, this is how it works. Its independent whether javascript is enabled or not. It works accordingly. Assuming javascript is enabled. The hyperlinks are as follows:


<a href="index.php?p=home.php">Home</a><br/>
<a href="index.php?p=page1.php">Page 1</a><br/>
<a href="index.php?p=page2.php">Page 2</a><br/>
<a href="index.php?p=page3.php">Page 3</a><br/>

Now I am loading a javascript which extracts the "href" parameter of all hyperlinks and stop the anchor tab to refresh the page by adding "return false" in the "onclick" event of the hyperlink as follows:


jQuery('a').click(function(){
link=jQuery(this).attr('href'); // extracts the value of the href attribute
.......
        .......
   return false;   // stops the page from refreshing on clicking the hyperlink
});



Now we parse the format of the 'link' variable and make a ajax call to load the destination page as:

Tuesday, March 15, 2011

Website Security - 2(SQL Injection & Spamming)

Hi,

This is a continuation of my previous post on website security. In this I will be discussing about SQL injection and spamming web forms. So coming to SQL injection.

1. SQL Injection

SQL Injection is possibly one of the easiest way for a professional hacker to tamper your database. The idea is to customize the internal SQL query according to the hackers choice. This happens when the users input from textbox/textarea are not filtered before executing them in a SQL query. This might sound a little complicated, but the solution to it is not. Consider the following query:

mysql_query("SELECT * from employees where username='".$_POST['user_name']."'");

The above statement simply takes the input entered in a text box, "user_name" and binds it in a SQL query. Now in case of SQL Injection, assume the value of $_POST['user_name'] is entered as:
' or '1'='1

So the final query becomes:

Monday, March 14, 2011

Drag and drop shopping cart

Hi,

I am compiled this script where the users can simply drag and drop products to shopping cart. For this jQuery has been used. The important thing to keep in mind are the syntax which makes an item draggable and an item droppable. You will find the entire source code at the end of this post, featuring the shopping cart functionality. So the things to keep in mind are:


$( ".draggable" ).draggable({ opacity: 0.7, helper: "clone",
start: function(){
...................
        .....................
       },
});


The above draggable function makes the element whose class name is "draggable", a draggable element. Same goes for the element where I am dropping:


$( ".drop_zone" ).droppable({
drop: function( event, ui ) {
.....................
}
})

Apart from this everything else is just basic PHP concepts of shopping cart. Here is what happens:


When the products are dragged and dropped in the shopping cart box it gets added in the cart as:

The vital part in this is the drag and drop. Whenever an item is dropped in the shopping cart a function is called where I have put the ajax call. The event to call the function is as follows:

Saturday, March 12, 2011

Facebook type getting a list of all logged in active users in realtime

Hi,

If you have used social networks such as facebook. They have a feature of showing all your friends who are online. I have made a custom code to achieve the same. But in my case instead of seeing online friends, I am checking for all online users. But of course you can change that logic to serve your purpose. You will find the code at the bottom of this page, but first let me explain what is happening.

By default i have created the following users:


To demonstrate this, I need to open atleast 2 different browsers. I am using Chrome for hasan/hasan login to see what happens:
In this the user sees 3 inactive users. Now I will login using user/user credentials in Safari. Following is what happened without page refresh in the above screen:
Now if the second user instead of logout, just closes the window, or tab then again in few seconds the first user will get the following:

Friday, March 11, 2011

Gmail style auto logout

Hi,

Assume you are logged into gmail and have opened various instance of gmail, by creating new tab or new window of the same browser. Now when you logout from any one of the instance you get logged out from all the instances. This code does exactly the same. This is how it works:


The idea here is to run a script continously in the backgroud, which always keeps checking the current session status. Whenever it finds that the session doesn't exist, it just redirects the current page to login.php. Javascript is the key, and the function which is making this happen is setTimeout(). Since I have used ajax it will not effect the actual page's performance. This is the code that got the ball rolling:

Thursday, March 10, 2011

Website Security

Hi,

Developing a website is not as easy as it may look or sound. Every time you write a code you need to keep two things in mind. Most important performance and security. In my earlier posts(also see compression and caching) I had discussed about performance. In this I will explain the most common security failures in a life of a programmer.

To start with, no one or nothing can teach you how to create a hack proof system. Here is the fact. Everything is hackable, every security can be breached. But what best you can do is to mislead the hacker. There is always someone somewhere who knows more than you, and can break into your system. So the best plan is to stick to few basic rules.

HTACCESS - Security

1. Never use actual URL's. 

Always try to mask the URL using htaccess. For example you have an image:
<img src="img/logo.jpg" /> now, instead of "img", keep the "logo.jpg" in some other directory with a name not easily identifiable, such as "assets/image_lib", where assets is a directory and images_lib the subdirectory. Now to make "images/logo.jpg" point to "assets/image_lib/logo.jpg", create a .htaccess in root directory with the following URL rewrite:

RewriteEngine on
RewriteRule ^img/(.*).(jpg|png|gif|jpeg)$ assets/image_lib/$1.$2 [L]

2. Forbid Directory

Even if someone gets to know the actual directory, prevent from seeing the content of the directory, for this create a new .htaccess file inside the directory whose access you want to forbid with the following:

Custom Dropdown with jQuery

Hi,

If you want to customize the conventional dropdown box in HTML, then here is what you need. In this you can put images, hyperlinks anything as the dropdown options. Here is how it looks like:

and the options as:


and finally after selecting:

Force Download with PHP

Hi,

Force downloading a file is commonly used in various asset management websites. The problem that a programmer faces is mainly with image or text files. If you put a simple hyperlink to a file, then on clicking the link it starts the download process automatically. But not for images or texts, because the image or text itself gets displayed in the browser, instead of downloading.

So in this code, no matter what ever your file its, it will always start the download process:

Step 1: create a hyperlink as follows:

<a href="download.php?file=my_pic.png">Download</a>

Step 2: create a "download.php" file in the same directory with the following:



<?php
session_start();
$file="my_asset/".$_GET['file'];
$ext=array_pop(explode(".",$file));
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
SWITCH($extension) {
  case 'dmg':
    header('Content-Type: application/octet-stream');
    break;
  case 'exe':
    header('Content-Type: application/exe');
    break;
  case 'pdf':
    header('Content-Type: application/pdf');
    break;
  case 'sit':
    header('Content-Type: application/x-stuffit');
    break;
  case 'zip':
    header('Content-Type: application/zip');
    break;
  default:
    header('Content-Type: application/force-download');
    break;
}
header("Content-Transfer-Encoding: binary");
readfile($file);
?>

and you are done.

But this code is just for a basic idea. Be careful of not letting the end users to type in any file name in the URL and get them downloaded. It will not be safe. So I have given, "my_asset/". But again, this code is just to understand how force download works. Use it smartly while implementing.

Best,

Wednesday, March 9, 2011

Performance Optimization - Part 2

Hi,

In my pervious post I had explained few reasons of slow server response time along with its solution. In this I will discuss how even after the response is received from the server, the page tend to load in the browser slowly. Following can be the reasons for that:


1. Heavy CSS and Javascript files
2. Too many images
3. Extensive DHTML processing loops


1. Heavy CSS and Javascript files
Sometimes using too many javascript libraries increases the size of Javascripts resulting in slow page. The best solution for this is choosing the Javascript framework smartly. If you are using common layout for multiple pages, then put only those JS files in the layout which will be common to all pages e.g. jquery.js. If you are using a package which is used only in few pages and not all, then do not put those in the layout, instead put them indivisually in each page e.g. the google map js.

Second and probably the best way to optimize JS and CSS usage is by JS/CSS compression. If you use gzip compression for CSS and Javascript, on an average it reduces the size by 80%, which really boosts up the speed. Click here to view my article on JS/CSS compression. It is really easy and extremely effective.

Install firebug in your Mozilla browser to analyze the above.

2. Too many images


Tuesday, March 8, 2011

Performance Optimization

Hi folks,

Improving the performance of a website has haunted the programmers for a long long time. In this post I would try to make it a little easy. But before you could start making super fast websites, you need to know how page request and response takes place. Because code might not be the only culprit in every case for slow websites.

Here are few reasons which might result in slow websites:

1. SQL Queries
2. Non indexed database tables
3. API calls in looping sequences

The above reasons will result in slow response from the server. During this you will keep on seeing "waiting for www.yoursite.com" in the status bar of your browser for a long time.

Finally, when the "waiting.." stage is over but still the actual page takes time to get downloaded in the browser, then following might be the reason:

4. Heavy CSS and Javascript files
5. Too many images
6. Extensive DHTML processing loops

In this post I will discuss the 1st three points, remaining I will discuss in future posts. So coming to our first point:

Monday, March 7, 2011

Create zip file on the fly with PHP

Hi,

This post is about creating zip files on the fly. I have found a class over the internet which allows you to do that. First of all you need to download the class file. Click here to download the class file. Once you have downloaded the code, create another file example.php and put the following:


<?php
require "zip.class.php";
$zipfile = new zipfile;

function make_archieve($location,$type,$filename,$zipfile)
{
if($type=="dir"){
$dir=opendir($location);
$i=0;
while($files=readdir($dir)){
if($i>1 && filetype($location."/".$files)!="dir"){
$tmp_location=str_replace("./","",$location);
$tmp_location=$tmp_location."/";
if($tmp_location=="./"){$tmp_location="";}
$zipfile->create_file(file_get_contents($location."/".$files), $tmp_location.$files);

Sunday, March 6, 2011

Creating/posting sitemaps for your blogpost blog in google, bing and yahoo

Hi,

If you are a blog addict and want to let the big search engines know, about your blog then posting sitemap can really boom your business. Here is how you can do it. For this you definitely do no need to have any SEO knowledge whatsoever.

For submitting in Google:
First of all you need to create a webmaster account for your blogspot.com blog. This go to https://www.google.com/webmasters/tools/home?hl=en and add your website.

For Bing and Yahoo there are no such prerequisites. Now we move on to creating our sitemaps. For this I came across an excellent tool, http://digitalinspiration.com/tools/blogger/sitemap/. Just type in your blogspot URL in the following:

After submitting it you will get a list something like:

Trigger javascript events manually

Hi,

This is a very interesting code segment I got from one of my friends. In this you can actually trigger any event manually. This gets very useful in daily programming, when you want to perform same set of task/s with multiple events. I am not referring to creating a common function, but creating a single function or set of functions and the event which is calling the function, you can actually cause the event to occur via code.

First of all you need to download a stable version of jquery.js and use it in your following code:


<html>
<head>
<title> execute button click event automatically using jQuery trigger() method</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {          
$('#btn1').bind('click', function() {
alert('You selected the First Button');
});
$('#btn2').bind('click', function() {
alert('You selected the Second Button');
});

Saturday, March 5, 2011

Extract details from a MP3 file, ID3 Tags

Hi,

In this post, code that I have given below will let you extract the basic information(ID3 tags) from a simple mp3 file. This is not a very advanced version, but it will serve the purpose. The idea is very simple, the details of the music files are appended at the end of the file content. We just need to extract those using fread(). The thing you need to know is what data is stored at what location.

Create a file "example.php" and copy and paste the following code:


<?php
$mp3 = "song.mp3";

$genre_arr = array("Blues","Classic Rock","Country","Dance","Disco","Funk","Grunge", "Hip-Hop","Jazz","Metal","New Age","Oldies","Other","Pop","R&B", "Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska", "Death Metal","Pranks","Soundtrack","Euro-Techno","Ambient", "Trip-Hop","Vocal","Jazz+Funk","Fusion","Trance","Classical", "Instrumental","Acid","House","Game","Sound Clip","Gospel", "Noise","AlternRock","Bass","Soul","Punk","Space","Meditative", "Instrumental Pop","Instrumental Rock","Ethnic","Gothic", "Darkwave","Techno-Industrial","Electronic","Pop-Folk", "Eurodance","Dream","Southern Rock","Comedy","Cult","Gangsta",
 "Top 40","Christian Rap","Pop/Funk","Jungle","Native American", "Cabaret","New Wave","Psychadelic","Rave","Showtunes","Trailer",
 "Lo-Fi","Tribal","Acid Punk","Acid Jazz","Polka","Retro", "Musical","Rock & Roll","Hard Rock","Folk","Folk-Rock", "National Folk","Swing","Fast Fusion","Bebob","Latin","Revival", "Celtic","Bluegrass","Avantgarde","Gothic Rock","Progressive Rock",
 "Psychedelic Rock","Symphonic Rock","Slow Rock","Big Band", "Chorus","Easy Listening","Acoustic","Humour","Speech","Chanson",
 "Opera","Chamber Music","Sonata","Symphony","Booty Bass","Primus", "Porn Groove","Satire","Slow Jam","Club","Tango","Samba",
 "Folklore","Ballad","Power Ballad","Rhythmic Soul","Freestyle", "Duet","Punk Rock","Drum Solo","Acapella","Euro-House","Dance Hall");

Google Sitemaps - Indexing URL's in Google

Hi,

Google sitemaps are an excellent way to let google know about the various webpages of your website. By default the google will crawl your website once in a while, but if you create sitemaps and submit them to google, then the indexing gets speed up and also a lot of pages might get indexed in google search engine.

By the term sitemap, I am not referring to the general websites sitemap.html which tell you what are the links and what are the sub links inside the website. Google sitemaps is like a special xml file with predefined tags, each of which has an distinctive meaning. Here is a sample content of a sitemap.xml file:


<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.google.com/schemas/sitemap/0.90">
  <url>
    <loc>http://www.url.com/</loc>
    <lastmod>2010-01-27T23:55:42+01:00</lastmod>
    <changefreq>daily</changefreq>
    <priority>0.5</priority>
  </url>
  <url>
    <loc>http://www.url.com/page1.html</loc>
    <lastmod>2010-01-26T17:24:27+01:00</lastmod>
    <changefreq>daily</changefreq>
    <priority>0.5</priority>
  </url>
  <url>
    <loc>http://www.url.com/page2.html</loc>
    <lastmod>2010-01-26T17:24:27+01:00</lastmod>
    <changefreq>daily</changefreq>
    <priority>0.5</priority>
  </url>
</urlset>

The given tags are predefined. <loc> contains the URL you want to index, <lastmod> is when the content was last modified, <changefreq> is how often its content gets changed and <priority> is how important is the file; where 1 is most important and .1 is least.

Thursday, March 3, 2011

Reading directory content

Hi,

If you are not sure about the content of a directory, this is how you can get it. This is helpful in scenarios e.g.  where the admin or any other user uploads music files, images etc to a specific directory in the server via some FTP client(e.g. filezilla) instead of a conventional web page with file uploader.

To achieve this you just need 2 main functions, opendir() and readdir(). Here is how I had done it:
<?php
$dir_path="repository/files/";
$browse_directory = opendir($dir_path);
while($entries = readdir($browse_directory)) {
$dir_array[] = $entries;
}
closedir($browse_directory);
$index_cnt= count($dir_array);
Print ($index_cnt." files<br>\n");

sort($dir_array);
print("<TABLE border=1 cellpadding=5 cellspacing=0 class=whitelinks>\n");
print("<TR><TH>Filename</TH><th>Type</th><th>File size</th></TR>\n");
for($index=0; $index < $index_cnt; $index++) {
print("<TR><TD><a href=\"$dir_array[$index]\">$dir_array[$index]</a></td>");
print("<td>");
print(filetype($dir_path.$dir_array[$index]));
print("</td>");
print("<td>");
print(filesize($dir_path.$dir_array[$index]));
print("</td>");
print("</TR>\n");
}
print("</TABLE>\n");
?>
The output of the above will be something like:

Wednesday, March 2, 2011

Adding a WWW at the beginning of a URL automatically

Hi,

If you want to add a "www" infront of your web URL automatically, here is how you can achieve it. For this you will need a .htaccess file located at the root directory of your website with the following:


RewriteEngine on
Options FollowSymlinks
rewritecond %{http_host} ^my_website.com [nc]
rewriterule ^(.*)$ http://www.my_website.com/$1 [r=301,nc]

"my_website" is the name of your website.

Similarly if you want to remove a "www" from the URL:


RewriteEngine on
Options FollowSymlinks
rewritecond %{http_host} ^www.my_website.com [nc]
rewriterule ^(.*)$ http://my_website.com/$1 [r=301,nc]

Hope it helps

Tuesday, March 1, 2011

Parse XML with PHP

Hi,

Parsing XML have been a headache for quit a few programmers, including me ;) . So in this post I will give a very simple approach to achieve it. First let us consider an XML file, "simple.xml" with the following content:


<products>
 <product>
  <name>iPhone</name>
  <currency>$</currency>
  <price>199.99</price>
 </product>
 <product>
  <name>Galaxy Tab</name>
  <currency>$</currency>
  <price>299.99</price>
 </product>
</products>

Our motive is to navigate through each product and display their details in a listed format such as:



During such parsing all you have to do is to use getElementsByTagName() function smartly. Here there is only 1 "products" tab but multiple "product" tag. So we need to run the loop on the "product" tag.

Here is how I have had done this. Create another file, "example.php" with the following:

Windows Authentication - Hiding URL's from search engines and users

Hi,

If you want to put windows authentication to your website, it can be achieved by simply using 2 files. One is the .htaccess and the other is the .htpasswd. The idea of using this is to prevent certain sections of your website to be accessed by the end user or from being crawled by search engines. For example, if you have a admin in a separate folder but in the same root directory of the site, then obviously you do no want your admin pages to get indexed by search engine. This is when windows authentication comes in play.

Whenever search engines try to crawl your website and finds a windows authentication to a page, the URL does not get indexed. And even if by chance any user gets to know such an URL, they cannot see the page unless they have entered the correct credentials. I am using localhost for this demonstration. Here is how an authentication box looks like:


Here is how you can achieve this. Create or modify your .htaccess file and add in the following: