Saturday, 12 December 2009

How to Install Google Analytics in 5 Minutes or Less

Google Analytics is easy to set up and it won't cost you a dime. More importantly, you can have lots of great data about your visitors tracking within the hour. Google Analytics and most other analytics applications are installed by pasting a few snippets of javascript code in the footer of the site. If you have access to your web files on the server, I'll show you how to do it yourself using Dreamweaver, or you can give the code to your webmaster and have them install it. Then we'll run a quick test to make sure the tool is tracking on all pages. Let's get started!

Step 1: If you don't already have a free Google Mail account, sign up for one. It will take 30-45 seconds.

Step 2: Go to the Google Analytics site, hit the "Sign Up Now" link and login with your GMail credentials.

Step 3: Once you are logged in, it will ask you to "Sign Up" once more. It is redundant, but it may be some kind of security or SPAM filter.

Step 4: Now you're in! Enter some information about the site and put in your URL (you don't need to add /index.php or similar if you have these extensions), nickname the account if you want (I like to because if you manage multiple sites in one account, it keeps the list nice and clean), select your country, and time zone and then Continue.

Step 5: Now just add your name, phone number (I put my number in, but I think it's optional, or just make one up if you don't want to use a real one), and your country one more time, then Continue.

Step 6: You're almost done with set up! Just accept the User Agreement, and also agree to the Data Settings clause. The default is set to allow Google to aggregate your data and use it for comparison purposes in the Benchmark section of Analytics. This is a fairly new module, and if you want, you don't have to agree to it, so you can change the default by clicking on "Settings". I use Benchmark data often, so I would contribute to the cause. Select Create New Account!

Step 7: Now you are going get the javascript code you need to install on your website. If you have a webmaster, you can copy this code and send it to him in an email, or you can brave on to the next couple of steps and do it yourself! You will notice that there are two types of code: ga.js and urchin.js. You will need to use the newest version, the ga.js, which is already defaulted to. Urchin.js was the old code for the prior version of Google Analytics. Copy this code, or leave the page open so you can come back to it and copy it later.

This is the next page if you Continue. You will see that Tracking Code is not verified. The next few steps we will be installing the code.

Step 8: Open your Dreamweaver software to install the code. If you don't have Dreamweaver, you can also use FireFTP for Firefox, which is a free Add-On. I like Dreaweaver since I can just copy and paste the code right on the page I need it, versus FireFTP I need to copy the page over to my hard disk, make the change, and then copy it back over. It is also easy to do, but I just prefer Dreamweaver. You will need your FTP information to get access to your web files, usually a path, username and password. Here is the console screen you should see:

Step 9: Find the "footer.php" file. It could reside under an "Includes" folder, which means that these files are included on each page. If you can find this file, it will ensure the code gets placed on every page, and you only have to copy it in once. Otherwise, if you can't find this type of file or similar, you will need to copy and paste to code on every page manually. If you need help, call your webmaster or developer to find which file you should paste the code into.

Step 10: Place the code from the Google Analytics (highlighted in yellow) page right before the tag (highlighted in red) at the bottom of the page. I also use another web analytics tool called Clicky, which I also have placed right before the body tag. Most web analytics tools javascript code will go here, with the exception of one or two, that might require some code to go up in the header section. Now, save the page file (Ctl+S) and you are done! Now we can test to make sure it is installed properly on all pages.

Step 11: Let's go and test to make sure all pages in the site are tracking properly in Google Analytics.

Simply enter the web address and your email, and shortly you will get an email with a link with the results that look like this:

Pre-Installation Steps for Installing Windows Server 2008

In this article we cover the basic installation options available to you when deploying a full copy of Windows Server 2008 on an enterprise class server. The article’s goal is to familiarize and acclimate you to the process of deploying Windows Server 2008 on systems on your production network.

Preparation Tasks
The first step in deploying a Windows Server 2008 system is to do all of the analysis needed upfront to appropriately size your server hardware and prepare for an easy installation. There is not enough that can be said about ‘pre-planning’ your installation. Make sure that you have all the software you need, appropriate drivers and so on. You should create a checklist or some form of list to help you keep track of what you need, what you need to do and what steps have been accomplished. This is helpful for problems that you may encounter during the installation – you can quickly ascertain the source of the problem when you have a checklist to follow so you can retrace your steps. You should always pre-plan any deployment (no matter how big or small) and run thorough tests so that you know what works and what does not before installing new systems on your network or upgrading older systems as an example. For another example, when we first started to run Windows Server 2008 in its earliest forms (Longhorn) for testing purposes, it was quickly found that it was extremely difficult to install on an enterprise class server due to the fact that most of the enterprise server hardware vendors had yet to create alternatives to the new release of Windows and most Windows Server 2003 drivers would (and will) not function on the newest version of Windows, 2008.

One of the main issues you may encounter when installing Windows Server 2008 comes in the form of installing RAID drivers and finding ones that are supported by Windows Server 2008 in its pre-release form. Since the inception of NT 3.x and 4.0, this process has never been easy. In earlier forms of the operating system (as previously mentioned - NT as an example), you had to hit a specific key (F6) to add RAID drivers while installing, force drivers in if not available and fight with the system to get it to function correctly and remain stable. A lot has changed since, but one thing that will never change is when new operating systems come out, the vendors have to keep up and create software to run on the new platform and that process usually takes time and usually never comes out during the beta process of any new release underway – very rarely do you receive fully functional, tested and supported drivers until a full release. That being said, it is possible to create a RAID array if you can find the drivers and a system that will allow for it until the final release of Windows Server 2008 is official, by then just about every operational hardware vendor will have drivers, software and other tools ready to go for 2008.

RAID is extremely important to consider and implement when deploying an enterprise class server. Since redundancy is important due to unexpected issues (such as a drive reaching its MTBF) which causes the drive to fail and causes the server to crash, you should consider this when deploying a new server. RAID is nothing more than a Redundant Array of Inexpensive Disks. Figure 2 shows an example of an Enterprise Class server configured as an array with 6 SCSI hard disks. Figure 3 shows an external RAID array that can be connected via Fiber or SCSI.

RAID comes in many levels. You can configure RAID in many ways. Table 1 lists a chart of the most commonly used RAID levels and their fault tolerance (or lack thereof).

Table 1: Most Commonly used RAID Levels

* Note:
Duplexing and Mirroring are similar in that they both use two disks and each carry a copy of the data, the main difference lies in the disk controller. When two disk controllers are used (one for each disk), this is duplexing. This also increases fault tolerance. When mirroring is used there is only one controller. Although you have two disks in use, your single point of failure becomes the controller itself.

Although there are many other RAID levels, these are absolutely the most commonly used today. You can also mix and match RAID levels based on how you create your partitions. You must know the available levels and know which level(s) you want to use when you deploy.

Once you have selected the enterprise class hardware you wish to use, you must make sure that you have all of the drivers and software needed for deployment. As 2008 is fairly new (just getting ready for prime time) as mentioned before, it’s likely that you will not have full driver support, or in some cases, the management software used for the server, may not run on 2008. Because of this, it’s important to make sure that you have visited Microsoft’s Web site to check for the current drivers and software and then check your server vendors Web site to check for any updates they have as well. You can also discuss options about the server hardware in a pre or post sales vendor meeting or contact them directly though their support centers. In either case, you will find yourself in a better position when you have planned out your install in advance, have gathered all of the needed software and drivers and prepped the server correctly for install.

System Requirements
When deploying Windows Server 2008, it’s important to consider and adhere to the minimum requirements needed for the system to be installed. If you do not meet the bare minimum requirements, the installation will not continue. Table 2 shows a list of minimum and maximum system requirement levels for your review.

Configuring your Hardware
To install Windows Server 2008 correctly, you must first configure your hardware. When working with enterprise class server systems such as the HP DL380, you will want to configure your storage correctly, so that you can install Windows Server 2008 within the needed hard disk space requirements. To do this, you may need to configure RAID. To configure RAID, you will likely have to use your servers BIOS, or the management utility that came with it. In this example, we will use the system BIOS.


Figure 4: Configuring a RAID Array

Earlier we mentioned that you can have multiple RAID levels exist on the same Server. Figure 5 shows the BIOS configuration for an HP DL380 being prepared for an installation of Windows Server 2008. Here in this example we are configuring the HP Smart Array 6i which comes with its own controller, or HBA (Host Bus Adapter). In figure 5, you can configure the drives for redundancy.

Installing IIS on Windows XP Home

Microsoft doesn't officially support running IIS (Internet Information Server) or PWS (Personal Web Server) on Windows XP Home.

See: INFO: Personal Web server is not included with Windows XP Home Edition.

There is no technical reason why XP Home didn't include a web server, so I can only assume it was done as a marketing decision.

These instructions are unofficial and unsupported. Hacking your Windows XP Home installation is a good way to put your computer out of commission and require a full reinstall.

If you are actually using your computer to run a business and need IIS, you must license an appropriate version of Windows to be in compliance with Microsoft EULAs. These versions include:

Windows XP Professional
Windows Web Server 2008
Windows Server 2008
Windows Server 2003

If you want to run a web server, but do not need IIS specific features (ASP/ASP.NET support), consider an alternative web server.

References and credits
Richard Sandoz provided the steps to install IIS on XP Home in this USENET post (Jan 8 2002). His original posting has been widely quoted around the web. Unfortunately, his steps are unclear on how to properly configure IIS after installation.

This article cleans up some style issues with Mr. Sandoz's post, and integrates additional steps needed to work on XP Home SP2. This article would not have been possible without Mr. Sandoz's work, and I thank him for sharing it with the community.

Path and CD-ROM notes
I assume that your windows folder is C:\Windows which is the default location. Substitute your actual windows folder if needed.
I assume that your CD-ROM drive is assigned the letter X:. Substitute your actual CD-ROM drive letter if needed.
Windows Script Installation
You need to be running Windows Script 5.6 or higher for these instructions to work. Newer versions of Windows XP will come with this version installed, but if you have a very old installation you may need to update this component manually.

To verify your version of Windows Script, open a command prompt and run:
cscript

