Monday, January 17, 2011

How to embed YouTube Videos as Valid XHTML 1.0 ?

Youtube embed code help us to embed the youtube videos in our webapge. The youtube embed code is similar as follows.
<object width="640" height="385"><param name="movie" value="http://www.youtube.com/v/me0zQaMqhPY?fs=1&amp;hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/me0zQaMqhPY?fs=1&amp;hl=en_US" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="385"></embed></object>
If we embed the youtube embed code in our html page, normally we fails in the w3c validation. If we validate this page we can see that the error is because of the <embed> tag. The <embed> tag inserts a non-standard object or external content (typically non-HTML) into the document.

To remove the errors from the webapge we can remove the <embed> tag. The code is similar as follows.
<object type="application/x-shockwave-flash" width="640" height="385" data="http://www.youtube.com/v/me0zQaMqhPY"><param name="movie" value="http://www.youtube.com/v/me0zQaMqhPY"></object>
This will remove the w3 error message.
We can add the wmode by adding the following code
<param name="wmode" value="transparent">

You can set the autoplay feature by adding the autoplay parameter in the url.
&autoplay=1
like as follows
data="http://www.youtube.com/v/me0zQaMqhPY&autoplay=1"

Tuesday, January 11, 2011

Pagination in wordpress

If we have a large number of posts in wordpress , its not good to list all posts in a single page. So we need to restrict the listing of the posts. The query_posts() returns posts from the database . The main disadvantages of query_posts() is the lack of pagination .We can use parameters to change the listing of posts. Suppose we have a number of 50 posts in our site, it’s better to use pagination in the site. Here am trying to explain about how to use pagination in wordpress with query_posts().

First we need to install a plugin for pagination. We can use WP-Paginate plugin for pagination. We can download the plugin from the following link http://wordpress.org/extend/plugins/wp-paginate/ and install the plugin.

Add the following code in the page where you want to set pagination links.

<div class="navigation_nav">
<?php if(function_exists('wp_paginate')) {
wp_paginate();
} ?></div>

The above code will generate pagination navigation in the post page.

Next is to set the parameters for the query_posts(). We need to get the current page number and the pagination page number.

Add the following code before query_posts() to get the page number.
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
The above code get the page number from the GET variables. If the variable is not set , the page number is set to 1;

Next we need to pass the parameters to query_posts(). Use the following code to pass the parameters to query_posts().
query_posts("&paged=".$paged)
This will display a pagination link in the post page. We can set the number of posts to display by setting the 'posts_per_page' variable.
Similar as follows
query_posts("&paged=".$paged."&posts_per_page=10")
Also we can set the property in the admin side.

To set the post per page using admin panel
Go to Settings -> Select Reading -> edit 'Blog pages show at most' to your number.
But priority for post per page will be with the code that we added in the page.

Full source code:

After applying the codes the page will be similar as follows.


<?php
// get the page number and get the posts
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$q = "paged=".$paged.'&posts_per_page=2';
query_posts($q);
?>

<div class="navigation_nav">
<?php
// pagination links
if(function_exists('wp_paginate')) {
wp_paginate();
} ?></div>

<?php
// listing of posts
if (have_posts()) :
while (have_posts()) : the_post();
$custom_fields = get_post_custom(get_the_ID());
?>

Tuesday, January 4, 2011

Static DIV in a webpage

For an html object, there are five position properties: static, relative, absolute, fixed and inherit.
We can use fixed property to set a DIV fixed in a webpage and stays in the same place while scrolling.
The IE6 does not support position: fixed and shows it in the position following this text where it has been coded and it will scroll.

A position: fixed div needs to be positioned with regard to the intended viewport size. A div with position: fixed; top: 700px will never show on a screen resolution of 800 x 600 and scrolling will not make it appear.

The code is
<div id="static1">static DIV</div>
The styles are:-
#static1 { position: fixed; top: 95px; left: 30px; width: 220px; height: 40px; background-color:#00CCFF; }
Full 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>Static DIV</title>
<style>
#static1 {
background-color:#00CCFF;
height:40px;
right:5px;
position:fixed;
bottom:5px;
width:220px;
}
</style>
</head>
<body>
<div id="static1">Static DIV</div>
<div style="height:1000px;">
page contents
</div>
</body>
</html>

