| 0 comments ]

Creating Google map and adding markers ans polyline on it

save this as map.html

this is used to show the google map.

replace URAPIKEY with the the APIIKEY Get while you register on the http://code.google.com/apis/maps/signup.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Maps JavaScript API Example</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=URAPIKEY"
type="text/javascript"></script>
<script type="text/javascript">

//<![CDATA[

function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl())
map.setCenter(new GLatLng(9.9798480,76.5738070), 8);

var side_bar_html = "";
var gmarkers = [];
var htmls = [];
var i = 0;


// A function to create the marker and set up the event window
function createMarker(point,name,html) {
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
// save the info we need to use later for the side_bar
gmarkers[i] = marker;
htmls[i] = html;
// add a line to the side_bar html
i++;
return marker;
}


// This function picks up the click and opens the corresponding info window
function myclick(i) {
gmarkers[i].openInfoWindowHtml(htmls[i]);
}

// Read the data from example4.xml

var request = GXmlHttp.create();
request.open("GET", "map.xml", true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
var xmlDoc = GXml.parse(request.responseText);
// obtain the array of markers and loop through it
var markers = xmlDoc.documentElement.getElementsByTagName("marker");

for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new GLatLng(lat,lng);
var html = markers[i].getAttribute("html");
var label = markers[i].getAttribute("label");
// create the marker
var marker = createMarker(point,label,html);
map.addOverlay(marker);
}
// put the assembled side_bar_html contents into the side_bar div
//document.getElementById("side_bar").innerHTML = side_bar_html;


// ========= Now process the polylines ===========
var lines = xmlDoc.documentElement.getElementsByTagName("line");
// read each line
for (var a = 0; a < lines.length; a++) {
// get any line attributes
var colour = lines[a].getAttribute("colour");
var width = parseFloat(lines[a].getAttribute("width"));
// read each point on that line
var points = lines[a].getElementsByTagName("point");
var pts = [];
for (var i = 0; i < points.length; i++) {
pts[i] = new GLatLng(parseFloat(points[i].getAttribute("lat")),
parseFloat(points[i].getAttribute("lng")));
}
map.addOverlay(new GPolyline(pts,colour,width));
}
// ================================================
}
}
request.send(null);




}
}

//]]>
</script>
</head>
<body onload="load()" onunload="GUnload()">
<div id="map" style="width:800px;height:500px"></div>
</body>
</html>




save map.xml.
this is used to show the markers and polilines . we need to the specify the markers line points


<markers>
<marker lat="9.9396253" lng="76.2594981" html="Cochin http://phpqa.blogspot.com"/>
<marker lat="9.9798480" lng="76.5738070" html="Muvattupuzha http://phpqa.blogspot.com"/>
<marker lat="9.5864460" lng="76.5217970" html="Kottayam http://phpqa.blogspot.com"/>
<marker lat="8.9973910" lng="76.7756730" html="Kottarakkara http://phpqa.blogspot.com"/>
<marker lat="8.5036960" lng="76.9521870" html="Trivandrum http://phpqa.blogspot.com"/>

<line colour="#008800" width="8" html="You clicked the green polyline">
<point lat="9.9396253" lng="76.2594981"/>
<point lat="9.9798480" lng="76.5738070"/>
<point lat="9.5864460" lng="76.5217970"/>
<point lat="8.9973910" lng="76.7756730"/>
<point lat="8.5036960" lng="76.9521870"/>
</line>

</markers>


Enjoy Google mapping LOL :)

| 0 comments ]

OOP in PHP5

What is an object?

Ans: A group information that holds the information about data,
methods from a class.

What is a class?

Ans : A collection of data and methods

What is an interface?

Ans: In OOP model inheritance is used to provide a interface
between unrelated classes and methods

What is inheritance, and why do you need it?

Ans: its is a method of the inheriting the properties of base
class into an another class. Its use ful when we need a class with
more functionality than the parent class. So we simply inherit the
base class to the new class. The new class has all the properties of
base class plus the the additional methods added in the new class

What is the Hollywood principle?

Ans: No idea

What is coupling?

Ans: its is described as how the one module is related to the the
other modules

What is tight coupling, is it bad or good?

Ans : if One module is heavily related to the the other modules is
referred as tight coupling . It is not good.

What are design patterns? What design patterns do you know,
which of them do you use?

Ans : No idea

What is the difference between equations of objects $a == $b and
$a === $b?

Ans : checks whether $a == $b equals, but the $a === $b is not only
checks equal, but also check its type.

What is the garbage collector? Describe the disadvantages of the garbage collector in PHP earlier than 5.3?

Ans : It is defined as the memory management, which reallocated the
resource's memory with no future usage.


Please give me the uncompleted answers though the comments

| 0 comments ]

PHP Question and answers

What is PHP? What are the differences between PHP 4 and PHP5?


Ans : PHP is a scripting language. Its referred as hypertext preprocessor.
PHP5 has more advanced class architecture than PHP4. Its has method
access properties like protected, public, private. The constructor,
destructor methods are changed in php5. Ie writing a constructor
function has been changed also there is no destructor in php4 version.
In PHP 5 version, there is , more advanced function added.
Exception were introduced in the PHP5 version.
In PHP5 new extensions like simpleXML, DOM were introduced.

What is HTTP? What types of HTTP requests do you know?

Ans : HTTP is HyperText Transfer Protocol. It is a protocol
used to transfer hypertext requests and information between servers
and browsers.
There are two types of http requests. They are GET method and POST method.

What is SQL? What RDBMSes do you know?

Ans: SQL is Structured Query Language. I have work
experience in Mysql. But I have knowledge about Oracle, Microsoft
Access.

What is web server? What web servers do you know?

Ans: A computer which can accept http requests from clients,
and can deliver these http response in the form of web pages.
The web servers I know are Apache ans IIS

What is the difference between HTML and XML? What markup languages do you know besides HTML and XML?

Ans: HTML is used for presentation. While the XML is used for
holding the data.
HTML has predefined tags. XML has no predefined tags.
We can use our own tags in XML. It is self descriptive language.
HTML is not case sensitive, while XML is.
In HTML the close tags are not mandatory, But in XML
its must one

| 0 comments ]

Hi

I have an issue with the page templates..

I have 4 menu links in the home page. these pages are loading differently styles pages. So I have created pages in word press admin with same page slugs. They are about, products, contacts, services. I also created the same 4 php files in my new themes named about.php, products.php, contacts.php and services.php

but when I load the pages the its shows only the page templates in the page.php

I am really stuck on this

Any help appreciated ..

Thanks in advance.. Cheers,

| 0 comments ]

How can we find out scrollbar position has reached at the bottom in js

Hi,

My issue is, I need to find out the the scroll bar position,
ie whether the current scroll bar reached at the bottom of the scroll bar.
I hope you can gimme a brief idea regarding this.

Thanks in advance.

--
Thanking you, Warm regards,

jay jay

...................................................................................

ben wrote....

Hi,

It's not very hard. It's a simple matter of detecting the current scroll offset,
the height of the current window view & the height of the document.

The logic is as follows

if(horizontalScrollOffset + windowHeight == documentHeight) {
// we're at the bottom of the page
} else {
// we're not at the bottom of the page
}

Off the top of my head, the code would look something like
(I haven't tested this)

&lt;script&gt;
function hasScrolledToBottom()
{
if(scrollYOffset() + window.innerHeight &gt;= document.body.offsetHeight) {
return true;
} else {
return false;
}
}

function scrollYOffset()
{
var ScrollTop = document.body.scrollTop;
if (ScrollTop == 0) {
if (window.pageYOffset) {
ScrollTop = window.pageYOffset;

} else {
ScrollTop = (document.body.parentElement) ?

document.body.parentElement.scrollTop : 0;
}
}
return ScrollTop;
}
&lt;/script&gt;

&lt;body style="height: 4000px; "&gt;
&lt;/body&gt;

Ben Rowe

......................................................

Brian Schilt Wrote

You would need to compare the overall document height with the
scrollTop position + viewport height. You could make a utility
function that you could use in the scroll event that fires when the
page is scrolled. When it reaches bottom the function could return
true, signifying the user has scrolled all the way to the bottom.

I haven't tested the below code, but the theory is there for you to
start with.

$(window).scroll(function(){
if(isScrollBottom()){
//scroll is at the bottom
//do something...
}

});

function isScrollBottom() {
var documentHeight = $(document).height();
var scrollPosition = $(window).height() + $(window).scrollTop();
return (documentHeight == scrollPosition);

}

Brian

| 0 comments ]