You should see "Microsoft (R) Windows Script Host Version 5.6" or "...5.7". If you have a prior version, use the following link to update your scripting components.

Micrsoft Download: Windows Script 5.7 for Windows XP

IIS Installation
Open the file C:\WINDOWS\INF\SYSOC.INF and find the section [Components].
Find the line:
iis=iis.dll,OcEntry,iis.inf,hide,7
and replace it with:
iis=iis2.dll,OcEntry,iis2.inf,,7
Typographical notes
This file is case-sensitive, so make sure you type OcEntry and not OCEntry or ocentry.
In the replacement text, there are two commas in a row before the 7.
From your Windows 2000 CD, copy the files X:\I386\iis.dl_ and X:\I386\iis.in_ to a folder on your hard drive.
Go to the folder from step #3 in a command window.
"Open Command Window Here"
Microsoft provides a PowerToy that lets you easily get to any folder in a command window. After installing the PowerToy, right-click on any folder to open it in the shell.

See: Microsoft PowerToys for Windows XP, and install "Open Command Window Here".


IIS Configuration
When cross-installing IIS from Windows 2000 to Windows XP Home, the default Directory Security and Home Directory settings will not work correctly out-of-the-box.

Configure Directory Security
The default IIS account is IUSR_NAME. We need to replace this with NAME\IUSR_NAME (where NAME is your computer name.)

IIS User Accounts
IIS creates some user accounts, based on your computer's name, that it uses to run ASP applications: IUSR_NAME and IWAM_NAME, where NAME is the name of your computer.

This allows custom security settings to be applied to ASP and ISAPI applications.

Start Internet Services Manager from Administrative Tools.
Your computer will appear under Internet Information Services. Right-click on your computer and choose Properties.
Select Master WWW Service in the drop-down, then click Edit....
Select the Directory Security tab.
Under Anonymous access and authentication control click Edit...
In the Authentication Methods form, make sure only Anonymous access is checked, then click Edit....
The default username will be IUSR_NAME. We need to replace this with NAME\IUSR_NAME where NAME is your computer name. You can type it in manually or use these steps:
Click the Browse... button.
On the Select User form click the Advanced... button in the bottom left.
Click the Find Now button in the middle-right of this form.
Select IUSR_NAME in the user list at the bottom of the form, then click OK
Click OK to dismiss the Select User form.
Uncheck Allow IIS to control password. (This is important!)
Click OK to dismiss the Anonymous User Account form.
Click OK to dismiss the Authentication Methods form.
Click OK to dismiss the WWW Service Master Properties form.
Click OK to dismiss the Computername Properties form.
If you see "The requested resource is in use." trying to access your new web server, follow the Home Directory steps below to modify the Application Protection settings for the default web site.

Apache has a native Windows version.
Lighttpd has a Windows version that runs with cygwin or mingw.
Note that neither of these support ASP applications natively, which is presumably why you are installing IIS in the first place.

Installing IIS on Windows XP Pro

If you are running Windows XP Professional on your computer you can install Microsoft's web server, Internet Information Server 5.1 (IIS) for free from the Windows XP Pro installation CD and configure it to run on your system by following the instructions below: -

1. Place the Windows XP Professional CD-Rom into your CD-Rom Drive.

2. Open 'Add/Remove Windows Components' found in 'Add/Remove Programs' in the 'Control Panel'.

3. Place a tick in the check box for 'Internet Information Services (IIS)' leaving all the default installation settings intact.

4. Once IIS is installed on your machine you can view your home page in a web browser by typing 'http://localhost' (you can substitute 'localhost' for the name of your computer) into the address bar of your web browser. If you have not placed your web site into the default directory you should now be looking at the IIS documentation.

5. If you are not sure of the name of your computer right-click on the 'My Computer' icon on your desktop, select 'Properties' from the shortcut menu, and click on the 'Computer Name' tab.

6. Your default web directory to place your web site in is 'C:\Inetpub\wwwroot', but if you don't want to over write the IIS documentation found in this directory you can set up your own virtual directory through the 'Internet Information Services' console.

7. The 'Internet Information Services' console can be found in the 'Administration Tools' in the 'Control Panel' under 'Performance and Maintenance', if you do not have the control panel in Classic View.

8. Double-click on the 'Internet Information Services' icon.

8. Once the 'Internet Information Services' console is open you will see any IIS web services you have running on your machine including the SMTP server and FTP server, if you chose to install them with IIS.

9. To add a new virtual directory right click on 'Default Web Site' and select 'New', followed by 'Virtual Directory', from the drop down list.

7. Next you will see the 'Virtual Directory Creation Wizard' from the first screen click the 'next' button.

9. You will then be asked to type in an 'Alias' by which you will access the virtual directory from your web browser (this is the name you will type into your web browser after 'localhost' to view any web pages you place in the directory).

10. Next you will see a 'Browse...' button, click on this to select the directory your web site pages are in on your computer, after which click on the 'next' button to continue.

11. On the final part of the wizard you will see a series of boxes, if you are not worried about security then select them all, if you are and want to run ASP scripts then check the first two, followed by the 'next' button.

12. Once the virtual directory is created you can view the web pages in the folder by typing 'http://localhost/aliasName' (where 'aliasName' is, place the alias you called the virtual directory) into the address bar of your web browser (you can substitute 'localhost' for the name of your computer if you wish).

Installing php in Microsoft IIS 7.0 and later

This section contains instructions for manually setting up Internet Information Services (IIS) 7.0 and later to work with PHP on Microsoft Windows Vista SP1, Windows 7, Windows Server 2008 and Windows Server 2008 R2. For instructions on setting up IIS 5.1 and IIS 6.0 on Windows XP and Windows Server 2003 refer to Microsoft IIS 5.1 and IIS 6.0.

In the Windows Start Menu choose "Run:", type "CompMgmtLauncher" and click "Ok";

If the "Web Server (IIS)" role is not present under the "Roles" node, then add it by clicking "Add Roles";

If the "Web Server (IIS)" role is present, then click "Add Role Services" and then enable the "CGI" checkbox under "Application Development" group;

Click "Next" and then "Install" and wait for the installation to complete.

Configuring IIS to process PHP requests
Download and install PHP in accordance to the instructions described in manual installation steps

Note: Non-thread-safe build of PHP is recommended when using IIS. The non-thread-safe builds are available at » PHP for Windows: Binaries and Sources Releases.

Configure the CGI- and FastCGI-specific settings in php.ini file as shown below:

%windir%\system32\inetsrv\appcmd set config /section:system.webServer/fastCGI ^
/+[fullPath='c:\PHP\php-cgi.exe']

Configure IIS to handle PHP specific requests by running the command shown below. Replace the value of the scriptProcessor parameter with the absolute file path to the php-cgi.exe file.

Example #3 Creating handler mapping for PHP requests

%windir%\system32\inetsrv\appcmd set config /section:system.webServer/handlers ^
/+[name='PHP_via_FastCGI', path='*.php',verb='*',modules='FastCgiModule',^
scriptProcessor='c:\PHP\php-cgi.exe',resourceType='Either']

This command creates an IIS handler mapping for *.php file extension, which will result in all URLs that end with .php being handled by FastCGI module.

Note: At this point the required installation and configuration steps are completed. The remaining instructions below are optional but highly recommended for achieving optimal functionality and performance of PHP on IIS.

Impersonation and file system access
It is recommended to enable FastCGI impersonation in PHP when using IIS. This is controlled by the fastcgi.impersonate directive in php.ini file. When impersonation is enabled, PHP will perform all the file system operations on behalf of the user account that has been determined by IIS authentication. This ensures that even if the same PHP process is shared across different IIS web sites, the PHP scripts in those web sites will not be able to access each other's files as long as different user accounts are used for IIS authentication on each web site.

For example IIS 7, in its default configuration, has anonymous authentication enabled with built-in user account IUSR used as a default identity. This means that in order for IIS to execute PHP scripts, it is necessary to grant IUSR account read permission on those scripts. If PHP applications need to perform write operations on certain files or write files into some folders then IUSR account should have write permission to those.

To determine what user account is used as an anonymous identity in IIS 7 use the following command. Replace the "Default Web Site" with the name of IIS web site that you use. In the output XML configuration element look for the userName attribute.