Sunday, December 19, 2010

session using php - sample code

A session is similar as a variable that resides in the server. The sesion variable is a global variable that can be used in all pages in a website. We can hold the userids, user email , privilages etc in the session.

The following is a sample code for session hanling. We can use an object oriented programming to handle the session.

Step 1 :
The SessionManager class is the session handler file. It contains the functions to create session, to store content to session, view the session content, delete session etc.

<?php
class SessionManager
{
public function __construct()
{

}

public function getSession($name = 'admin')
{
return $this->hasSession() ? ($_SESSION[$name]) : null;
}

public function hasSession($name = 'admin')
{
return (isset($_SESSION[$name]));
}

public function createSession($content,$name = 'admin', $override = false)
{
if(!$this->hasSession() || ($this->hasSession() && $override) )
{
$_SESSION[$name] = $content;
session_write_close();
return true;
}
else
{
return false;
}
}

public function destroySession ($name = 'admin')
{
$_SESSION[$name] = null;
unset($_SESSION[$name]);

return true;
}
}
?>
The createSession function creates the session . If we pass the session name it will create a session with the passing name, otherwise it will create session with tha name as 'admin'.
The 'hasSession' function checks whether the session is existing or not. It will return true, if the session exists.The 'getSession' function returns the informations stored in the session.

The 'destroySession' function destroys the session details.

Step 2:
Create an object for the SessionManager. Here we are using conditions to display how these functions are working.


<?php
session_start();
include_once 'SessionManager.class.php';
$sess = new SessionManager();
extract($_GET);
if($type==1)
{
$advalue = array('adid'=>1,'adname'=>'main admin','privilage'=>'super','lastlogin'=> time());
$sess->createSession($advalue);
}
else if($type==2)
{
echo "<pre>";
print_r($sess->getSession());
echo "</pre>";
}
else if($type==3)
{
$sess->destroySession();
}
?>
<a href="?type=1"> Create Session </a> <br>
<a href="?type=2">View Session</a> <br>
<a href="?type=3"> Delete Session </a> <br>


Here we are storing an array in the session.

Wednesday, November 24, 2010

Creating an RSS feed with PHP and MySQL

What is RSS feed ?

RSS (most commonly expanded as Really Simple Syndication) is a family of web feed formats used to publish frequently updated works—such as blog entries, news headlines, audio, and video—in a standardized format. An RSS document (which is called a "feed", "web feed", or "channel") includes full or summarized text, plus metadata such as publishing dates and authorship. Web feeds benefit publishers by letting them syndicate content automatically. They benefit readers who want to subscribe to timely updates from favored websites or to aggregate feeds from many sites into one place. RSS feeds can be read using software called an "RSS reader", "feed reader", or "aggregator", which can be web-based, desktop-based, or mobile-device-based.
http://en.wikipedia.org/wiki/RSS_feed

RSS is a technology that is being used by millions of web users around the world to keep track of their favorite websites.
Using RSS feed we can share our website content with the rest of the Internet.

The RSS format is based on XML that is built using standardised tags. Following is an example of RSS document.
<rss version="2.0">
<channel>
<title>RSS Feed</title>
<description>RSS Feed</description>
<link>http://mywebsite.com</link>
<lastBuildDate>Wed, 24 Nov 2010 09:47:31 +0100</lastBuildDate>
<language>en-us</language>
<copyright>Copyright (C) 2010 mywebsite.com</copyright>