Relational DBMSes


There is a table of two fields, primary key integer ID and
char(50) VALUE. Before adding the unique index to it, you need to
know, if there are duplicated VALUEs in the table. How you will do it?

Ans: should check the primary key integer is repeating in the
primary key field. If any one value from the field returning the
count greater than 1, we can not add unique index to the the field

What's the difference between INNER JOIN and OUTER JOIN? What
other types of JOINs do you know?

Ans : The INNER JOIN takes data from both tables returns the
specified data exists in both tables. But the OUTER JOIN check both
tables and returns values from the outer table when the criteria mets.

Other major join are LEFT OUTER JOIN, RIGHT OUTER JOIN.

What is a VIEW? What are the advantages and disadvantages of views?

Ans : View is a representation of a sql statement stored in
memory, which can be easily reusable.
Advantages of views:
we can view the data without storing the data into the object.
We can restict the view of a table i.e. can hide some of columns
in the tables.
We can Join two or more tables and show it as one object to user.
Disadvantages of views
we can not use DML operations on views.
When a table is dropped view will becomes inactive.. it depends on
the table objects.
It is an object so it occupies space

What's the main difference between WHERE and HAVING?

Ans: WHERE is a single row function, where as Having is based on groups.
When we use having Having we should use the Group by keyword.

What are subqueries? Does MySQL support them?

A query that is used within another query. For example a
select-statement within the WHERE or HAVING clause of another SQL
statement.
Mysql supporting the subquery system.

please complete the questions through the comments

thanks

| 1 comments ]

PHP Question and answers

Do you need to initialize the variable before its usage? Why?

Ans: Actually, Its not mandatory in php. But its recommended to
initialize variable before its usage. In most of the servers the the
error reporting for display notices are disabled. In the case of
servers which enabled error reporting on for notices, its highly
recommended to initialize variable before its usage.

How do you use a function's parameters inside the function?

Ans: Information are passed to the functions as parameters
separated by commas. We can handle these parameters in several ways.
We can pass variables into the function
We can pass arrays to the function
We can set default argument values in the function parameters.

There are two non-empty arrays $a and $b. What is the result of their sum (+) ?

Ans: it will return the value of $a (the first array);


Comment the following code: $q = 'SELECT * FROM mytable WHERE id = ' . $_POST['id'] ? Is there any possibility to make it better?

Ans: $q = 'SELECT * FROM mytable WHERE id = ' . htmlentities ( mysql_real_escape_string ( $_POST['id'] ) );

How do you swap the values of string variables $a and $b, without using a third variable?
Ans : $a = "content";
$b = "not a content";
list($a,$b) = array($b,$a);
echo "new a is - ". $a;
echo "
new b is - ".$b;

What way will you choose to sort the array of strings?

Ans: Will use asort() function.

What methods can you use to start a PHP block? Which is best,and why?


Ans: we can use tags
tags
<% %> tags
The best on is tag. Because its the default code block
of php. It works on all servers , no need to edit the php.ini settings
in the server. The other blocks are referred as short tags. Its server
specific, needs to edit in the php.ini settings to activate them.

Will be the value of $a after the execution of the following line of code: $a = include 'somefile.php'; ?

Ans: It will execute the script in it

Describe the advantages and disadvantages of the various ways of configuring a Web server to process PHP scripts.

Ans: Please post your the answer as comments below

What are the sessions. How is sessions data stored at the server?

Ans: Session is defined as the instance between when a user starts a
requests to a particular webserver and closing the requests to that
server.
These informations can stored server based on the session ids. We can
store these informations on the server in its local memory, files, or
in the databases.

| 0 comments ]

Hi Joban

I work for a start-up in california. I need some help with my website development in CodeIgnitor. Could you please help me out?

Thanks, Mr.Urs

| 0 comments ]

Use of Site Map

Usually saved as sitemap.html or sitemap.php ...etcThis file will be having the list of all possible or most important links of Your website and the URL in it should be in SEO friendly mode.This will help in links traversal of search engineswhich finally result in indexing.

Link Exchange or Web Ring

A webring in general is a collection of websites from around the Internet joined together in a circular structure. When used to improve search engine rankings, webrings can be considered a
search engine optimization technique. To be a part of the webring, each site has a common

navigation bar; it contains links to the previous and next site. By clicking next (or previous) repeatedly, the surfer will eventually reach the site they started at; this is the origin of the term webring. However, the click-through route around the ring is usually supplemented by a central site with links to all member-sites; this prevents the ring from breaking completely if a member site goes offline.

A link exchange (also known as a banner exchange) is a confederation of websites that operates similarly to a web ring.Webmasters register their web sites with a central organization, that runs the exchange, and in turn receive from the exchange HTML code which they insert into their web pages. In contrast to a web ring, where the HTML code simply comprises simple circular ring navigation hyperlinks, in a link exchange the HTML code causes the display of banner advertisements, for the sites of other members of the exchange, on the member web sites, and webmasters have to create such banner advertisements for their own web sites.

Link exchanges have advantages and disadvantages from the point of view of those using the World Wide Web for marketing. On the one hand, they have the advantages of bringing in a highly targeted readership (for link exchanges where all members of the exchange have similar web sites), of increasing the "link popularity" of a site with Web search engines, and of being relatively stable methods of hyperlinking. On the other hand, they have the disadvantages of potentially distracting
visitors away to other sites before they have fully explored the site that the original link was on.

PAID INCLUSION PROGRAMS

Paid Submission

Sites pay a certain amount to have a directory editor look at their pages and evaluate them within a certain time period. Since the backlog at some directories is 4-5 months or more, this can be a good deal. However, the directory doesn't guarantee that your site will get listed - only evaluated.

Paid Placement

Used first by GoTo (now called Overture). Sites can purchase either a top rank or prominent listing for particular search terms. The listing may or may not be identified as a paid advertisement. Some search engines and directories charge a flat fee while GoTo/Overture uses a pay per click system.

Paid Inclusion

Search engines guarantee to list pages from your Web site in their database and re-spider them on a regular basis, usually at least once per week. Unlike paid placement, you aren't guaranteed a particular place in the search rankings.

| 0 comments ]

Handling Dynamic ഉരല്

One of the major reasons for using a server-side language such as PHP is for the ability to generate dynamic content. Often this will lead to single scripts that produce their content based on the input parameters (that is, the variables in the URL).

SEO friendly URLs

The SEO friendly URLs are highly encouraged for using in Dynamic Sites Navigation.
Some facts which helps in pretty good indexing of pages are:

1.No of Pages
2. Access Frequency of Pages
3. Meaningful(SEO Friendly) URLs for accessing a page
4. Link Exchange

So Lets think about the appearence of a non SEO friendly URL it may look à´²ൈà´•്
Based on the supplied URL parameters 'sec' and 'id' the respective item is fetched and shown in the browser.Here the index page is manupulated for the variant display of items.Search engines are less efficient in indexing Dynamic URLs .Inorder to over come such a situation we can do some alterations in this URL and make it more meaningful for Searchengines as well as users of the website.
I will give a suggestion for the above URL like the one below
http://culblog.com/index/technical/2/sectechniques/5/
By this technique
You can use a Static like Dynamic URL which is more meaningful to User and the search engine. Hide the technology or language you have used for creating the website.
Easily Indexibile for Search Engines. Gives a feel to Web crawlers that the site have lots of pages under lots of virtual folders. Makes Easily trackable URLs.(You can easily track from the list of URLs popdown from the addressbar of Browser). How to generate SEO friendly URLs :This is not much complex step.Its like generating the synamic URLs but some more meaning ful fields added in the URL.