appcmd.exe set config -section:system.webServer/fastCgi ^
/+"[fullPath='C:\php\php.exe',arguments=''].environmentVariables.^
[name='PHPRC',value='C:\Some\Directory\']" /commit:apphost

Integrating Tomcat with Apache

If you write JavaServer Pages or use Servlets to provide the functionality of your Web site, you're probably already aware of Tomcat. Tomcat is the Apache Foundation's reference implementation of the JavaServer Pages and Servlet technologies. Tomcat 3 covers the Servlet 2.2 and JSP 1.1 revisions, while Tomcat 4 covers Servlet 2.3 and JSP 1.2. Tomcat itself is part of the Jakarta Project, which is a suite of Java development tools developed through the Apache foundation.

Installing Tomcat itself is relatively easy — download the corresponding installer from the Tomcat pages at Apache, expand the files or run the installer, and then use the corresponding script to start up the Tomcat service. Tomcat has its own built-in HTTP service that handles and services requests from clients. We'll look at the specific steps later in this article.

To integrate the Tomcat server processes with the Apache HTTP server we need the mod_jk module, which implements the interface between Tomcat and Apache, combined with some small steps to configure Apache and Tomcat to our needs.

Tomcat is written in Java, while Apache and its modules are written in C, so how do the two work together?

Well, when Tomcat executes as well as creating an HTTP listener service, it also creates a number of "worker" processes responsible for executing JSPs/servlets. The mod_jk module is written in C, so it's incapable of interpreting Java classes directly. Instead, mod_jk communicates with the various worker processes created by Tomcat through a network connection. There is, of course, slightly more to it than that, but the core execution is handled through Apache to Tomcat and back again.

There are some advantages to this method, even though it looks convoluted. The primary advantage is flexibility. For example, if you wanted to run Apache (and mod_jk) on one physical server but the Tomcat service and the actual JSPs and servlets on another machine, you can. Some companies use this method to provide an additional level of security, with the Tomcat server behind another firewall only accessible from the Apache server.

Another advantage is stability — if a significant failure within Tomcat caused it to fail completely, it wouldn't render your entire Apache service unusable, just your servlets and JSP pages.

We'll be using Tomcat 4.1.18, although the connector pack we'll be using will actually work with any version of Tomcat you want to use.

Installing Tomcat
Tomcat is very easy to install, as the only prerequisite is Java. If you don't already have the Java SDK (you need the SDK rather than the runtime) you can get a copy of Java for most platforms here.

After you've installed Java, make sure you set your JAVA_HOME environment variable to point to your Java installation, as it's needed not only by Tomcat but also by other tools we use in this article. You'll probably also want to set your PATH variable to point to the bin directory within the Java directory so you have easy access to all the Java tools.

Now download Tomcat. There's no installer under Unix/OS X, so once downloaded, extract the package and then copy the directory created to where you want to store your Tomcat installation. Within Windows use the installer.

Once installed, you can startup and shutdown Tomcat using the provided scripts. These are in the bin directory and called startup (Windows) or startup.sh (Unix). By default Tomcat runs on port 8080. To change this, edit the file conf/server.xml in the Tomcat directory and replace 8080 with the port number you want to use.

You can test your installation by opening up a web browser and entering a suitable URL for your machine.

Shutdown scripts are provided in the bin directory if you want to shutdown your Tomcat installation.

Installing mod_jk
The easiest way to get hold of a suitable mod_jk library is to go to the project's build directory. From there you'll find a number of directories for different platforms. Within each directory are two files, mod_jk for use with Apache 1.3.x and the other for use with Apache 2.x.

Download the file and copy it into your libexec or modules directory within your Apache server installation.

Building mod_jk
If you really want (or need) to, you can build your own mod_jk from the source. You'll need to download the Jakarta Tomcat Connectors pack. You'll also need Ant, the Apache Java build engine.

The Apache Tomcat 5.5 Servlet/JSP Container

Introduction
This document introduces several ways to set up Tomcat for running on different platforms. Please note that some advanced setup issues are not covered here: the full distribution (ZIP file or tarball) includes a file called RUNNING.txt which discusses these issues. We encourage you to refer to it if the information below does not answer some of your questions.

Windows
Installing Tomcat on Windows can be done easily using the Windows installer. Its interface and functionality is similar to other wizard based installers, with only a few items of interest.


Installation as a service: Tomcat will be installed as a Windows NT/2k/XP service no matter what setting is selected. Using the checkbox on the component page sets the service as "auto" startup, so that Tomcat is automatically started when Windows starts. For optimal security, the service should be run as a separate user, with reduced permissions (see the Windows Services administration tool and its documentation).
Java location: The installer will use the registry or the JAVA_HOME environment variable to determine the base path of a J2SE 5 JRE.
Tray icon: When Tomcat is run as a service, there will be a tray icon visible. Note that when choosing to run Tomcat at the end of installation, the tray icon will be loaded at the same time.
Refer to the Windows Service HOW-TO for information on how to manage Tomcat as Windows NT service.

Unix daemon
Tomcat can be run as a daemon using the jsvc tool from the commons-daemon project. Source tarballs for jsvc are included with the Tomcat binaries, and need to be compiled. Building jsvc requires a C ANSI compiler (such as GCC), GNU Autoconf, and a JDK.

Before running the script, the JAVA_HOME environment variable should be set to the base path of the JDK. Alternately, when calling the ./configure script, the path of the JDK may be specified using the --with-java parameter, such as ./configure --with-java=/usr/java.

Note that the Commons-Daemon JAR file must be on your runtime classpath to run Tomcat in this manner. The Commons-Daemon JAR file is in the Class-Path entry of the bootstrap.jar manifest, but if you get a ClassNotFoundException or a NoClassDefFoundError for a Commons-Daemon class, add the Commons-Daemon JAR to the -cp argument when launching jsvc.

Thursday, 10 December 2009

Learn JavaScript The Hello World Project

Introduction

Just about all programming courses start off with a simple program called "Hello World". This program is designed to output the text "Hello World" from the program and is designed to introduce you to the programming language and show you how to write, compile, and execute programs using that language. JavaScript is a scripting language so it doesn't need to be compiled - instead it is executed directly by the web browser - but we still need to know how to write the code and attach it to our web page.
Your First Script

The first thing that we need to do is to add some HTML into the body section of our web page.
<script type="text/javascript">

</script>
These two lines form a container into which we can place our JavaScript code. The parameters on the script tag identify the content surrounded by these tags as JavaScript code to be executed rather than text to be displayed.
There will also be times when you will want to add JavaScript to the head section of your page (which is the best place to put it all) and some JavaScript can even be added into parameters in the HTML tags themselves but for the first few tutorials we will stick with placing our JavaScript between these tags in the body section of the page.
Where about's in the body section should you place the tags? Well the JavaScript is going into the body section of your page because we intend to use the JavaScript to display something on the page. The script tags (and the JavaScript that we are about to add to it) should therefore be positioned within your page content at the place where we want the output from the script to appear.
The usual purpose of a "Hello World" script is to output the text "Hello World" so let's add the JavaScript statement to do this between the HTML script tags. The complete code added to the page will now look like this:
<script type="text/javascript">

document.write('<b>Hello World</b>');

</script> So let's examine our first line of JavaScript and see what we have learned so far about writing JavaScript code.
The first thing that we have learned is that we can get JavaScript to output something to our web page by using document.write. The "document" part of this command identifies the current web page as what we are updating and the "write" is how we are updating it - ie. by writing something to the page. You will find the what portion of these commands is usually referred to as an object and the how portion is usually referred to as the method. The actual value that is to be written out is contained between the parentheses that follow.
In this instance we want to write out the text "Hello World". In the example I have surrounded the text with apostrophes (') rather than quotes ("). Surrounding your JavaScript text with apostrophes rather than quotes will make it easier to including quotes in the text to be written out.
The example text is also surrounded by HTML bold tags. This will result in the text being displayed on the page in bold. You can easily include HTML code into your JavaScript document.write statements and since the JavaScript writes its output into the page before the page is processed by the browser, any HTML that is included will be processed exactly the same as if it were statically coded into the page.
Finally you will notice that the line ends with a semi-colon (;). The semi-colon is what determines where individual JavaScript statements end in the same way that a greater than (>) determines where an HTML tag ends.
The document.write statement is the easiest way to output something into our web page. It certainly isn't the best way (it's the worst way) but it is the easiest way and so we will use it through the earlier tutorials while looking at the core part of the JavaScript language.
If you look at other people's JavaScript you may find a language="javascript" (possibly with a number on the end). That part of the script tag is now obsolete and should be removed (you may still find it on some of the pages of this site that were written some time ago and which I haven't yet had time to go back and correct, if you do then just make sure you use type='text/javascript' instead).
Using What You Know

At this stage you are probably wondering what you can possibly do using just the JavaScript that you have learned in this first tutorial. Well not everyone uses a web browser that supports JavaScript and some whose browsers do support JavaScript have it disabled. We can make use of what we already know to hide parts of our page from those whose browsers don't support JavaScript.
Suppose that we have obtained some complex JavaScript from one of the many JavaScript libraries available on the internet and have followed the instructions to install it on one of our web pages. We might now have a web page that only functions correctly when JavaScript is enabled. It would be preferable if we could hide the existance of that page from visitors whose browsers don't have JavaScript enabled.
We can use what we have learned in this tutorial to edit the page(s) that link to the page that we want to hide so that the link only appears when JavaScript is enabled. To do this we locate the HTML code in the page that forms the link to the page to be hidden and replace the static link code with our JavaScript code above. For example, suppose the static link code reads as follows:
<a href="script.htm">Page Requiring JavaScript</a>
We would replace this code exactly where it appears with:
<script type="text/javascript">

document.write('<a href="script.htm">Page Requiring JavaScript</a>');

</script>
For visitors who have JavaScript enabled the page will look exactly the same as before but for those visitors without JavaScript the link to script.htm no longer appears.

Writing Your First VB.NET Program

If you have some experience with VB 6, you'll find that Visual Studio has changed as much or more than the rest of the .NET world. And it's changed for the good!

The "Microsoft Press" aspects of our text start to show up here, however. The text makes it seem like the new VS.NET is sooooo good that we have almost been translated into heaven when we use it.

But there are a couple of things that can trip you up.

As we read Chapter 1, I'll try to point out both a few of the hazards as well as going beyond the book to a few things that were not covered.

Hopefully, those of you who had to install VB.NET met with success! While our text is really great at explaining VB AFTER it's installed, it's strangely quiet about all the cartwheels and handsprings you have to do to get it installed. Most of the installation problems are there to make sure that nobody, but nobody, has a copy of VB that they didn't pay for!!! (Nary a leaf falls upon the Earth but that Microsoft makes a penny of revenue from it's falling!)

The VB.NET solution files, like their counterparts in VB 6, are a repository for the source and compiled versions of the application and also maintain information about the project for Visual Studio. But there are more of them in VB.NET and they're organized in a more complicated directory structure.

For a Windows Application project, you can also browse these XML files:

•Form1.resx
•WindowsApplication1.vbproj.user
And the character based, but not XML files:

•WindowsApplication1.sln
•AssemblyInfo.vb
•Form1.vb
Note that, except for AssemblyInfo.vb, these names will change if the name of the project changes.

The rest of Chapter 1 is all about modifying Properties in the first practice project supplied on the CD with the book, MusicTrivia. But since we're moving on to the creation of our own project in the next chapter, it would be a shame to leave this chapter without also checking out the code in the MusicTrivia project. So let's do that now.

After you have changed the Properties as suggested in the book, make sure that Solution Explorer is visible as shown above and then right-click the MusicTrivia.vb file to display the Context Menu and select View Code. You should see this code. (Note: the two Sub statements have been reformatted to make them fit the web page.)

~~~~~~~~~~~~~~~~~~~~~~~~~
Public Class Form1
Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