<item>
<title>Sample title one</title>
<link>http://mywebsite.com/news1.html</link>
<description>This is the description of the smaple title one</description>
<pubDate>Wed, 10 Nov 2010 11:04:12 +0100</pubDate>
</item>
<item>
<title>Sample title two</title>
<link>http://mywebsite.com/news2.html</link>
<description>This is the description of the smaple title two</description>
<pubDate>Wed, 10 Nov 2010 11:03:24 +0100</pubDate>
</item>
<item>
<title>Sample title three</title>
<link>http://mywebsite.com/news3.html</link>
<description>This is the description of the smaple title three</description>
<pubDate>Wed, 10 Nov 2010 11:01:53 +0100</pubDate>
</item>
</channel>
</rss>

We can generate an RSS feed similar as the above sample using PHP and MySQL.

In this example we are listing the latest articles from the database are feed. For that we need a database table . If not not created, we can create a table using the following code..

CREATE TABLE `articles` (
`id` int(11) unsigned NOT NULL auto_increment,
`title` varchar(255) NOT NULL default '',
`link` varchar(255) NOT NULL default '',
`introtext` mediumtext NOT NULL,
`created` datetime NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

RSS feeds are using XML tags. So we are going to generate the XML tags using PHP.

Step 1 : Creating the header

header("Content-Type: application/rss+xml; charset=ISO-8859-1");

The first step is that , we need to tell PHP that what type of data we would like to output. In the header function we are specify that the content type is " application/rss+xml ". This will output a XML formated data into the browser.

Step 2 : Setup a Database connecction

Create a database connection to fetch the datas from the database.

DEFINE ('DB_USER', 'dbusername');
DEFINE ('DB_PASSWORD', 'dbpassword');
DEFINE ('DB_HOST', 'dbroot');
DEFINE ('DB_NAME', 'dbname');

$connection = @mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die('Could not connect to database');
mysql_select_db(DB_NAME) or die ('Error.. Could not connecct to database');
$query = "SELECT * FROM articles ORDER BY id DESC";
$result = mysql_query($query) or die ("Error.. Could not execute query");

Step 3 : Add RSS Feed Information

Next add the information about our RSS feed such as the title of it, the description, and a link to the the site.
Also add the xml version, rss version etc.

$rssfeed = '<?xml version="1.0" encoding="UTF-8"?>';
$rssfeed .= '<rss version="2.0">';
$rssfeed .= '<channel>';
$rssfeed .= '<title>RSS Feed</title>';
$rssfeed .= '<description>RSS Feed</description>';
$rssfeed .= '<link>http://mywebsite.com</link>';
$rssfeed .= '<lastBuildDate>Wed, 24 Nov 2010 09:47:31 +0100</lastBuildDate>';
$rssfeed .= '<language>en-us</language>';
$rssfeed .= '<copyright>Copyright (C) 2010 mywebsite.com</copyright>';
Step 4 : Adding RSS Items

Next, we need to extract our data by looping through our MySQL database to create the <item> tags.

while($row = mysql_fetch_array($result))
{
extract($row);
$rssfeed .= '<item>';
$rssfeed .= '<title>' . $title . '</title>';
$rssfeed .= '<link>http://mywebsite.com/news'.$id.'.html</link>';
$rssfeed .= '<description>[CDATA[' .$introtext . ']]</description>';
$rssfeed .= '<pubDate>' . $created . '</pubDate>';
$rssfeed .= '</item>';
}

Make sure you escape any characters that might cause your XML to invalidate, these characters include <, >, & - I like to enclose any content that may contain HTML inside a CDATA section.

Step 5: Close Channel, RSS tags and output the rssfeed.

$rssfeed .= '</channel>';
$rssfeed .= '</rss>';

echo $rssfeed;


Step 6: Validate your feed

Validate your feed using FeedValidator.org.


Full Source Code:
<?php
header("Content-Type: application/rss+xml; charset=ISO-8859-1");
DEFINE ('DB_USER', 'root');
DEFINE ('DB_PASSWORD', '');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'fourjmktg9908_iapc');
$connection = @mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die('Could not connect to database');
mysql_select_db(DB_NAME) or die ('Error.. Could not connecct to database');
$query = "SELECT * FROM jos_content ORDER BY id DESC";
$result = mysql_query($query) or die ("Error.. Could not execute query");