A sample script for creating the dynamic URL
$row['SectionName'] "); } ?>

This will generate links liks
"Personal
"Technical
"Spiritual
"SEO Techniques
Some additional work can be done on this to make this a SEO friendly URL
We can change the above php code like this
$row['SectionName'] "); } ?>

This will generate links liks
"Personal
"Technical
"Spiritual
"SEO Techniques

If you check the fourth URL you can find a space between 'SEO' and 'Techniques'
in such cases you can replace the space with an hyphen (-).
print("$row['SectionName'] ");
and the output will be like
SEO Techniques
Avoid use of '_' instead of '-'.
Next question is how to access this URL or how Browser identify this SEO friendly URLs
This magic is done by the HTACCESS file which is placed in root of your web directory.

.HTACCESS file and URL rewrite rule


.HTACCESSFILE : .htaccess is the default name for a file that is used to indicate

who can or cannot access the contents of a specific file directory from the Internet or an
intranet. The .htaccess file is a configuration file that resides in a directory and
indicates which users or groups of users can be allowed access to the files
contained in that directory.It may also contain some rewrite rules which say
the server to access a page in it if the URL on the browser address bar satisfies
any of the rewrite rules on .htaccess file. A sample .htaccess file
all requests to whatever.htm will be sent to whatever.php:
DirectoryIndex index.php

order allow,deny
deny from all

Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.*)\.htm$ $1.php [NC]

Lets rewrite our Example URLs the .htaccess file content will be like this
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.*)\.htm$ $1.php [NC]
RewriteRule ^topics/(.+)/([0-9]+)/(.+)/([0-9]+)/$ http://%{SERVER_NAME}/index.php?sec=$2&id=$4 [nc]

Here the SEO URL
http://www.culblog.com/topics/seo-techniques/4/generate-seo-friendly-url/23
will be rewrited to
http://www.culblog.com/index.php?sec=4&id=23
http://culblog.com/index.php?sec=2&id=5

| 0 comments ]

Search engine optimisation tips

SEO Techniques

Well what you need to do is to try and get your web site listed as high as

possible in the results and there are a number of things you can do to help.
As 95% people using search engines only look at the top 20 search results,
it is important to get your web site as high as possible.

SEO factors to be considered:

1
. Page Title
2. Meta tags
3
. Page Content
4. Hyper Links
5. Images
6. Links to the Site- URL Exchange
7
. Site Using Frames
Page Title Make sure each page on your web site has a title in the head of the document.Many search engines use the title of the web page as the link to your site,so it is important that your title be as relevant and descriptive as possible. Example : Home page of Jesus youth India Meta tags Meta tags are one of the most important parts of a web page when it is indexed by a search engine.The description meta tag is very often used by a search engine to display a sort description of what your web page contains. Some search engines look at the keywords entered into the keywords meta tag and will use this to display your page in the search results if it is one of the words used in the search criteria.If you want your web site indexed then consider using Meta tags.Meta tags go in the head of your web page, in-between the HTML tags, and . There are a number of different Meta tags that you can use, but the most important ones are the Description and the Keywords Meta tags as well as having a title for the web page. Description This tag is used to give a short description of the contents of your web page,and is often used by search engines in the search results as a description of what your page contains.Example : official website,JY - is Spiritual youth movement dedicated to Christ"> Keywords To help get your web site up in the ratings you can supplement the title and description with a list of keywords, separated by commas.Most search engines will index the first 64 characters in this Meta tag. Example : content="Jesus,youth,JY,Emmavoos,Jesus Youth,Spiriual,Movement" > Revisit-After The revisit-after meta tag is useful for sites where the content changes often and tells the search engine how often to revisit your site. The example below will tell the search engine to revisit your site ever 31 days.. Example : Distribution Tells the search engine who the page is meant for and can be set to; global, for everyone, local, for regional sites, and UI, for Internal Use. Example : Robots This Meta tag is used is used to tell the search engine whether you want the web page indexed or not. The values for this tag are: - index(default) Index the page noindex Don't index the page nofollow Don't index any pages hyper-linked to this page none Same as "noindex, nofollow" Example : Meta Tag Example: Jesus Youth India Home page Page Content A number of search engines will index the first few lines of your web page, so try to make a the first few lines as descriptive as possible.Some search engines will even index your entire page. Hyper Links Try to place as many descriptive text links in your homepage to other relevant pages in your site as possible as search engines will use these links to index the other pages on your site.Usage : Issue21 Images Most sites these days contain images, so it is important that you use the ALT tag on any images to try and describe as much as possible what the image is of. Usage : my Magazine issue 21 Cover Image Links to the Site- URL Exchange Many search engines, including Google, will return your web site higher in search results by the amount of web sites that link to your site, also the higher the profile of the site that links to yours, the higher your listing is in search results again. Site Using Frames It's very difficult to get a good ranking on search engines if your Web site uses frames. The problem is that search engines do not index framed Web sites well. Actually, the search engines do such a poor job of indexing frames. If you must use frames on your Web site for some reason, make sure you use the NoFrames tag so that search engines can find some text to index. The NoFrames tag is a tag specifically for search engines that cannot read the actual pages in your frame set.

| 0 comments ]

Search engine optimisation tips

SEO techniques -Tips

You can find millions of Web site on the internet and its number is fast growing.In such a scenario We need to think about the possibilities of some pretty good strategies that make your site viewable to the Web world.

What is a Web Search Engine

A Web search engine is a search engine designed to search for information on the World Wide Web. Information may consist of web pages, images and other types of files.Commonly used search engines are Yahoo,Google,Msn,Altavista....

How Web Search Engines വര്à´•്à´•്

A search engine operates, in the following order

1. Web crawling

2. Indexing

3. Searching

Web search engines work by storing information about many web pages, which they retrieve from the WWW itself. These pages are retrieved by a Web crawler (sometimes also known as a spider) An automated Web browser which follows every link it sees. The contents of each page are then analyzed to determine how it should be indexed (for example, words are extracted from the titles, headings, or special fields called meta tags). Data about web pages are stored in an index database for use in later queries. Some search engines, such as Google, store all or part of the source page (referred to as a cache) as well as information about the web pages, whereas others, such as AltaVista, store every word of every page they find.

When a user enters a query into a search engine (typically by using key words), the engine examines its index and provides a listing of best-matching web pages according to its criteria, usually with a short summary containing the document's title and sometimes parts of the text.

Crawlers A web crawler is a program which automatically traverses the web by downloading documents and following links from page to page . They are mainly used by web search engines to gather data for indexing. Web crawlers are also known as spiders, robots, bots etc.

How Crawlers/Spiders work

Crawler-based search engines have three major elements. First is the spider, also called the crawler. The spider visits a web page, reads it, and then follows links to other pages within the site. This is what it means when someone refers to a site being "spidered" or "crawled." The spider returns to the site on a regular basis, such as every month or two, to look for changes.
Everything the spider finds goes into the second part of the search engine, the index. The index, sometimes called the catalog, is like a giant book containing a copy of every web page that the spider finds. If a web page changes, then this book is updated with new information.
Sometimes it can take a while for new pages or changes that the spider finds to be added to the index. Thus, a web page may have been "spidered" but not yet "indexed." Until it is indexed -- added to the index -- it is not available to those searching with the search engine.
Search engine software is the third part of a search engine. This is the program that sifts through the millions of pages recorded in the index to find matches to a search and rank them in order of what it believes is most relevant.

How to exclude site pages from Indexing

Exclusions can be made by the use of robots.txt. Based on the specifications in robot.txt
the specified files or directory will stay hidden from Indexing

A Sample robot.txt file

Here is what your robots.txt file should look like; _____________________________________________________________