Private Sub Button1_Click
(ByVal sender As System.Object,
ByVal e As System.EventArgs)
Handles Button1.Click
Label2().Visible = True
PictureBox1().Visible = True
End Sub

Private Sub Button2_Click
(ByVal sender As System.Object,
ByVal e As System.EventArgs)
Handles Button2.Click
End
End Sub
End Class
~~~~~~~~~~~~~~~~~~~~~~~~~

At the top of page 20, the book discusses the fundamental nature of Properties and notes that Properties can be set initially (that is, before the program is compiled and run) or while the program is running. The code for the Button1 event subroutine is an example of changing properties while the program is running.

If you "play around" with this code for a while, you'll be very well prepared for the next lesson. So it's a great way to get the jump on learning until the next lesson arrives in your email!

Monday, 7 December 2009

Drawing Pie Shapes in GDI+

A pie is a slice of an ellipse. A pie shape also consists of two radial lines that intersect with the endpoints of the arc. Figure 3.30 shows an ellipse with four pie shapes.

The Graphics class provides the DrawPie method, which draws a pie shape defined by an arc of an ellipse. The DrawPie method takes a Pen object, a Rectangle or RectangleF object, and two radial angles.

Let's create an application that draws pie shapes. We create a Windows application and add two text boxes and a button control to the form. The final form looks like Figure 3.31.

The DrawPie button will draw a pie shape based on the values entered in the Start Angle and Sweep Angle text boxes. Listing 3.22 shows the code for the DrawPie button click event handler.

LISTING 3.22: Drawing a pie shape

Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Linq
Imports System.Text
Imports System.Windows.Forms

Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' Create a Graphics object
Dim g As Graphics = Me.CreateGraphics()
g.Clear(Me.BackColor)

' get the current value of start and sweep angles
Dim startAngle As Single = CSng(Convert.ToDouble(textBox1.Text))
Dim sweepAngle As Single = CSng(Convert.ToDouble(textBox2.Text))

' Create a pen
Dim bluePen As New Pen(Color.Blue, 1)

' Draw pie
g.DrawPie(bluePen, 20, 20, 100, 100, startAngle, _
sweepAngle)

' dispose of objects
bluePen.Dispose()
g.Dispose()
End Sub
End Class

jQuery Tutorials for Designers

This article contains 10 visual tutorials intended for web designers and newbies on how to apply Javascript effects with jQuery. In case you don’t know about jQuery, it is a "write less, do more" Javascript library. It has many Ajax and Javascript features that allow you to enhance user experience and semantic coding. Since these tutorials are focused on jQuery, I’m not going to get into the details of the CSS.

Dynamic forms builder with jQuery

Recently I have searched a foms editor - wizard" in web mode. I looked for it on internet, believing many projects should greatly deal with this problem (I don't like to develop something if it already exist). After many tests I have come to the conclusion that it does not exist (or that it is not well "referenced"...). Also I have taken advantage of my holidays to do this "little" project. After my research I signal you the following sites which seem quite good but do not fit my objectives (tey were not in opensource).

Como interpretar Google Analytics

Una vez configurado Google Analytics en nuestro sitio ya lo tenemos todo listo para empezar a recoger información. Con este post lo único que quiero es dejar claro que “la información si no se sabe interpretar no es información, son datos” que no sirven para nada.

No quiero plantearlo como un manual, sino más bien como reflexiones que podemos sacar de Google Analytics y que nos pueden servir de cara al posicionamiento web o a la conversión de objetivos en el sitio.

En usuarios podemos ver las visitas por ubicación, lo cual nos puede ser útil para orientar las campañas de Adwords por ciudades. Incluso ver qué palabras clave funciona mejor en qué ciudades y hacer campañas orientadas claramente a conseguir clicks.

Las opciones del navegador son muy útiles para intentar optimizar los sitios. Aunque tendrían que estar optimizados para todos los navegadores no es así. Si no preguntadle a “Viajes el Corte inglés”.

Haciendo pruebas me di cuenta que el tiempo medio de estancia en IE6 era casi el doble que en IE7. Así que cuando entre con IE7 me di cuenta que se descolocaban algunas cosas. “Lo siento pero esta es una de las consecuencias de ser maquero”.

En fuentes de tráfico podemos ver todo lo referente a cómo acceden a nuestra web. Podemos ver que palabras claves nos reportan más visitas y optimizar mejor el sitio para mejorar las posiciones o mantenernos ahí. Si el sitio está orientado a objetivos otra opción es enfocarnos a las palabras claves que nos reportan mayor número de conversiones y aumentan el roi

Porcentaje de rebote es el % de visitas que se van en esa página, generalmente con el botón atrás del navegador si es la de entrada, un enlace o escribiendo en la barra de dirección si no ha entrado desde ahí. Suele ser porque no nos ha convencido la página.

Si además el tiempo en el sitio de la página es reducido, el diseño flaquea, es cutre, etc… Si es largo, es el contenido el que falla. O bien no es lo que buscábamos, estamos cometiendo errores de posicionamiento en la mente del consumidor o simplemente el contenido no convence. Esto último es muy importante y significativo si hay un formulario para solicitar información, un campo para suscribirse, etc…

La sección de contenidos es muy útil para la conversión de objetivos y el redireccionamiento de usuarios. Redireccionar a un usuario es intentar hacer que siga la ruta que quieres, y que generalmente, lleva a rellenar un formulario de contacto, suscripción, etc…

Cuando vemos las páginas más visitadas la “ruta de navegación” es interesantísima para ver las páginas siguientes a las que suelen ir los usuarios. “En un proyecto reciente me di cuenta que todo el que entraba en el sitio iba directamente a clientes, que estaba casi al final en el menú”, después a localización y a contactar para rellenar el formulario.

Con estos datos sacas la conclusión de que lo importante en el sector del diseño web son los clientes y ver ejemplos de los trabajos, después ver si son de tu ciudad y te puedes pasar por su oficina y si nos convence contactamos.

La mejor solución fue poner “clientes” al lado de inicio, la localización del sitio en una barra lateral y un enlace a la página contactar. Algo tan simple aumentó las conversiones un 45%.

También podemos ver las distintas páginas a las que van las visitas y poner enlaces a las mismas y orientar el texto de la página a la siguiente, que si salen bien las cosas, es a la que va a ir el usuario.

Bueno, estas son unas pequeñas reflexiones que espero os hayan servido. Si necesitais un manual seo con el que complementar o un consultor de marketing online ya sabeis…

También podeis consultar el manual de google analytics es español o ponerte en contacto conmigo desde el e-mail


Saludos!!

Aprendiendo a usar Google Analytics

Resumen: La herramienta de Google que puede conseguir que las organizaciones presten más atención a las estadísticas y las tengan en cuenta en su toma de decisiones.

Debate (10 comentarios) | Valoración media: 2,97 | Votos: 4471 | Lecturas: 21518

Hasta ahora siempre había usado Awstats y aunque tenía muchas limitaciones, me había acostumbrado a esta herramienta de análisis de estadísticas de servidor. Sin embargo hace unos meses Ubaldo me comentó las bondades de Google Analytics y decidimos ponerlo en Panoramio y Alzado. Al principio la adaptación fue difícil, pero pero tres meses más tarde las ventajas de Google Analytics (en adelante GA) se han hecho evidentes:

Permite comparaciones y seguir tendencias

Un número en bruto no sirve de nada si no lo puedes comparar con otro. Saber que en X periodo han habido Y páginas vistas no te dice mucho, ¿es mucho o poco? ¿va el sitio bien o mal? Solo cuando comparas un dato con otro de un periodo equivalente del pasado los números sirven para algo. Cualquier experto en análisis de datos sabe esto y es justo lo que hace GA.

Con casi cada dato que da, GA incluye por defecto la comparación con un dato anterior y la correspondiente tendencia (flechitas verde, sube, o roja, baja). Esto ayuda a saber de un vistazo la evolución del sitio. La comparación por defecto es de una semana, pero se puede configurar al periodo que nos interese.

Los tradicionales programas de estadísticas dejan mucho que desear porque aunque incluyen todos los datos (incluso más datos que GA), las comparaciones deben ser de memoria. Ciertamente con el tiempo sueles aprender los números que sueles tener, es un poco primitivo, poco fiable y no te da una visión clara de la evolución del sitio.

El gran incoveniente de GA es el primer día. Al estar tan centrado en comparar datos y buscar tendencias, sin datos históricos sus tablas de datos apenas tienen sentido. Puesto que GA no analiza los logs de servidor sino que funciona a partir de un código que se incluye al final de cada página solo puede tener datos desde el día que el código se incluyó. Esto provoca que la primera visión sea decepcionante. Hay que tener paciencia y dejarlo correr un par de semanas para que muestre sus ventajas.

Centrado en lo más probablemente relevante

Tradicionalmente los programas de estadísticas incluyen mucha información poco relevante: información sobre hits, ancho de banda, accessos de robots, host, tipos de archivo descargados, etc. Añadir más información no es gratis, tiene un coste, la información menos relevante quita visibilidad a la información más relevante.

Ciertamente estos datos pueden ser útiles para personas que trabajan en optimización de buscadores o para los técnicos que se preocupan del rendimiento del servidor. Sin embargo este exceso de información menos relevante y compleja, conlleva que el resto de miembros de la organización y especialmente los responsables del sitio, terminen ignorando las estadísticas.

En mi experiencia quienes toman las decisiones, apenas consultan las estadísticas más allá de las páginas vistas y el número de visitantes globales. Normalmente simplemente no entienden las estadísticas, no son capaces de sacar conclusiones y creo que en parte es por a causa de la interfaz de los programas de estadísticas tradicionales. Ignorar las estadísticas supone que los responsables tomen decisiones sin tener en cuenta una información crucial y opten por la intuición en lugar de los datos cuantitativos objetivos.

En lugar de incluir toda la información disponible de una vez, GA se centrá en solo lo que estima que más probablemente sea útil y relevante (fuentes del tráfico, contenidos más vistos, rutas de clicks, conversiones, etc.). Incluso tiene un resumen ejecutivo y el resto de información la segmenta según los objetivos (marketing, contenido, conversiones, etc.) y en diferentes niveles de detalle. La información se dosifica.