$rssfeed = '<?xml version="1.0" encoding="UTF-8"?>';
$rssfeed .= '<rss version="2.0">';
$rssfeed .= '<channel>';
$rssfeed .= '<title>RSS Feed</title>';
$rssfeed .= '<description>RSS Feed</description>';
$rssfeed .= '<link>http://mywebsite.com</link>';
$rssfeed .= '<lastBuildDate>Wed, 24 Nov 2010 09:47:31 +0100</lastBuildDate>';
$rssfeed .= '<language>en-us</language>';
$rssfeed .= '<copyright>Copyright (C) 2010 mywebsite.com</copyright>';
while($row = mysql_fetch_array($result)) {
extract($row);
$rssfeed .= '<item>';
$rssfeed .= '<title>' . $title . '</title>';
$rssfeed .= '<link>http://mywebsite.com/news'.$id.'.html</link>';
$rssfeed .= '<description>[CDATA[' .$introtext . ']]</description>';
$rssfeed .= '<pubDate>' . $created . '</pubDate>';
$rssfeed .= '</item>';
}
$rssfeed .= '</channel>';
$rssfeed .= '</rss>';
echo $rssfeed;
?>

Save this file as index.php and save it in the folder named 'feed'. Now we can directly access the rss feeds from the browser using the link ' http://mywebsite.com/feed '

Monday, November 22, 2010

How to resize youtube embed video using regular expression ?

When we are creating a web application that let the user insert video embeds coming from YouTube or from Vimeo, or what ever else, there is the problem of the embed size. Most probably they will directly insert the embed code, that they are copied from youtube. This size of object tag (iframe, embed, object) may affect our design. If we are creating a video gallery we need to resize the embed code video into our size. In PHP we can use regular expression to resize the embed code.

Sample Code
<?php
//eg :
$video = "<object width="640" height="385">

<param value="http://www.youtube.com/v/bIx5vDn28eE?fs=1&amp;hl=en_US" name="movie" />

<param value="true" name="allowFullScreen" />

<param value="always" name="allowscriptaccess" /><embed width="640" height="385" allowfullscreen="true" allowscriptaccess="always" type="application/x-shockwave-flash" src="http://www.youtube.com/v/bIx5vDn28eE?fs=1&amp;hl=en_US"></embed></object>";


// our prefered size : width="208" height="103"
// regular exression to change the height and width
$pattern = "/height=\"[0-9]*\"/";
$video = preg_replace($pattern, "height='103'", $video);
$pattern = "/width=\"[0-9]*\"/";
$video = preg_replace($pattern, "width='208'", $video);
echo $video;

?>
The above code will resize the embed video into the size we are given.

If we want to add the 'wmode' in the video we can assign that value along with the width parameter.

eg :
$video = preg_replace($pattern, "width='208' wmode='transparent'", $video);

Thursday, November 18, 2010

How to check a radio button list is checked or not using javascript?

How to check a radio button list is checked or not using javascript ?


Radio Buttons are work in groups .If we have a set of radio buttons on a form , they are unchecked by default. We want an alert message if the radio buttons are not checked on submit.

Radio buttons are stored as an array, so we have to loop the array elements to see if one is checked or not.

To determine whether a particular button is pressed the syntax required is:
test = document.formName.radioGroupName[indexNumber].checked;

This will result a TRUE or False value . If the radio button is checked it will result a TRUE value, otherwise FALSE.

Sample Code

<script language="javascript">

function validate()

{

var flag = false;

for(var i =0 ;i<document.frmgraph.cond1.length; i++)

{

if(document.frmgraph.cond1[i].checked)

flag = true;

}

if(flag == false)

{

alert("Please select the group");

return false;

}

return true;

}

</script>

<form id="frmgraph" name="frmgraph" method="post" onsubmit="return validate();">

Male <input type="radio" name="cond1" id="cond1" value="male" />

Female <input type="radio" name="cond1" id="cond1" value="female" />

<input type="submit" name="btnSubmit" id="btnSubmit" value="Submit" />

</form>



In this function the javascript will alert a message if the radio button is not checked.