# Robots.txt file created by http://www.webtoolcentral.com

# For domain: http://192.168.0.213
# All robots will spider the domain User-agent: * Disallow:
# Disallow Crawler V 0.2.1 admin@crawler.de
User-agent: Crawler V 0.2.1 admin@crawler.de Disallow: /
# Disallow Scooter/1.0 User-agent: Scooter/1.0 Disallow: /
# Disallow directory /cgi-bin/ User-agent: * Disallow: /cgi-bin/
# Disallow directory /images/ User-agent: * Disallow: /images/
______________________________________________________________
put this file in your root directory..

| 3 comments ]

sample page for creating dynamic elements in HTML using Javascript.
For working Please COPY & PASTE in an editor and run it on browser.
Please edit the Js part for modify the code


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>test</title>
<meta name="GENERATOR" content="Quanta Plus">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
//Please edit the Js part for modify the code
function show_new()
{
var id=document.getElementById('count').value;
var currentVal = document.getElementById('showTr').innerHTML;
document.getElementById('showTr').innerHTML = currentVal +"<tr><td align=\"center\" width=\"33%\">"+id+"<input type=\"text\" name=\"events_venue_"+id+"\" ></td><td align=\"center\" width=\"33%\"><input type=\"text\" name=\"events_title_"+id+"\" size=\"10\"></td><td align=\"center\" width=\"33%\"><input type=\"radio\" name=\"events_date_"+id+"\">Yes <input type=\"radio\" name=\"events_date_"+id+"\">No</td></tr>";
document.getElementById('count').value = parseInt(id)+1;
}

</script>
</script>
</head>
<body>
<TR>
<TR>
<td align="center" colspan="2"> <a href="javascript:void(0);" onclick="show_new()">add more</a></td>
</TR>
<tr><TD><table id="showTr">
<tr><td align="center" width="33%"><input type="text" name="events_venue" ></TDd><td align=center
width=33%><input type='text' name="events_title" size="10"></td><td align="center" width="33%"><input type="radio" name="events_date">Yes <input type="radio" name="events_date">No</td></tr>
</table>
</TD>
</tr>
<TR>
<td align="center" colspan="2"><input type="hidden" name="count" id="count" value="2"></td>
</TR>
</table>
</body>
</html>

| 0 comments ]

Here are some links for displaying Tooltips and balloons


http://www.dhtmlgoodies.com/index.html?page=tooltip
http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
http://web-graphics.com/mtarchive/001717.php
http://boxover.swazz.org/
http://www.nickstakenburg.com/projects/prototip/
http://demos.mootools.net/Tips
http://examples.learningjquery.com/62/demo/index.html#examplesection
http://ajaxian.com/archives/tooltipjs-creating-simple-tooltips
http://ashishware.com/Tooltip.shtml
http://www.twinhelix.com/dhtml/supernote/
http://www.beauscott.com/2006/08/19/ajax-enabled-help-balloons/

http://www.robertnyman.com/glt/index.htm
http://www.e-magine.ro/web-dev-and-design/46/tooltips-from-ajax-dom-nodes-or-inline-attributes-contents/
http://www.codylindley.com/blogstuff/js/jtip/
http://www.thinkvitamin.com/misc/yui-demos/demo-11.html

http://www.twinhelix.com/dhtml/tipster/demo/
http://www.texsoft.it/index.php?%20m=sw.js.htmltooltip&c=software&l=it
http://www.kryogenix.org/code/browser/nicetitle/
http://www.1976design.com/blog/archive/2003/11/21/nice-titles/

http://www.walterzorn.com/tooltip/tooltip_e.htm
http://developer.yahoo.com/yui/container/tooltip/
http://www.bosrup.com/web/overlib/

| 0 comments ]

// function for random string, in this function there are 6 different types of string functions are available.
they are alphanumeric,numeric,nonzero numeric,alphabets,alpha numerics with special charectors like -_#@ and unique one.

function randomKey($type = 'alphanum', $len = 8)
{
switch($type)
{
case 'alphanum' :
case 'numeric' :
case 'nonzero' :
case 'alpha' :
case 'alphanumspechar':

switch ($type)
{
case 'alphanum' : $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
break;
case 'numeric' : $pool = '0123456789';
break;
case 'nonzero' : $pool = '123456789';
break;
case 'alpha' : $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
break;
case 'alphanumspechar': $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-#@'; break;

}

$str = '';
for ($i=0; $i < $len; $i++)
{
$str .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
}
return $str;
break;
case 'unique' : return md5(uniqid(mt_rand()));
break;
}
}

| 0 comments ]

//function redirecting the page
function funRedirect($url = '', $type = 'location')
{
switch($type)
{
case 'refresh' : header("Refresh:0;url="($url);
break;
default : header("Location: ".($url);
break;
}
exit;
}

| 1 comments ]

| 0 comments ]

//function to find out time finished in words

function timeFinishedInWords($datetime_string, $format = 'j/n/y', $backwards = false, $return = false) {
$datetime = $this->fromString($datetime_string);

$inSeconds = $datetime;
if ($backwards) {
$diff = $inSeconds - time();
} else {
$diff = time() - $inSeconds;
}

$months = floor($diff / 2419200);
$diff -= $months * 2419200;
$weeks = floor($diff / 604800);
$diff -= $weeks * 604800;
$days = floor($diff / 86400);
$diff -= $days * 86400;
$hours = floor($diff / 3600);
$diff -= $hours * 3600;
$minutes = floor($diff / 60);
$diff -= $minutes * 60;
$seconds = $diff;

if ($months > 0) {

$relativeDate = 'on ' . date($format, $inSeconds);
$old = true;
} else {
$relativeDate = '';
$old = false;

if ($weeks > 0) {
// weeks and days
$relativeDate .= ($relativeDate ? ', ' : '') . $weeks . ' week' . ($weeks > 1 ? 's' : '');
$relativeDate .= $days > 0 ? ($relativeDate ? ', ' : '') . $days . ' day' . ($days > 1 ? 's' : '') : '';
} elseif ($days > 0) {
// days and hours
$relativeDate .= ($relativeDate ? ', ' : '') . $days . ' day' . ($days > 1 ? 's' : '');
$relativeDate .= $hours > 0 ? ($relativeDate ? ', ' : '') . $hours . ' hour' . ($hours > 1 ? 's' : '') : '';
} elseif ($hours > 0) {
// hours and minutes
$relativeDate .= ($relativeDate ? ', ' : '') . $hours . ' hour' . ($hours > 1 ? 's' : '');
$relativeDate .= $minutes > 0 ? ($relativeDate ? ', ' : '') . $minutes . ' minute' . ($minutes > 1 ? 's' : '') : '';
} elseif ($minutes > 0) {
// minutes only
$relativeDate .= ($relativeDate ? ', ' : '') . $minutes . ' minute' . ($minutes > 1 ? 's' : '');
} else {
// seconds only
$relativeDate .= ($relativeDate ? ', ' : '') . $seconds . ' second' . ($seconds != 1 ? 's' : '');
}
}

$ret = $relativeDate;

// show relative date and add proper verbiage
if (!$backwards && !$old) {
$ret .= ' ago';
}
return $this->output($ret, $return);
}

| 1 comments ]

function browserChecking(){
$browser = get_browser(null, true);
if($browser[browser]=="mozilla"){
return true;
}
else{
return true;
}
}

function isMozilla() {
$useragent=$_SERVER['HTTP_USER_AGENT'];
if (stristr($useragent, 'mozilla')){
return true;
}else{
return false;
}
}

| 0 comments ]

function browserChecking(){
$browser = get_browser(null, true);
if($browser[browser]=="IE"){
return true;
}
}

function isIeSeven() {
$useragent=$_SERVER['HTTP_USER_AGENT'];
if (stristr($useragent, 'msie 7')) {
return true;
}else{
return false;
}
}

function isIeSix() {
$useragent=$_SERVER['HTTP_USER_AGENT'];
if (stristr($useragent, 'msie 6')){
return true;
} else{
return false;
}
}