Además para no saturar con largos listados por defecto solo muestra los principales 5 datos de cada análisis. Evidentemente sacrifica detalles para dar una visión rápida y clara de lo más relevante para un siti web. Con este enfoque, GA no está dirigido a quienes disfrutan mirando las estadísticas de su sitio hasta el mínimo detalle para saber donde ha sido referenciado su blog y de donde han venido 2 visitantes.

Por otro lado la integración de Adwords con Google Analytics y la posibilidad de definir metas y averiguar conversiones (de visitante a cliente, o de registro a subida de fotos, por ejemplo) son herramientas increíblemente útiles para mejorar la usabilidad del sitio y que ciertamente interesarán mucho a los responsables del sitio y la gente de marketing.

Conclusiones

GA es especialmente útil para quienes no quieren perder demasiado tiempo mirando estadísticas, pero necesitan conocer rápidamente los números más relevantes del sitio y conocer tendencias.

Quienes por distintas razones hasta ahora han prestado poca atención a las estadísticas de su sitio web GA les da la oportunidad para sacarles jugo y utilizarlas como herramienta básica tanto es la toma de decisiones como en el día a día.

Nota: Aunque parte de la crítica que hice a los sistema de estadísticas en el artículo: Logs y estadísticas: la verdad, pero no toda, sigue siendo válida, algunos de los problemas se resuelven con sistemas como GA.

Google Analytics para principiantes

Tras leer este artículo esta mañana me pareció buena idea traducirlo para compartirlo con el mundo de habla hispana, porque como yo en su momento, me imagino que habrá mucha gente que se vaya animando a usar Google Analytics para las estadísticas de sus sititos webs. Tanto por el hecho de que es gratuito, como por su potencia.Google Analytics es una de las mejores herramientas que existen para analizar el tráfico de tu sitio web.

Configurandolo un poco, te proporcionará una enorme cantidad de información sobre quién llega a tu sitio, que buscan, y como llegan hasta allí. De hecho, tiene tantísima información que puede ser abrumador.

No te dejes asustar. Con un poco de práctica, tu también podrás usar Google Analytics como un profesional.

Traducido y adaptado de: Mahalo.com

Paso 1: Abre tu cuenta
Para poder usar Google Analytics, necesitarás abrirte una cuenta con ellos. Así obtendrás un identificador único para añadir a tu sitio. Sólo puedes acceder a información sobre tu propio sitio; no puede acceder a la información de otros sitios al manoes que el propietario del sitio de conceda explicitamente acceso. Las únicas personas que accederán a tu sitio será gente a la que le concedas permisos para hacerlo.

Ve a Google Analytics.
Si no tienes una cuenta con Google, haz click en "Regístrese Ahora", a la izquierda del cuadro de acceso. Esto te llevará a una página donde puedes registrar una cuenta de Google.
Si ya tienes una cuenta de Google, usa la dirección y clave de tu email para acceder.
Haz click en el botón "Acceder" para continuar.
En la siguiente ventana, dale a Google la URL del sitio que deseas analizar.
Dale al sitio un nombre de cuenta que sea fácil de recordar. Si vas a estar siguiendo varios sitios, esto es especialmente importante.
Selecciona el país a donde está dirigio tu sitio o desde el que haces el seguimiento. Luego selecciona la zona horaria adecuada.

- Si tu sitio está alojado en los Estados Unidos pero tus usuarios son principalmente de España, lo lógico es que elijas la zona horaria de España o puede que prefiers elegir la zona de la ciudad en la que residas.

Haz click en "Continuar".
En la próxima ventana, entra tu información de contacto.
Y haz click de nuevo en "Continuar".
A continuación, leete los "Términos del Servicio" de Goolge Analytics. Y si estás de acuerdo con ellos, haz click en la casilla "Si".
Haz click "Crear una nueva cuenta".
Google te dará un bloque de código. Copialo - necesitarás insertarlo en tu sitio web-
Paso 2: Inserta el Javascritp de Google Analytics en tus páginas
Debes insertar el código en cada página de la que quieras estadísticas. Si tienes algúna técnico a cargo de tu web, deja que el añade el código por tí.

Añadiendo el código de Google Analytics para la mayoría de los sitios
Para insertar el código de Google Analytics, necesitas meterte en las tripas de tu página - el HTML. Si usas un servicio como WordPress, necesitarás abrir el fichero "footer.php" para colocar el código, y en Joomla el "index.php" de tu plantilla.
Encuentra el tag al final de tu página, debe estar justo encima del tag .
¿ Ves el código urchinTracker(), utmLinker(), utmSetTrans(), o utmLinkPost() sobre el tag ?

- Si es así, debes pegar el Javascript de Google Analytics sobre ese código. Si no, pegalo inmediatamente justo sobre el tag.

Si tienes plantilla, inserta el códgio en ellas también.
Una vez haz subifo las páginas de vuelta a tu sitio, ya puedes empezar a seguir la información.
Paso 3: Obten una visión general de tus visitas
En cuanto tienes tu cuenta e insertas el Javascript de Google en tus páginas, Google Analytics te proporciona fantásticas gráficas que te darán una visión general del tráfico en tu sitio, si sabes como leerlos.



Accede a Google Analytics.
En el centro de la página hay una sección titulada "Perfiles del sitio web". Haz click en el enlace "Ver Informes" que está a la derecha del nombre del sitio en el que estás interesado. Esto te abrirá el Panel.
En la parte superio de la págin hay una gráfica que muestra una representación visual del tráfico de tu sitio a lo largo del mes pasado.

- Esta gráfica solo te dará datos desde que insertaste el código para el seguimiento en tus páginas.

- Si quieres cambiar el rango de tiempo que el gráfico muestra, haz click en las fechas en la esquina superior-derecha. Haz click en las fechas del calendario que aparece o teclealas manualmente para ver un ragno de tiempo diferente.

- Para comparar tráfico sobre dos periodos distintos, selecciona un rango de datos que quieras usar, haz click en "Compara con anterior", y selecciona el rango contra el que quieres comparar.

- Justo debajo de las fechas hay un menú que dice "Visitas". Haz click en el para cambiar la gráfica a "Páginas vistas" (cuantas veces han sido vistas las páginas de tu sitio), "Páginas/Visitas" (cuantas páginas de tu sitio visitan los usuarios de media), "Promedio de tiempo en el sitio" (cuanto tiempo pasan los usuarios en tu sitio), "Porcentaje de abandonos" (que porcentaje de usuarios dejan el sitio habiendo visitado sólo una página), o "Porcentaje de visitas nuevas" (cuantos visitantes nunca han estado antes en tu sitio).

A continuación bajo esa gráfica, verás una cabecera que dice "Uso del sitio", con seis pequeñas gráficas debajo. Bajo "Uso del sitio", encontrarás información rápida sobre varias estadísticas de tráfico para el periodo mostrado en la gráfica principal. Cada uno tiene su propia gráfica.


- "Visitas": te dice cuantas visitas ha habido a tu página. Una visita se define como una página vista cuando el usuario no ha visto ninguna otra página en la pasada media hora.

- "Páginas Vistas": te dice cuantas veces las páginas de tu sitio han sido vistas.

- "Paginas/Visitas": muestra cuantas páginas, de media, los usuarios ven cuando llegan hasta tu sitio.

- "Porcentaje de abandonos": que señala el porcentaje de usuarios que marcharon tras ver solo una página de tu sitio.

- "Promedio de tiempo en el sitio": muestra cuanto tiempo estuvo cada usuario en su visita.

- "Porcentaje de nuevas visitas": indica el porcentaje de usuarios que no han sido tu sitio anteriormente.

El gráfico "Visión general de usuarios" muestra cuantos visitantes han llegado a tu sitio.

- Este número es por lo general inferior a la estadísticas de visitas, y a veces mucho más pequeño, porque algunos visitantes pueden visitar tu sitio una y otra vez.

- Haz click en "Ver informe" para ver una información más detallada sobre tus visitantes.

"Gráficos de visitas por ubicación" muestra de que paises vienen tus visitantes.

- Cuanto más oscuro el verde, más visitantes son de ese país.

- Haz click en "Ver informe" para obtener información en profundidad sobre de donde vienen tus visitantes.

"Visión general de la fuentes de tráfico" muestra que porcentaje de usuarios llegan a tu sitio tecleando tu URL directamente en sus navegadores, y via motores de búsqueda, sitios de referencia, y otras formas como enlaces en emails.

- Haz click en "Ver informe" para obtener un desglose de exactamente de que lugares vienen tus usuarios, y que palabras clave estaban buscando.

"Visión general del contenido" especifica las cinco páginas más vistas en el periodo que tienes seleccionado.

- Haz click en el nombre de cualquier página para obtener información muy detallada sobre de donde venian las personas que han vsto esa página, cuanto tiempo pasaron en la página, cuantos eran nuevos en la página, y mucho más.

- Hax click en "Ver informe" para acceder a la información sobre el tráfico de todas las páginas del sitio.

Paso 4: Ve como se comporta tu sitio diariamente y en cada hora
Si quieres descubrir si tu sitio tiene picos durante ciertas horas del dia o en ciertos dias de la semana, Google Analytics te lo puede decir.

En el menú de la izquierda, haz click sobre la palabra "Usuarios".
A la izquierda bajo el gráfico principal, verás una serie de estadísticas diferentes.
Haz click en cualquiera de las palabras para obtener una gráfica con el desglose de la actuación diaria para esa medida del aspecto del tráfico del sitio.
Si quieres estudiar las tendencias hora por hora, haz click en la palabra "hora" sobre el gráfico para ver una gráfica hora por hora para el periodo de tiempo en el que estás.
Para comparar dos periodos de tiempo distintos, haz click en las fechas sobre el gráfico de linea.
Selecciona el primer conjunto de fechas con las que quieres trabajar, marca la casilla "Comparar con anterior", haz click en el segundo rango de fechas, y haz click en el botón "Aplicar intervalo".

Paso 5: Mira de donde viene tu tráfico
¿ Te está llegando la mayoría del tráfico de los motores de búsqueda? ¿ Hay un blog que enlaza a tus páginas y genera un montón de tráfico ? Aquí tienes como descubrirlo.

En la esquina inferior derecha del Panel encontrarás las 5 páginas con mayores visitas de tu sitio. Haz click en cualquiera de ellas.
Debajo de la gráfica a tu derecha, verás un titular que dice "Análisis de navegación". Haz click en el enlace inferior donde pone "Fuentes de entrada".
Bajo la gráfica, verás una tabla. Esta tabla muestra todos los lugares de donde venían tus usuarios a visitar tu sitio.

- En la primera columna a la derecha del nombre de la fuente está el número de páginas vista que tu página ha recibido desde esa fuente.

- La siguiente columna dice cuantas de esas visitas fueron páginas vistas únicas - alguien que vino a tu página que no ha estado en esa página antes en el rango de fechas que estes viendo.

- "Tiempo en la página" te indica cuanto tiempo, de media, los usuarios provenientes de esa fuente estuvieron en esa página en cuestión.

- "Porcentaje de abandonos" muestra cuantas personas desde esa fuente específica dejo tu sitiodespués de ver esa página, sin ver ninguna otra.

- "Porcentaje de salidas" muestra cuante gente de esa fuente determinada fue a otro sitio desde esa página. (Este número puede ser inferior que el "porcentaje de abandonos"; en caso de que hayan cerrado la ventana o cerrado el navegador, no es considerado "salida")

- Cuando estableces ciertas medidas financieras en la sección de objetivos, Google procesará los números para mostrarte cuanto estas obteniendo con la columna "Indice de ingresos".

Si quieres conseguir información de otras páginas, en el menú "Contenido" de la izquierda, haz click sobre la opción "Contenido por titulo". Ahora podrás recorrer todo tu contenido para estudiar la información de cada página.
Vuelve al panel principal haciendo click en la palabra "Panel" en la esquina superior izquierda.

Wednesday, 2 December 2009

Go, lenguaje de programación de Google

Productividad, sencillez y rapidez claves del nuevo lenguaje de Google para el desarrollo de aplicaciones y programas.

16/11/2009 - Go, el nuevo lenguaje de código abierto, aún en fase de desarrollo, con el Google se adentra en el terreno de los lenguajes de programación.

Según podemos ver en la web de Go, este proyecto combina el rendimiento y las prestaciones de seguridad propios de un lenguaje compilado como C++ con la velocidad de un lenguaje dinámico como Python.

El proyecto Go, concebido inicialmente para poder escribir de forma optimizada el software que Google utiliza internamente, esta siendo desarrollado, entre otras razones, para dar respuesta a las necesidades de programadores que se posicionan contra la complejidad de sistemas como Java y C++.

La sintaxis del lenguaje de programación Go es muy parecida a la de C. Hasta la fecha, existen versiones para Linux y Mac OS X, con capacidad para compilar ejecutables de las plataformas x86, x86-64 y ARM. La licencia de este lenguaje es libre y de tipo BSD.

Pese a tratarse de un lenguaje experimental cuyo desarrollo se espera siga evolucionando, las características de este lenguaje hacen pensar a Google que Go puede llegar a ser adoptado rápidamente por los programadores en la creación de las primeras aplicaciones.

Interesados en instalar o acceder a completa información técnica de Go pueden hacerlo desde golang.org.

Cookies, cambian las reglas de juego

La Unión Europea reforma la Directiva Europea de Protección de Datos conocida como Directiva ePrivacy.

17/11/2009 - La actual directiva relacionada con la privacidad de los datos personales en las telecomunicaciones ha sido recientemente reformada con una enmienda que afectará directamente a sectores como la publicidad online o las estadísticas de visitas web.

El nuevo régimen jurídico exige que el usuario deba dar su consentimiento explicito para que puedan instalarse en su ordenador nuevas cookies. Además la reforma de la directiva traerá una mayor protección frente a amenazas de seguridad, spyware, cookies o spam.

Las cookies son pequeños archivos que determinados websites colocan en nuestro equipo para almacenar información variada sobre nuestras preferencias.

La reforma establece la excepción en la instalación de una cookie sin que esta deba estar consentida por el usuario en los casos estrictamente necesarios, lo que abre una puerta a la ambigüedad, ya que ¿Qué es lo estrictamente necesario? ¿Quién decide qué es y qué no es estrictamente necesario?

Una Directiva, como la reformada Directiva ePrivacy es una norma con carácter legal que obliga en cuanto al objetivo perseguido pero no en cuanto a la forma en que este objetivo debe llevarse a cabo, lo que supone que los diferentes países miembros de la U.E podrán llevar a la practica, a su manera, la obligación común a todos ellos de mejora de la protección de seguridad y privacidad en las telecomunicaciones perseguidos por esta reforma.

PHP 5.3.1, lanzado

El equipo de desarrollo de PHP anuncia la inmediata disponibilidad de una nueva actualización de seguridad la rama 5.3 de PHP.

23/11/2009 - PHP 5.3.1 es una nueva actualización de seguridad y estabilidad de este lenguaje de programación de libre licencia empleado en la creación de páginas web dinámicas.

El objetivo central de este nuevo lanzamiento es la corrección de más de 75 bugs algunos de los cuales están relacionados con la seguridad.

Entre los problemas de seguridad a los que este lanzamiento pone solución destaca que PHP no limitaba el número máximo de subidas de archivo por petición mientras que ahora son 20 por defecto, y otros errores que podían permitir una denegación del servicio.

Desde PHP se anima a todos los desarrolladores y usuarios de PHP a que se actualicen a la mayor brevedad a PHP 5.3.1.

Interesados pueden acceder a más información de PHP 5.3.1 desde www.php.net

Chrome OS: próximo lanzamiento del sistema operativo de Google

Nuevas informaciones apuntan que Google estaría preparada para lanzar la primera versión en pruebas de su nuevo sistema.

16/11/2009 - Chrome OS, según ha sido anunciado por la web especializada TechCrunch y recogido por varios medios, estaría previsto para ser lanzado antes de fin de año en su primera versión en desarrollo.

Google Chrome OS pretende convertirse en un sistema de código abierto sobre kernel de Linux, centrado en Internet y pensado originalmente para netbooks, que se apoyaría en tres pilares básicos, rapidez, seguridad y simplicidad, características responsables del éxito de la compañía propietaria del popular motor de búsqueda.

La noticia aún no confirmada de forma oficial supondría el inicio definitivo de un nuevo frente para Google (sistemas operativos para netbooks) donde pese al éxito alcanzado con Android (sistema para smartphones) lo tendrá difícil si quiere estar a la altura de compañías con dilatada experiencia como Microsoft con Windows XP o Windows 7 o Ubuntu con Ubuntu Netbook Remix.

Los primeros ordenadores equipados con el sistema operativo Chrome OS, entre ellos Acer, ASUS, HP o Lenovo, no empezarán a ser comercializados hasta la segunda mitad del próximo 2010.

Desde DesarrolloWeb estaremos atentos a la confirmación y lanzamiento de esta primera versión en fase de desarrollo de Google Chrome OS.

Configuración global de Joomla en Español

Principales opciones de la configuración global del CMS Joomla, en español.

Hasta este momento en el Manual de Joomla hemos aprendido simplemente a instalar el CMS. Estamos sólo en el principio de este camino que nos ayudará a hacer webs profesionales auto-administradas, casi sin esfuerzo. En el artículo anterior probábamos la instalación y cambiábamos los datos del usuario de administración. para mayor seguridad. Sabiendo que ya funciona Joomla en nuestro sistema, en este siguiente articulo vamos a ir viendo las distintas opciones de configuración de este interesante CMS.
Vamos a empezar por la pestaña de configuración global que tenemos en el panel de control.




Dentro de esta pestaña tenemos tres pestañas (sitio, sistema, servidor) que vamos ir viendo paso por paso.
Configuración de Joomla: Pestaña sitio
La pestaña sitio tiene tres zonas una para la configuración del sitio, otra para los metadatos y otra para SEO.
En la configuración del sitio podemos modificar por ejemplo el nombre del sitio, el número de items por página, el número de noticias a mostrar, el editor WYSIWYG predeterminado, y bueno algo importante si todavía no tenemos el sitio preparado y es la opción de mostrar en la portada un mensaje donde se informa que el sitio esta en construcción.

Dentro de los parámetros de los metadatos podemos modificar la descripción del sitio y las palabras clave del mismo, así como decidir si mostramos o no dichos metadatos.

Y ya en la zona de SEO podemos decidir si queremos urls amigables, usar apache en modo mod_rewrite o si agregamos sufijos a las urls.

Configuración de Joomla: Pestaña sistema
Esta pestaña es algo mas complicada y tiene parámetros más técnicos pero le daremos un repasoal menos para los elementos más importantes.
Empezamos por la zona de configuración del sistema, donde podemos ver y cambiar la ruta del registro, activar los servicios web o seleccionar un servidor de ayuda.

Después tenemos la zona de parámetros del usuario donde podemos permitir el registro de usuarios, su nivel de acceso, la necesidad o no de activación de la cuenta.

En la zona de configuración multimillonaria podemos listar las extensiones permitidas, el tamaño máximo de los archivos, las rutas de las imágenes, etc. También podemos restringir la subida de los archivos y habilitar la subida de flash.

En otra zona podemos activar o no la depuración de errores tanto de sistema como de idioma.
En la configuración de la cache podemos habilitarla o no y darle un tiempo.

Y por último tenemos la configuración de la sesión en la que damos un tiempo máximo para cada sesión y decidimos quien maneja dichas sesiones, pudiendo ser la base de datos o nada.

Configuración de Joomla: Pestaña servidor
En esta sección podemos encontrarnos con la posibilidad de administrar la ruta de la carpeta temp, la posibilidad de comprimir las paginas para que ocupen menos espacio en el servidor, de cambiar la zona horaria y de habilitar el informe de errores entre otras cosas.
Además podemos introducir los datos del ftp, la base de datos y el servidor de correo.