| 1 comments ]

<?php
$values = array();
$pass = "";
for($i=0;$i<10;$i++) i="65;$i<91;$i++)" i="97;$i<123;$i++)" i="0;$i<7;$i++)">>

| 1 comments ]

1 Which of the following will extract the TLD (top level domain) of ".net" from the string?

2 Which php.ini directive should be disabled to prevent the execution of a remote PHP script via an include or require construct?

3 Consider the following code:

<?php
header("Location: {$_GET['url']}");
?>

Which of the following values of $_GET['url'] would cause session fixation?

Session Fixation is not possible with this code snippet
http://http://phpqa.blogspot.com//?PHPSESSID=123
PHPSESSID%611243
Set-Cookie%3A+PHPSESSID%611234
http://phpqa.blogspot.com/%2F%0D%0ASet-Cookie%3A+PHPSESSID%611234

4 Which of the following are not true about streams?

They are always seekable
When used properly they significantly reduce memory consumption
They can be applied to any data source
They are always bi-directional
They can be filtered

5 When using a function such as strip_tags, are markup-based attacks still possible?
Answer...
No, HTML does not pose any security risks
Yes, even a <p> HTML tag is a security risk
Yes, attributes of allowed tags are ignored
No, strip_tags will prevent any markup-based attack


Please answer through the comments I will make it publish on blog..............

| 1 comments ]

1 When connecting to a database using PDO, what must be done to ensure that database credentials are not compromised if the connection were to fail?

2 How can one take advantage of the time waiting for a lock during a stream access, to do other tasks using the following locking code as the base:

$retval = flock($fr, LOCK_EX);

3 The Decorator pattern is used to__________

4 HTTP authentication, how can we retrieve the user name & pasword?

5 Type-hinting and the instanceof keyword can be used to check what types of things about variables?

6 The MVC pattern in Web development involves which of the following components?

7 Given the string:
$var = "john@php.net";

Please answer through the comments I will make it publish on blog..............

| 1 comments ]

1 Which functions would be needed to translate the following string:

I love PHP 5

to the following?

5 PHP EVOL I

mirror()
strtoupper()
toupper()
str_reverse()
strrev()

2 What is the output of the following code block?


<?php

$array = array(1 => 0, 2, 3, 4);

array_splice($array, 3, count($array), array_merge(array('x'), array_slice($array, 3)));

print_r($array);

?>

3 Given the following array:

$array = array(1,1,2,3,4,4,5,6,6,6,6,3,2,2,2);

4 The fastest way to determine the total number a particular value appears in the array is to use which function?

array_total_values
array_count_values
A foreach loop
count
a for loop


Please answer through the comments I will make it publish on blog..............

| 0 comments ]

1 Which PCRE regular expression will match the string PhP5-rocks?


Answer...
/^[hp1-5]*\-.*/i
/[hp1-5]*\-.?/
/[hp][1-5]*\-.*/
/[PhP]{3}[1-5]{2,3}\-.*$/
/[a-z1-5\-]*/

2 Which of the following are valid PHP variables?
@$foo
&$variable
${0x0}
$variable
$0x0

3 To destroy one variable within a PHP session you should use which method in PHP 5?

4 When comparing two strings, which of the following is acceptable?
$a === $b;
strcasecmp($a, $b);
strcmp($a, $b);
$a == $b;
str_compare($a,$b);


Please answer through the comments I will make it publish on blog..............

| 0 comments ]

1 What is the best approach for converting this string:

$string = "a=10&b[]=20&c=30&d=40+50";

Into this array?


array(4) {
["a"]=>
string(2) "10"
["b"]=>
array(1) {
[0]=>
string(2) "20"
}
["c"]=>
string(2) "30"
["d"]=>
string(5) "40 50"
}


Answer...
Write a parser completely by hand, it's the only way to make sure it's 100% accurate
Use the parse_str() function to translate it to an array()
Pass the variable to another PHP script via an HTTP GET request and return the array as a serialized variable
Just call unserialize() to translate it to an array()
Write a string parser using strtok() and unserialize() to convert it to an array


2 SQL Injections can be best prevented using which of the following database technologies?

Answers: (choose 1)
All of the above
Prepared Statements
Persistent Connections
Unbuffered Queries
Query escaping

3 Name three new extensions in PHP 5


Answers: (choose 3)
tidy
soap
java
curl
mysqli

4 Which of the following is not a valid fopen() access mode:


Answer...
b
x
a
w
r+


Please answer through the comments I will make it publish on blog..............

| 0 comments ]

1 In PHP5 objects are passed by reference to a function when (Select the answer that is the most correct):

Answer...
Always; objects are passed by reference in PHP5
When the calling code preceeds the variable name with a &
Never; objects are cloned when passed to a function
When the function paramater listing preceeds the variable name with a &

2 What three special methods can be used to perform special logic in the event a particular accessed method or member variable is not found?


Answers: (choose 3)
__get($variable)
__call($method, $params)
__get($method)
__set($variable, $value)
__call($method)

3 When running PHP in a shared host environment, what is the major security concern when it comes to session data?

Answer...
Sessions on shared hosts are easily hijacked by outside malicious users
All of the above
You cannot use a custom data store in shared hosts
Session data stored in the file system can be read by other scripts on the same shared host
Users outside the shared host can access any site which created a session for them

4 In PHP 5, the ________ method is automatically called when the object is created, while the _______ method is automatically called when the object is destroyed.


Answer...
__construct(), __destruct()
<Class Name>, __destroy()
<Class Name>, ~<Class Name>
__startup(), __shutdown()
__construct(), __destroy()

Please answer through the comments I will make it publish on blog..............

| 1 comments ]

1 What is the best way to ensure the distinction between filtered / trusted and unfiltered / untrusted data?

Answer...
None of the above
Never trust any data from the user
Enable built-in security features such as magic_quotes_gpc and safe_mode
Always filter all incoming data
Use PHP 5's tainted mode

2 SimpleXML objects can be created from what types of data sources?


Answers: (choose 3)
A String
An array
A DomDocument object
A URI
A Database resource

3 Which of the following functions could be used to break a string into an array?

Answers: (choose 3)
array_split()
split()
string_split()
preg_match_all()
explode()

4 If you would like to change the session ID generation function, which of the following is the best approach for PHP 5?


Answer...
Set the session.hash_function INI configuration directive
Use the session_set_id_generator() function
Set the session id by force using the session_id() function
Use the session_regenerate_id() function
Implement a custom session handler

Please answer through the comments I will make it publish on blog..............

| 3 comments ]

1 Unlike a database such as MySQL, SQLite columns are not explicitly typed. Instead, SQLite catagorizes data into which of the following catagories?

Answers: (choose 2)
textual
unicode
numeric
binary
constant

2 When working with a database, which of the following can be used to mitigate the possibility of exposing your database credientials to a malicious user?

Answers: (choose 3)
Moving all database credentials into a single file
Moving all database credentials outside of the document root
Restricting access to files not designed to be executed independently
Setting creditial information as system environment variables
Using PHP constants instead of variables to store credentials

3 Which from the following list is not an approrpiate use of an array?

Answers: (choose 1)
As a list
All of these uses are valid
As a Lookup Table
A Stack
As a hash table

4 In PHP 5 you can use the ______ operator to ensure that an object is of a particular type. You can also use _______ in the function declaration.

Answer...
instanceof, is_a
instanceof, type-hinting
type, instanceof
===, type-hinting
===, is_a

Please answer through the comments I will make it publish on blog..............

| 2 comments ]

1 Consider the following String:

$string = "John\tMark\nTed\tLarry";

2 Which of the following functions would best parse the string above by the tab (\t) and newline (\n) characters?

3 How can you modify the copy of an object during a clone operation?

Answer...
Put the logic in the object's constructor to alter the values
Implment your own function to do object copying
Implement the object's __clone() method
Implement __get() and __set() methods with the correct logic
Implement the __copy() method with the correct logic