Con esto tenemos visto todas las opciones de la configuración global de Joomla. En el siguiente artículo que publicaremos pronto en DesarrolloWeb.com veremos la opción de gestión de plantillas, una de las opciones más atrayentes, donde podremos dar un diseño a nuestra web, además de editar las plantillas predefinidas.

Acceder y modificar atributos HTML desde jQuery

En jQuery existe una función llamada attr() que sirve para recuperar y alterar atributos de los elementos de la página.

Con el objetivo de seguir tratando el Core de jQuery, del que ya empezamos a hablar en este Manual de jQuery, vamos a explicar la función jQuery, también conocida como $().
El funcionamiento del Core de jQuery se basa en esta función. Como dicen en la propia documentación del framework, "Todo en jQuery está basado en esta función o la usa de alguna forma".

La función jQuery sirve para hacer varias cosas, según los parámetros que le pasemos. El uso más simple es seleccionar elementos o grupos de elementos de una página web, pero también sirve para crear elementos sobre la marcha o para hacer un callback de funciones.

En realidad esta función se invoca también con el símbolo dólar $(), lo que sería una manera resumida de utilizarla y que nos ahorrará bastantes caracteres en el código y a la postre, tiempo de descarga y peso de los scripts de la página.

Veamos los distintos usos de esta función, según los parámetros que reciba.

Función jQuery enviando un selector y un contexto
Este uso de la función sirve para seleccionar elementos de la página. Recibe una expresión y se encarga de seleccionar todos los elementos de la página que corresponden con ella. Adicionalmente, podemos pasarle un contexto de manera opcional. Si no se le envía un contexto, selecciona elementos del documento completo, si indicamos un contexto conseguiremos seleccionar elementos sólo dentro de ese contexto.
La expresión que debemos enviar obligatoriamente como primer parámetro sirve de selector. En ese parámetro tenemos que utilizar una una notación especial para poder seleccionar elementos de diversas maneras y la verdad es que las posibilidades de selección con jQuery son muy grandes, como veremos en el tema de "Selectores".

Este paso de selección de elementos es básico en cualquier script jQuery, para poder actuar en cualquier lugar de la página y hacer nuestros efectos y utilidades Javascript sobre el lugar que deseemos.

Veamos un uso de esta función:

var elem1 = $("#elem1");

Con esta línea de código habremos seleccionado un elemento de la página que tiene el identificador (atributo id del elemento HTML) "elem1" y lo hemos guardado en una nueva variable llamada elem1.


Nota: Como hemos dicho, $() es un resumen o forma corta de invocar la función jQuery. También podríamos haber escrito la línea de esta manera: var elem1 = jQuery("#elem1");
Luego, podríamos hacer cualquier cosa con ese elemento seleccionado, como lo siguiente:

elem1.css("background-color", "#ff9999");

Este método css() no forma parte del core, pero sirve para cambiar atributos CSS de un elemento, entre otras cosas. Así pues, con esa línea cambiaríamos el color de fondo del elemento seleccionado anteriormente, que habíamos guardado en la variable elem1.

Ahora veamos otro ejemplo de la selección de elementos con la función dólar.

var divs = $("div");
divs.css("font-size", "32pt");

Aquí seleccionamos todas las etiquetas DIV de la página, y les colocamos un tamaño de letra de 32pt.

Podemos ver en una página aparte este pequeño script en uso.

El código de esta página es el siguiente:








Este elemento se llama elem1
Este otro elemento se llama elem2



Si queremos, podemos utilizar el segundo parámetro opcional, que es el contexto. Con él podríamos conseguir seleccionar elementos que pertenecen a una zona concreta de nuestro documento. Por defecto el contexto es la página entera, pero lo podemos restringir de esta manera:

var inputs = $("input",document.forms[0]);
inputs.css("color", "red");

Con la primera línea conseguimos seleccionar todos los elementos INPUT que pertenecen al primer formulario de la página. Con la segunda línea estaríamos cambiando el color del texto de esos elementos. Esto no seleccionaría los INPUT de otros formularios, como se puede ver en esta página de ejemplo.

Ahora por completar un poco más estas notas, veamos otro ejemplo en el que seleccionamos todos los párrafos (etiqueta P), pero restringimos el contexto únicamente los que están en un DIV con id="div1".

var parrafos_div1 = $("p","#div1");
parrafos_div1.hide()

En la segunda línea lanzamos el método hide() sobre los párrafos seleccionados, con lo que conseguimos que se oculten. Podemos ver una página que con este ejemplo en marcha.

El el siguiente artículo veremos otros usos de la función jQuery() / función dólar $().

Instalación y configuración de CodeIgniter

Explicaciones sobre el proceso de instalación y configuración del framework PHP CodeIgniter.

Como apuntábamos en el artículo anterior, en el que presentamos las características principales de CodeIgniter, una de las ventajas de este framework PHP es que su instalación es muy sencilla. Veremos aquí algunos detalles sobre el proceso:
Requisitos de servidor
Necesitamos disponer de un servidor PHP 4 ó PHP 5. Ambos funcionan perfectamente y en el caso de PHP 4, la versión mínima que debemos tener es la PHP 4.3.2.
Por lo que respecta a las bases de datos, CodeIgniter es compatible con unas cuantas, las más habituales en e desarrollo de webs: MySQL (4.1 o posterior), MySQLi, MS SQL, Postgres, Oracle, SQLite, y acceso a cualquier base de datos en entornos Windows por ODBC.

Descarga de CodeIgniter
Podemos descargar la versión más actualizada de CodeIgniter directamente desde su página web, en la sección de descargas: http://codeigniter.com/downloads/
En el momento de escribir este artículo la versión más actual es la 1.7.2, pero probablemente cuando leas este texto ya la hayan actualizado, así que entra al sitio de descargas para estar seguro sobre la versión más nueva que exista.

Instalación de CodeIgniter en 4 sencillos pasos
1.- Descomprimir el paquete
Descomprime el archivo de descarga que has descargado
2.- Sube codeIgniter a tu servidor
Ahora tienes que subir todos los archivos descomprimidos a tu servidor web.

Opción A: Si estás programando en tu ordenador local, para pruebas y desarrollo, deberás tener un servidor instalado en tu ordenador que soporte PHP, para lo que te recomendamos los paquetes Wamp o Xampp. En este caso tendrás que copiar simplemente los archivos de codeIgniter en el directorio de publicación de tu servidor. Puedes colocar los archivos en la raíz del directorio de publicación o bien en un subdirectorio cualquiera.

Opción B: Si estás subiendo CodeIgniter a un servidor web de Internet, en un espacio que tengas contratado de hosting, deberás subir por FTP todos los archivos. Lo general es que copies CodeIgniter en la raíz de tu dominio, para que todas las páginas del dominio se sirvan a través del framework PHP, pero nada te impide copiar CodeIgniter en un subdirectorio particular, para que tu dominio web sólo funcione bajo CodeIgniter en la carpeta donde lo has subido.

3.- Configura la URL base de tu aplicación web
Necesitas decirle a CodeIgniter la URL base de tu aplicación, es decir, la URL para acceder a la raíz de CodeIgniter, según en el servidor y directorio donde lo has colocado, es decir, donde has subido el código del framework. Para ello tienes que abrir el archivo de configuración, que se encuentra en system/application/config/config.php, con cualquier editor de texto y cambiar la variable de configuración llamada que se guarda en $config['base_url'].
Si hemos instalado en local CodeIgniter pondremos http://localhost/ y si además lo colocamos en un directorio específico podría ser algo como http://localhost/directorio_codeigniter
Si hemos instalado el framework en un dominio de Internet podremos indicar algo como http://eldominiodeinstalacion.com/ y si hicimos una carpeta para subir CodeIgniter en ella pondremos el nombre del dominio y luego el nombre de la carpeta o carpetas, separadas por barras y acabando siempre en una barra: http://eldominioquesea.com/carpeta/otracarpeta/
Según nos indican en el manual de instalación, aparte de este dato podemos opcionalmente escribir una llave de encriptación en la variable $config['encryption_key'], que servirá si deseamos usar la clase de encriptado que proporciona CodeIgniter o queremos que nuestras variables de sesión estén encriptadas, algo que hace el framework de manera transparente para nosotros.

4. Configurar la base de datos
En este último paso tendrás que indicar los datos de acceso a la base de datos que piensas utilizar con CodeIgniter, ya que prácticamente todas las aplicaciones web que podrás crear con el framework van a tener que utilizar la base de datos para algo. Para ello tenemos que editar el archivo system/application/config/database.php e indicar los parámetros de conexión al servidor de base de datos, como el nombre del servidor y nombre de la base de datos, el usuario y la contraseña.

Con esto ya tenemos todo listo para comenzar a crear nuestras aplicaciones web PHP. Podemos testar CodeIgniter accediendo a la URL donde lo hemos instalado. Debemos ver el mensaje de bienvenida de CodeIgniter que nos confirma que está funcionando.

CodeIgniter

CodeIgniter es un framework PHP para la creación rápida de aplicaciones web. Presentación general del framework y primeras notas para empezar a usarlo.

Probablemente ya sepamos que un framework es un programa para desarrollar otros programas, CodeIgniter, por tanto, es un programa o aplicación web desarrollada en PHP para la creación de cualquier tipo de aplicación web bajo PHP. Es un producto de código libre, libre de uso para cualquier aplicación.

Como cualquier otro framework, Codeigniter contiene una serie de librerías que sirven para el desarrollo de aplicaciones web y además propone una manera de desarrollarlas que debemos seguir para obtener provecho de la aplicación. Esto es, marca una manera específica de codificar las páginas web y clasificar sus diferentes scripts, que sirve para que el código esté organizado y sea más fácil de crear y mantener. CodeIgniter implementa el proceso de desarrollo llamado Model View Controller (MVC), que es un estándar de programación de aplicaciones, utilizado tanto para hacer sitios web como programas tradicionales. Este sistema tiene sus características, que veremos en artículos siguientes.

CodeIgniter no es magia, pero contiene muchas ayudas para la creación de aplicaciones PHP avanzadas, que hacen que el proceso de desarrollo más rápido. A la vez, define una arquitectura de desarrollo que hará que programemos de una manera más ordenada y contiene diversas herramientas que ayudan a hacer aplicaciones más versátiles y seguras.

CodeIgniter y otros frameworks PHP pueden ayudarte a dar el salto definitivo como desarrollador PHP, creando aplicaciones web más profesionales y con código más reutilizable, con la diferencia que Code Igniter está creado para que sea fácil de instalar en cualquier servidor y de empezar a usar que cualquier otro framework. Además muchas de sus utilidades y modos de funcionamiento son opcionales, lo que hace que goces de mayor libertad a la hora de desarrollar sitios web.

Características generales de CodeIgniter
Algunos de los puntos más interesantes sobre este framework, sobre todo en comparación con otros productos similares, son los siguientes:
Versatilidad: Quizás la característica principal de CodeIgniter, en comparación con otros frameworks PHP. CodeIgniter es capaz de trabajar la mayoría de los entornos o servidores, incluso en sistemas de alojamiento compartido, donde sólo tenemos un acceso por FTP para enviar los archivos al servidor y donde no tenemos acceso a su configuración.

Compatibilidad: CodeIgniter, al menos en el momento de escribir este artículo de desarrolloweb.com, es compatible con la versión PHP 4, lo que hace que se pueda utilizar en cualquier servidor, incluso en algunos antiguos. Por supuesto, funciona correctamente también en PHP 5.

Facilidad de instalación: No es necesario más que una cuenta de FTP para subir CodeIgniter al servidor y su configuración se realiza con apenas la edición de un archivo, donde debemos escribir cosas como el acceso a la base de datos. Durante la configuración no necesitaremos acceso a herramientas como la línea de comandos, que no suelen estar disponibles en todos los alojamientos.

Flexibilidad: CodeIgniter es bastante menos rígido que otros frameworks. Define una manera de trabajar específica, pero en muchos de los casos podemos seguirla o no y sus reglas de codificación muchas veces nos las podemos saltar para trabajar como más a gusto encontremos. Algunos módulos como el uso de plantillas son totalmente opcionales. Esto ayuda muchas veces también a que la curva de aprendizaje sea más sencilla al principio.

Ligereza: El núcleo de CodeIgniter es bastante ligero, lo que permite que el servidor no se sobrecargue interpretando o ejecutando grandes porciones de código. La mayoría de los módulos o clases que ofrece se pueden cargar de manera opcional, sólo cuando se van a utilizar realmente.

Documentación tutorializada: La documentación de CodeIgniter es fácil de seguir y de asimilar, porque está escrita en modo de tutorial. Esto no facilita mucho la referencia rápida, cuando ya sabemos acerca del framework y queremos consultar sobre una función o un método en concreto, pero para iniciarnos sin duda se agradece mucho.

Sin duda, lo más destacable de CodeIgniter es su accesibilidad, ya que podemos utilizarlo en la mayor gama de entornos. Esta es la razón por la que en DesarrolloWeb.com hemos elegido este framework PHP para comenzar un manual que explicará cómo utilizarlo para desarrollar nuestras propias aplicaciones web. En siguientes artículos iremos contando diferentes aspectos de este framework y lo utilizaremos para crear una primera aplicación web.

Cómo procesar código HTML desde aplicaciones PHP, para eliminar posibles ataques XSS y restringir las etiquetas utilizadas, con la librería HTML Purif

Esta librería permite eliminar código malicioso (XSS) y validar las etiquetas HTML que queramos definir como permitidas. También valida el código HTML con el estándar que nosotros deseemos y realiza las modificaciones necesarias para "purificarlo".
HTML Purifier es gratuito y de código libre. Se trata además de un sistema altamente personalizable que puede abarcar varios tipos de usos dentro de un sitio web. Se utiliza generalmente para validar los campos que se reciben desde editores WYSIWYG o simplemente para validar el código que se muestra en una página web.

Toda la documentación, archivos de descarga y ejemplos los puedes encontrar en http://htmlpurifier.org . El sitio web de la librería está bastante completo y tiene varios textos con documentación y demos que sirven para hacerse una idea de las posibilidades y sobre cómo programar el script PHP para configurar la librería de filtrado de HTML.

Existen otras librerías similares para filtrar, validar y depurar HTML, con distintas funcionalidades y complejidades. Alguna de ellas ya las habíamos comentado en DesarrolloWeb.com, como la librería Kses, que es bastante más sencilla en sus posibilidades, pero también un poco más fácil de utilizar. HTML Purifier es quizás el filtro de HTML más completo y para comprobarlo podemos acceder a una comparativa de distintos filtros que aparece en la propia página del HTML Purifier. Claro que es una comparativa un poco subjetiva, que intenta ensalzar las posibilidades de su propia librería, pero aun así merece la pena echarle un vistazo para y conocer el verdadero alcance de HTML Purifier.

Instalación de HTML Purifier
Primero convendría saber que la última versión de HTML Purifier sólo es compatible con PHP 5. Es el único requisito importante de conocer antes de decantarnos por esta solición.
Hay dos versiones para descargar esta librería desde http://htmlpurifier.org/download. La única diferencia entre la versión completa y la "Lite" es que se ha eliminado la documentación, los archivos de prueba, perfiles y archivos de mantenimiento, es decir, sólo contiene la carpeta con la librería.

Una vez descargado, descomprimimos el archivo y lo guardamos en el servidor. Después hay que darle permisos de escritura a la carpeta HTMLPurifier/DefinitionCache/Serializer. Suponiendo que hemos descomprimido el archivo en la carpeta raíz del servidor, hay que incluir unas líneas de código en el archivo donde vamos a utilizar esta librería:


Si tu sitio web trabaja con UTF-8 y XHTML Transitional utiliza el siguiente código:
require_once '/htmlpurifier/library/HTMLPurifier.auto.php';

$purifier = new HTMLPurifier();
$clean_html = $purifier->purify($dirty_html);
?>
Si utilizas un juego de caracteres distinto o quieres validar el código HTML conforme a otro document type, por ejemplo HTML Transitional, utiliza este otro código:
require_once '/htmlpurifier/library/HTMLPurifier.auto.php';

$config = HTMLPurifier_Config::createDefault();
$config->set('Core', 'Encoding', 'ISO-8859-1'); // Cambiar por tu juego de caracteres
$config->set('HTML', 'Doctype', 'HTML 4.01 Transitional'); // cambiar por tu doctype
$purifier = new HTMLPurifier($config);

$clean_html = $purifier->purify($dirty_html);
?>
Ejemplo de HTML Purifier
Vamos a mostrar un ejemplo utilizando algunas de las funciones de filtrado de HTML, que proporciona la librería y que permiten verificar un código HTML.
En el ejemplo partiremos de un código HTML inicial en el que contendrá una serie de etiquetas HTML, de las cuales, las que nosotros no indiquemos como válidas, las eliminará de nuestro código.

En el siguiente código tenemos una cadena de caracteres con una serie de etiquetas HTML. Lo utilizaremos para configurar HTML Purifier de modo que elimine las etiquetas no permitidas.

$miHTML='Prueba de HTML Purifier de www.desarrolloweb.com';

Primero configuramos incluimos la librería y la configuramos con la codificación que necesitemos.

$config = HTMLPurifier_Config::createDefault();
$config->set('Core.Encoding', 'ISO-8859-1');

Indicaremos, de manera opcional, que automáticamente ponga saltos de linea al código que queremos verificar. Esto hace que los saltos de línea dobles se cambien por etiquetas P. Los saltos de línea los deja tal cual. Y por supuesto, para que funcione tenemos que incluir a la etiqueta P entre las permitidas. Luego veremos cómo hacerlo.

$config->set('AutoFormat.AutoParagraph', true);

Después indicaremos las etiquetas y atributos permitidos para nuestro código HTML. En nuestro ejemplo, vamos a permitir las etiquetas “b”, “p”, “div” y “a”, de las cuales de la etiqueta “p” sólo admitirá el atributo “align” y de la etiqueta “a” admitirá los atributos “target” y “href”. El resto de las etiquetas permitidas admiten todos sus atributos correspondientes.

$config->set('HTML.Allowed', 'b,p[align],div,a[target|href]');

Si queremos que en una etiqueta en concreto sólo se pueda admitir un cierto valor de un atributo, incluiremos el siguiente código indicando el archivo desde donde se está ejecutando este código. Hay que crear una nueva directiva de HTMLDefinicion con un identificador único de la definición.

$config->set('HTML.DefinitionID', '1');

Y hay que crear también un identificador exclusivo para la definición anterior, que sirve para manejar la caché de manera inteligente y a la vez vaciarla.

$config->set('HTML.DefinitionRev', 1);
$def = $config->getHTMLDefinition(true);

Aquí hemos indicado que para la etiqueta “a” sólo admita el atributo “target” con el valor “_blank”. Dentro del array se pueden indicar todos los valores que queramos que pueda tomar el atributo de la etiqueta en concreto.

$def->addAttribute('a', 'target', new HTMLPurifier_AttrDef_Enum(
array('_blank')
));

Y ya sólo queda purificar nuestro código HTML.

$purifier = new HTMLPurifier($config);
$html_purificado = $purifier->purify($miHTML);

Puedes ver mas funcionalidades de esta librería en la documentación de HTML purifier http://htmlpurifier.org/docs

Para terminar vamos a mostrar el código del ejemplo completo.

$miHTML='Prueba de HTML Purifier de www.desarrolloweb.com';

$config = HTMLPurifier_Config::createDefault();
$config->set('Core.Encoding', 'ISO-8859-1');
$config->set('AutoFormat.AutoParagraph', true);
$config->set('HTML.Allowed', 'b,p[align],div,a[target|href]');
$config->set('HTML.DefinitionID', '1');
$config->set('HTML.DefinitionRev', '1');
$def = $config->getHTMLDefinition(true);
$def->addAttribute('a', 'target', new HTMLPurifier_AttrDef_Enum(
array('_blank')
));

$purifier = new HTMLPurifier($config);
$html_purificado = $purifier->purify($miHTML);