4 Which function would you use to add an element to the beginning of an array?

Answer...
array_shift()
array_push();
$array[0] = "value";
array_unshift()
array_pop();

ans: array_unshift();

Please answer through the comments I will make it publish on blog..............

| 4 comments ]

1 You can determine if you can seek an arbitrary stream in PHP with the ___________ function

2 To ensure that a given object has a particular set of methods, you must provide a method list in the form of an ________ and then attach it as part of your class using the ________ keyword.

Answer...
array, interface
interface, implements
interface, extends
instance, implements
access-list, instance

3 When executing system commands from PHP, what should one do to keep applications secure?

Answers: (choose 3)
Remove all quote characters from variables used in a shell execution
Avoid using shell commands when PHP equivlents are available
Hard code all shell commands
Escape all shell arguments
Escape all shell commands executed

4 When attempting to prevent a cross-site scripting attack, which of the following is most important?

Answer...
Not writing Javascript on the fly using PHP
Filtering Output used in form data
Filtering Output used in database transactions
Writing careful Javascript
Filtering all input



Please answer through the comments I will make it publish on blog..............

| 6 comments ]

1 When uploading a file using HTTP, which variable can be used to locate the file on PHP's local filesystem?


Answer...
None of the above
$_FILES['fieldname']['tmp_name']
$_FILES['fieldname']
$_FILES['fieldname'][0]['filename']
$_FILES['fieldname']['filename']

ans : $_FILES['fieldname']['tmp_name']


2 Which of the following SQL statements will improve SQLite write performance?


Answers: (choose 2)
PRAGMA locking_mode = "Row";
PRAGMA count_changes = Off;
PRAGMA default_synchronous = Off;
PRAGMA default_synchronous = On;
PRAGMA locking_mode = "Table";

Ans:

3 What is the best way to iterate and modify every element of an array using PHP 5?

Answer...
You cannot modify an array during iteration
for($i = 0; $i < count($array); $i++) { /* ... */ }
foreach($array as $key => &$val) { /* ... */ }
foreach($array as $key => $val) { /* ... */ }
while(list($key, $val) = each($array)) { /* ... */

4 What is the primary benefit of a SAX-based XML parser compared to DOM?




Please answer through the comments I will make it publish on blog..............

| 2 comments ]

What is the output of the following?


<?php

$a = 010;
$b = 0xA;
$c = 2;

print $a + $b + $c;

?7gt;
20
22
18
$a is an invalid value
2

Ans : 22


Please answer through the comments I will make it publish on blog..............

| 0 comments ]

What is the output of the following code?

class MyException extends Exception {}
class AnotherException extends MyException {}

class Foo {
public function something() {
throw new AnotherException();
}
public function somethingElse() {
throw new MyException();
}
}

$a = new Foo();

try {
try {
$a->something();
} catch(AnotherException $e) {
$a->somethingElse();
} catch(MyException $e) {
print "Caught Exception";
}
} catch(Exception $e) {
print "Didn't catch the Exception!";
}

?>


When using a function such as strip_tags, are markup-based attacks still possible?
Answer...
No, HTML does not pose any security risks
Yes, even a

HTML tag is a security risk
Yes, attributes of allowed tags are ignored
No, strip_tags will prevent any markup-based attack



Please answer through the comments I will make it publish on blog..............

| 0 comments ]

What is the output of the following?


<?php

$a = 20;

function myfunction($b) {
$a = 30;

global $a, $c;
return $c = ($b + $a);
}

print myfunction(40) + $c;

?>

ans: 120

Please answer through the comments I will make it publish on blog..............

| 0 comments ]

Consider the following script:


<?php
try {
$dbh = new PDO("sqlite::memory:");
} catch(PDOException $e) {
print $e->getMessage();
}

$dbh->query("CREATE TABLE foo(id INT)");
$stmt = $dbh->prepare("INSERT INTO foo VALUES(:value)");
$value = null;
$data = array(1,2,3,4,5);
$stmt->bindParam(":value", $value);

/* ?????? */
try {
foreach($data as $value) {
/* ????? */
}
} catch(PDOException $e) {
/* ??????? */
}

/* ?????? */
?>

What lines of code need to go into the missing places above in order for this script to function properly and insert the data into the database safely?

Please answer through the comments I will make it publish on blog..............

| 0 comments ]

Consider the following code block:

<?php
function &myFunction() {
$string = "MyString";
var_dump($string);

return ($undefined);
}

for($i = 0; $i < 10; $i++) {
$retval = myFunction();
}
?>

This code block's behavior has changed between PHP 4 and PHP 5. Why?


Answer...
None of the above
This could would cause an automatic segmentation fault in PHP 4
This code would throw a syntax error in PHP 4
Returning an undefined variable by reference in PHP 4 would cause eventual memory corruption
You could not return undefined variables by reference in PHP 4
Mark for Review?


Please answer through the comments I will make it publish on blog..............

| 0 comments ]

What is the output of the following script?


<?php

class A {

public function bar() {
print "Hello";
}

}

class B extends A {

function bar() {
print "Goodbye";
}
}

$c = new B();
$c->bar();
?>

| 0 comments ]

What are the values of $a in $obj_one and $obj_two when this script is executed?


<?php
class myClass {
private $a;

public function __construct() {
$this->a = 10;
}

public function printValue() {
print "The Value is: {$this->a}\n";
}

public function changeValue($val, $obj = null) {
if(is_null($obj)) {
$this->a = $val;
} else {
$obj->a = $val;
}
}

public function getValue() {
return $this->a;
}
}

$obj_one = new myClass();
$obj_two = new myClass();

$obj_one->changeValue(20, $obj_two);
$obj_two->changeValue($obj_two->getValue(), $obj_one);

$obj_two->printValue();
$obj_one->printValue();

?>


Answer...
10,20
You cannot modify private member variables of a different class
20,20
10,10
20,10

MY ans: 20, 20

Please answer through the comments I will make it publish on blog..............

| 0 comments ]

When your error reporting level includes E_STRICT, what will the output of the following code be?


<?php
function optionalParam($x = 1, $y = 5, $z)
{
if ((!$z > 0))
{
$z = 1;
}
for($count = $x; $count < $y; $count+= $z)
{
echo "#";
}
}
optionalParam(2,4,2);
?>


Answer...
##
Notice
Warning
Syntax Error
#

my ans #

| 3 comments ]

Consider the following PHP script:


<?php
function get_socket($host, $port) {
$fr = fsockopen($host, $port);
stream_set_blocking($fr, false);
return $fr;
}

// Assume $host1, $host2, etc are defined properly
$write_map[] = array('fr' => get_socket($host1, $port1),
'data' => str_pad("", 500000, "A"));
$write_map[] = array('fr' => get_socket($host2, $port2),
'data' => str_pad("", 500000, "B"));
$write_map[] = array('fr' => get_socket($host3, $port3),
'data' => str_pad("", 500000, "C"));

do {
$write_sockets = array();

foreach($write_map as $data) {
$write_sockets[] = $data['fr'];
}

$num_returned = stream_select($r = null, $write_sockets, $e = null, 30);

if($num_returned) {
foreach($write_sockets as $fr) {
foreach($write_map as $index => $data) {
if($data['fr'] === $fr) {
$len = fwrite($fr, $data['buf']);

if($len) {
$data['buf'] = substr($data['buf'], $len);

if(empty($data['buf'])) {
fclose($data['fr']);
/* ????????? */
}
}
}
}
}
}
} while(count($write_map));
?>

What should go in the ??????? above for this script to function properly?

Please answer through the comments I will make it publish on blog..............

| 0 comments ]

What is the output of the following code?


<?php
function x10(&$number)
$number *= 10;

$count = 5;
x10($count);
echo $count;
?>

Please answer through the comments I will make it publish on blog..............

| 1 comments ]

Consider the following PHP script fragment:

&lt:?php
$title = $dom->createElement('title');
$node = ????????
$title->appendChild($node);
$head->appendChild($title);
?>>

What should ??????? be replaced with to add a <title> node with the value of Hello, World!

My ans : Hello, World

Please answer through the comments I will make it publish on blog..............

| 0 comments ]

What is the output of the following code?

<?php
function callbyReference(&$variable = 5)
{
echo ++$variable;
}
callbyReference();
?>>

answer : 6
Please answer through the comments I will make it publish on blog..............

| 0 comments ]

Another Question regarding XML .

$dom = new DomDocument();
$dom->load('test.xml');
$xpath = new DomXPath($dom);
$nodes = $xpath->query(???????, $dom->documentElement);
echo $nodes->item(0)->getAttributeNode('bgcolor')->value
. "\n";
?>

What XPath query should go in the ?????? above to display the "bgcolor" attribute of the first "body" node in the XML document?


Please answer through the comments I will make it publish on blog..............

| 0 comments ]

What is the output of the following code?

<?php

class MyException extends Exception {}
class AnotherException extends MyException {}

class Foo {
public function something() {
throw new AnotherException();
}
public function somethingElse() {
throw new MyException();
}
}

$a = new Foo();

try {
try {
$a->something();
} catch(AnotherException $e) {
$a->somethingElse();
} catch(MyException $e) {
print "Caught Exception";
}
} catch(Exception $e) {
print "Didn't catch the Exception!";
}

?>


Please answer through the comments I will make it publish on blog..............

| 1 comments ]

function ByteSize($bytes)
{
$size = $bytes / 1024;
if($size < 1024)
{
$size = number_format($size, 2);
$size .= ' KB';
}else {
if($size / 1024 < 1024) {
$size = number_format($size / 1024, 2);
$size .= ' MB';
} else if($size / 1024 / 1024 < 1024) {
$size = number_format($size / 1024 / 1024, 2);
$size .= ' GB';
}
}
return $size;
}

| 0 comments ]

//This function is for sub directories size (This will retrn an array )
function du($location) {
if (!$location || !is_dir($location))
return 0;
$size = 0;
$files = 0;
$dirs = 0;

$all = opendir($location);
while ($file = readdir($all)) {
if (is_dir($location.'\\'.$file) and $file != ".." and $file != ".") {
$temp = du($location.'/'.$file);
$dirs++;
$size += $temp['size'];
$files += $temp['files'];
$dirs += $temp['dirs'];
unset($temp);
unset($file);
} elseif (!is_dir($location.'\\'.$file)) {
$stats = stat($location.'\\'.$file);
$size += $stats['size'];
$files++;
unset($file);
}
}
closedir($all);
unset($all);
return array('size' => $size, 'files' => $files, 'dirs' => $dirs);
}

| 0 comments ]

// This function shows the file size of aparticular
function show_dir($dir){
// global $totalsize;
$handle = @opendir($dir);
while ($file = @readdir($handle)){
$size=filesize($dir.$file);
$totalsize=$totalsize+$size;
}
@closedir($handle);
if($totalsize==8192){$totalsize=0;}
return($totalsize);
}

| 0 comments ]

function cropImage($picture,$fixedwidth,$fixedheight,$mogrify) {

// GET IMG
$img = imagecreatefromjpeg($picture);
$width= imagesx($img);
$height= imagesy($img);
// CROP WIDTH
if($width!=$fixedwidth){
$ratio =$fixedwidth/$width;
$NewHeight=round($height*$ratio);
$NewWidth=round($width*$ratio);
exec( $mogrify." -resize ".$NewWidth."x".$NewHeight."! $picture");
exec( $mogrify." -crop ".$fixedwidth."x".$fixedheight."+0+0 $picture");
// REFRESH
$img = imagecreatefromjpeg($picture);
$width= imagesx($img);
$height= imagesy($img);
}
// CROP HEIGHT
if($height!=$fixedheight){
$ratio =$fixedheight/$height;
$NewHeight=round($height*$ratio);
$NewWidth=round($width*$ratio);
exec( $mogrify." -resize ".$NewWidth."x".$NewHeight."! $picture");
exec( $mogrify." -crop ".$fixedwidth."x".$fixedheight."+0+0 $picture");
}
//
ImageDestroy($img);
}

| 0 comments ]

function getFileSizeW($filePath){
$blah = getimagesize($filePath);
$type = $blah['mime'];
$width = $blah[0];
return $width;}

function getFileSizeH($filePath){
$blah = getimagesize($filePath);
$type = $blah['mime'];
$height = $blah[1];
return $height;}

| 0 comments ]

function imageInfo($file = null, $out = null) {

// If $file is not supplied or is not a file, warn the user and return false.
if (is_null($file) || !is_file($file)) {
echo '

Warning: image_info() => first argument must be a file.

';
return false;
}

// Defines the keys we want instead of 0, 1, 2, 3, 'bits', 'channels', and 'mime'.
$redefine_keys = array(
'width',
'height',
'type',
'attr',
'bits',
'channels',
'mime',
);

// If $out is supplied, but is not a valid key, nullify it.
if (!is_null($out) && !in_array($out, $redefine_keys)) $out = null;

// Assign usefull values for the third index.
$types = array(
1 => 'GIF',
2 => 'JPG',
3 => 'PNG',
4 => 'SWF',
5 => 'PSD',
6 => 'BMP',
7 => 'TIFF(intel byte order)',
8 => 'TIFF(motorola byte order)',
9 => 'JPC',
10 => 'JP2',
11 => 'JPX',
12 => 'JB2',
13 => 'SWC',
14 => 'IFF',
15 => 'WBMP',
16 => 'XBM'
);
$temp = array();
$data = array();

// Get the image info using getimagesize().
// If $temp fails to populate, warn the user and return false.
if (!$temp = getimagesize($file)) {
echo '

Warning: image_info() => first argument must be an image.

';
return false;
}

// Get the values returned by getimagesize()
$temp = array_values($temp);

// Make an array using values from $redefine_keys as keys and values from $temp as values.
foreach ($temp AS $k => $v) {
$data[$redefine_keys[$k]] = $v;
}

// Make 'type' usefull.
$data['type'] = $types[$data['type']];

// Return the desired information.
return !is_null($out) ? $data[$out] : $data;
}

| 0 comments ]

function cropimage($picture,$fixedwidth,$fixedheight,$mogrify) {

// GET IMG
$img = imagecreatefromjpeg($picture);
$width= imagesx($img);
$height= imagesy($img);
// CROP WIDTH
if($width!=$fixedwidth){
$ratio =$fixedwidth/$width;
$NewHeight=round($height*$ratio);
$NewWidth=round($width*$ratio);
exec( $mogrify." -resize ".$NewWidth."x".$NewHeight."! $picture");
exec( $mogrify." -crop ".$fixedwidth."x".$fixedheight."+0+0 $picture");
// REFRESH
$img = imagecreatefromjpeg($picture);
$width= imagesx($img);
$height= imagesy($img);
}
// CROP HEIGHT
if($height!=$fixedheight){
$ratio =$fixedheight/$height;
$NewHeight=round($height*$ratio);
$NewWidth=round($width*$ratio);
exec( $mogrify." -resize ".$NewWidth."x".$NewHeight."! $picture");
exec( $mogrify." -crop ".$fixedwidth."x".$fixedheight."+0+0 $picture");
}
//
ImageDestroy($img);
}

?>

| 0 comments ]

function get_rnd_iv($iv_len){
$iv = '';
while ($iv_len-- > 0) {
$iv .= chr(mt_rand() & 0xff);
}
return $iv;
}
function md5Encrypt($plain_text, $password, $iv_len = 16){
$plain_text .= "\x13";
$n = strlen($plain_text);
if ($n % 16) $plain_text .= str_repeat("\0", 16 - ($n % 16));
$i = 0;
$enc_text = get_rnd_iv($iv_len);
$iv = substr($password ^ $enc_text, 0, 512);
while ($i < $n) {
$block = substr($plain_text, $i, 16) ^ pack('H*', md5($iv));
$enc_text .= $block;
$iv = substr($block . $iv, 0, 512) ^ $password;
$i += 16;
}
return base64_encode($enc_text);
}
function md5Decrypt($enc_text, $password, $iv_len = 16){
$enc_text = base64_decode($enc_text);
$n = strlen($enc_text);
$i = $iv_len;
$plain_text = '';
$iv = substr($password ^ substr($enc_text, 0, $iv_len), 0, 512);
while ($i < $n) {
$block = substr($enc_text, $i, 16);
$plain_text .= $block ^ pack('H*', md5($iv));
$iv = substr($block . $iv, 0, 512) ^ $password;
$i += 16;
}
return preg_replace('/\\x13\\x00*$/', '', $plain_text);
}
?>

| 0 comments ]

function flipImage($image, $vertical, $horizontal) {
$w = imagesx($image);
$h = imagesy($image);

if (!$vertical && !$horizontal) return $image;

$flipped = imagecreatetruecolor($w, $h);

if ($vertical) {
for ($y=0; $y<$h; $y++) {
imagecopy($flipped, $image, 0, $y, 0, $h - $y - 1, $w, 1);
}
}

if ($horizontal) {
if ($vertical) {
$image = $flipped;
$flipped = imagecreatetruecolor($w, $h);
}

for ($x=0; $x<$w; $x++) {
imagecopy($flipped, $image, $x, 0, $w - $x - 1, 0, 1, $h);
}
}

return $flipped;
}

| 0 comments ]

function createImage(){

// creates the images, writes the file
$fileRand = md5(rand(100000,999999));
$string_a = array("A","B","C","D","E","F","G","H","J","K",
"L","M","N","P","R","S","T","U","V","W","X","Y","Z",
"2","3","4","5","6","7","8","9");
$keys = array_rand($string_a, 6);
foreach($keys as $n=>$v){
$string .= $string_a[$v];
}
$backgroundimage = "security_background.gif";
$im=imagecreatefromgif($backgroundimage);
$colour = imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255));
$font = 'Arial';
$angle = rand(-5,5);
// Add the text
imagettftext($im, 16, $angle, 15, 25, $colour, $font, $string);
$outfile= "$fileRand.gif";
imagegif($im,$outfile);
return $outfile;
}

//code for image display
echo "";

?>

| 0 comments ]

function randomFloat ($min,$max) {
return ($min+lcg_value()*(abs($max-$min)));
}

| 0 comments ]

function isNaN( $var ) {
return !ereg ("^[-]?[0-9]+([\.][0-9]+)?$", $var);
}

| 0 comments ]

function arabicToRomanNumerals($input_arabic_numeral='') {

if ($input_arabic_numeral == '') { $input_arabic_numeral = date("Y"); } // DEFAULT OUTPUT: THIS YEAR
$arabic_numeral = intval($input_arabic_numeral);
$arabic_numeral_text = "$arabic_numeral";
$arabic_numeral_length = strlen($arabic_numeral_text);

if (!ereg('[0-9]', $arabic_numeral_text)) {
return false; }

if ($arabic_numeral > 4999) {
return false; }

if ($arabic_numeral < 1) {
return false; }

if ($arabic_numeral_length > 4) {
return false; }

$roman_numeral_units = $roman_numeral_tens = $roman_numeral_hundreds = $roman_numeral_thousands = array();
$roman_numeral_units[0] = $roman_numeral_tens[0] = $roman_numeral_hundreds[0] = $roman_numeral_thousands[0] = ''; // NO ZEROS IN ROMAN NUMERALS

$roman_numeral_units[1]='I';
$roman_numeral_units[2]='II';
$roman_numeral_units[3]='III';
$roman_numeral_units[4]='IV';
$roman_numeral_units[5]='V';
$roman_numeral_units[6]='VI';
$roman_numeral_units[7]='VII';
$roman_numeral_units[8]='VIII';
$roman_numeral_units[9]='IX';

$roman_numeral_tens[1]='X';
$roman_numeral_tens[2]='XX';
$roman_numeral_tens[3]='XXX';
$roman_numeral_tens[4]='XL';
$roman_numeral_tens[5]='L';
$roman_numeral_tens[6]='LX';
$roman_numeral_tens[7]='LXX';
$roman_numeral_tens[8]='LXXX';
$roman_numeral_tens[9]='XC';

$roman_numeral_hundreds[1]='C';
$roman_numeral_hundreds[2]='CC';
$roman_numeral_hundreds[3]='CCC';
$roman_numeral_hundreds[4]='CD';
$roman_numeral_hundreds[5]='D';
$roman_numeral_hundreds[6]='DC';
$roman_numeral_hundreds[7]='DCC';
$roman_numeral_hundreds[8]='DCCC';
$roman_numeral_hundreds[9]='CM';

$roman_numeral_thousands[1]='M';
$roman_numeral_thousands[2]='MM';
$roman_numeral_thousands[3]='MMM';
$roman_numeral_thousands[4]='MMMM';

if ($arabic_numeral_length == 3) { $arabic_numeral_text = "0" . $arabic_numeral_text; }
if ($arabic_numeral_length == 2) { $arabic_numeral_text = "00" . $arabic_numeral_text; }
if ($arabic_numeral_length == 1) { $arabic_numeral_text = "000" . $arabic_numeral_text; }

$anu = substr($arabic_numeral_text, 3, 1);
$anx = substr($arabic_numeral_text, 2, 1);
$anc = substr($arabic_numeral_text, 1, 1);
$anm = substr($arabic_numeral_text, 0, 1);

$roman_numeral_text = $roman_numeral_thousands[$anm] . $roman_numeral_hundreds[$anc] . $roman_numeral_tens[$anx] . $roman_numeral_units[$anu];
return ($roman_numeral_text);
}

| 0 comments ]

#******************************************************************************
# This is a super-hard array conversion function.(PHP.net)
#******************************************************************************
#It only returns TRUE if the two arrays are completely identical, that means that
#they have the same keys, and the values of all keys are exactly the same (compared with ===)

function array_same($a1, $a2) {
if (!is_array($a1) || !is_array($a2))
return false;

$keys = array_merge(array_keys($a1), array_keys($a2));

foreach ($keys as $k) {
if (!isset($a2[$k]) || !isset($a1[$k]))
return false;

if (is_array($a1[$k]) || is_array($a2[$k])) {
if (!array_same($a1[$k], $a2[$k]))
return false;
}
else {
if (! ($a1[$k] === $a2[$k]))
return false;
}
}

return true;
}

#******************************************************************************

| 1 comments ]

#******************************************************************************
# function to generate unique key
#******************************************************************************
function generateUniqueKey($key)
{
if (strlen($key)>8) {
$key = $key[0] . $key[1] . $key[2];
}
$id = $key . '_';
$uid = uniqid();
$len = strlen($uid);
$max = (9 - strlen($key));
for ($c = $len; ; $c --) {
$id .= $uid[$c];
if ($c == ($len - $max)) {
break;
}
}
return $id;
}

#******************************************************************************

| 0 comments ]

#******************************************************************************
# function to find factorial
#******************************************************************************

function fact($i){
if($i==1){
return 1;
}else{
return $i*fact($i-1);
}
}

#******************************************************************************

| 0 comments ]

#******************************************************************************
# function to remove random underscore
#******************************************************************************

function removeUnderscore($string)
{

$result = str_replace("_"," ",$string);
return $result;

}

#******************************************************************************
# function to add random underscore
#******************************************************************************
function addUnderscore($string)
{

$result = str_replace(" ","_",$string);
return $result;

}
#******************************************************************************

| 0 comments ]

#******************************************************************************
# function to create random password
#******************************************************************************

function createRandomPassword() {

$chars = "abcdefghijkmnopqrstuvwxyz023456789";
srand((double)microtime()*1000000);
$i = 0;
$pass = '' ;

while ($i <= 7) {
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}

#******************************************************************************