whenpenguinsattack.com

Tuesday, February 28, 2006

using pear cache_lite for high performance


By Justin Silverton

What is cache lite?

Cache_lite is a php/pear caching module that is designed for high traffic sites. It is different than most caching systems because it has a built-in locking mechanism that will prevent cache corruption that can sometimes occur when there are a large amount of concurrent users trying to read and write to your cached data.

How to use it

Here is a simple example on how to cache your data:

//assign an id to the cache object
$cacheid = '589';

$cache_options = array(
'cacheDir' => '/cachetmp', //this is the temp directory of the cache files
'lifeTime => 5000 //time, in seconds, of how long the cache will be valid
);


// Create a Cache_Lite object
$Cache_object = new Cache_Lite($cache_options);

// Test if thereis a valide cache for this id
if ($data = $Cache_object->get($cacheid)) {

// data is in our cache, access it through $data

} else { // Not found in cache, it needs to be added

$Cache_Lite-&gtsave($data);

}

?>

Performance tip: Don't include every package your page needs. Only
load the modules you need when the page is not in the cache.

Example:

<?php
require_once("Cache/Lite.php");
// (...)
$cache_object = new Cache_Lite();
if ($data = $cache_object->get($cache_id)) { // cache hit !
echo($data);
} else { // page has to be constructed
require_once("...")
require_once("...")
// (...)
$Cache_object->save($data);
}
?>

Downloading

Cache_lite is part of the free pear package, which is a large repository of modules available Here

Sunday, February 26, 2006

using paypal mass payment


By Justin Silverton

Introduction

Mass Payment allows anyone with a Premier or Business account to send multiple payments instantly—saving time, money and the hassle of having to individually send funds to every payment recipient.

Click the links on the left of this page to learn more about Mass Payment.

Mass Payment can be used for such things as:
  • Affiliate commissions
  • Customer rebates
  • Pay-to-surf rewards
  • Employee benefits
  • Lottery prizes
  • Survey incentives
File Format

You must create a tab-delimited file containing your recipients’ information to send a Mass Payment file. A tab-delimited file can be generated from most spreadsheet applications, such as Excel.

Column 1: recipients’ email addresses.
Column 2: the payment amounts for each recipient.
Column 3: the three-letter currency code for the currency of the payment (only one currency type is allowed for each Mass Payment file):

  • EUR for Euro
  • USD for U.S. Dollar
  • GBP for Pound Sterling
  • CAD for Canadian Dollar
  • JPY for Yen
  • AUD for Australian Dollar
Column 4 (optional): a unique identifier for each customer for easier overall record-keeping. The unique identifier must be equal to or less than 30 characters, and must not contain any spaces. Examples of name format: Pitel, John; John_Pitel; JohnPitel.

Column 5 (optional): customized notes about each customer.

How to export a table in comma delimited text format (using mysql):

Here is an example on how to export your mysql tables in the above format:

select field1,field2,'USD' from paypal_payments into outfile '$export_long_name' fields terminated by '\t' lines terminated by '\r\n'";

in mysql, when you are selecting data from a table, if you add a string in quotes 'string', it will add on that string in a separate column for each record returned.

File downloads in PHP

By Justin Silverton

This is a simple code snippet. It will allow you to force the web-browser that is currently viewing your script to come up with a file-download box (and the a file on your system can be downloaded).

Here is the code:

//so only the data from the headers is sent
ob_start();
//dispable caching
header ("Cache-Control: must-revalidate, pre-check=0, post-check=0");
header ("Content-Type: application/binary");
header ("Content-Length: " . filesize($export_long_name));
header ("Content-Disposition: attachment; filename=yourfile.ext");
readfile($export_long_name);

A list of of mime types can be found Here

The history of Apple


By Justin Silverton

Here is an interesting article I found on the history of apple.

Before Apple

John Sculley's childhood was the antithesis of Steve Jobs'. His father was strict and had impossibly high standards for his son.

Sculley attended St. Marks, an exclusive private boarding school made up of blue blooded Northeasterners. While there, he succeeded socially and academically, becoming the captain of the soccer team and earning impeccable grades at the same time.
Being sociable was not easy for Sculley, however, and he feared it. He had to train himself to be sociable. He says in his autobiography, Odyssey, that he decided that he would overcome his stutter and become an inspiring speaker, and he did.

To learn appropriate body language during speaking, he went to movie after movie, studying the actors' poses, committing them all to memory.

It worked. Throughout his career, his speaking skill would be commended, though it was not perfect. He was nervous in crowds and recoiled at being touched. He often sat by himself in the Apple cafeteria eating his peanut butter sandwich until some merciful employee joined him.
After St. Marks, Sculley studied at Wharton, and he eventually married the daughter of the chairman of PepsiCo, Don Kendall. The two soon divorced, though Sculley maintained a close relationship with his former father-in-law, who gave him a job managing PepsiCo's struggling Brazilian snack division, which soon became the most profitable division in the southern hemisphere...

The rest can be found Here

Thursday, February 23, 2006

Bart's preinstalled Environment (PE)


What is Bart's PE?

PE Builder is not a Microsoft product and does not create Microsoft Windows Preinstallation Environment ("Windows PE"). Using PE Builder does not grant you a license to Microsoft Windows PE or to use the Windows XP or Server 2003 binaries in a manner other than stated in the End-User License Agreement included in your version of Microsoft Windows XP or Windows Server 2003. Microsoft has not reviewed or tested PE Builder and does not endorse its use.Please do not contact Microsoft for support on the preinstallation environment that has been created by PE Builder!Microsoft does not provide support for PE Builder or for the preinstallation environment created by PE Builder.The PE Builder program (pebuilder.exe) runs on Windows 2000/XP/2003/BartPE. It does not run on Windows NT4/ME/9x.To avoid any confusion, the bootable CD generated by PE Builder should be called by its nickname "BartPE"!

Differences between BartPE and Windows PE

  • Target - Microsoft sees Windows PE as an installation platform. Bart sees Windows PE as the next generation rescue platform.
  • Start-menu - Bart's builder gives you a simple, dynamic and powerful start-menu (Nu2Menu, see screenshots). Microsoft's builder does not give you a start-menu, it uses a command prompt.
  • Build from - Bart's builder can also build from Windows XP Home Edition or from a preinstalled Windows XP version (without CD).
  • Plugins - With PE Builder you can easily add applications, drivers or tools using plugins. This makes PE Builder extremely powerful. The end user can even combine plugins from different software vendors into one CD image.
  • Network support - PE Builder includes its own network support tools (bartpe/penetcfg) to start TCP/IP and Microsoft Client. The TCP/IP settings like: dynamic/static ip-address, subnet-mask, default gateway, dns-servers computer-name, workgroup can be changed on-the-fly. You can create pre-defined profiles, that you can select. Microsoft Windows PE only supports DHCP or fixed settings using winbom.ini.
    Also there is a plugin (NwDskPe) created by Erwin Veermans that loads the Netware Client on BartPE (IP/IPX).
  • Fileshare - BartPE can start File Sharing support so you can connect to the system through a share.
  • VNC - Because of the File Sharing support you can also run UltraVNC.
  • Dos support - Bart's builder has a plugin called "dospe".
  • License - Microsoft Windows PE is only for Enterprise/OEM customers (see previous), BartPE is for everybody!
  • 64-Bit - Bart's builder does not support Windows 64-bit editions.

Requirements

The files from your Windows Installation CD-Rom.Supported Windows versions are:
Windows XP Home Edition (must be slip streamed with Service Pack 1 or higher)
Windows XP Professional (must be slip streamed with Service Pack 1 or higher)
Windows Server 2003, Web Edition
Windows Server 2003, Standard Edition
Windows Server 2003, Enterprise Edition
PE Builder runs on Windows 2000/XP/2003/BartPE systems.
CD/DVD writer if you want to creat a bootable CD/DVD.

The Download is available Here

Another great project based on barts PE called the Ultimate Boot CD can be found Here

using vmware for development


By Justin Silverton

As a programmer, I often times need to develop or test my work on multiple operating systems such as linux, freebsd, and various versions of windows. Rather than keep separate boxes around for each operating system, I run windows 2003 standard edition as my base OS and a vmware session for each separate OS.

My current hardware is : amd64 with an 80 gig harddrive/1 gig of Ram. Any OS that I have tried runs very fast, with almost no noticable difference from a regular installation.

One quick tip: install the Vmware tools. This will improve performance significantly.

One of the most interesting features of Vmware is the fact that it has bridged networking. This allows your sessions to each have their own separate IP addresses on your network. This can really come in handy if you want to test out a new server on linux or an apache installation.

Beyond development, vmware can also be used to surf the Internet without having to worry about your computer getting infected with spyware. This may be overkill, but it just might save you from having to re-install your entire OS because of an insecure browser.

Vmware has a free verson available for both windows and linux. It is in beta, but it still works very well for most people's needs.

Both can be downloaded Here

Wednesday, February 22, 2006

using sql relay


By Justin Silverton

What is SQL relay?

SQL Relay is a persistent database connection pooling, proxying and load balancing system for Unix and Linux supporting ODBC, Oracle, MySQL, mSQL, PostgreSQL, Sybase, MS SQL Server, IBM DB2, Interbase, SQLite and MS Access (minimally) with APIs for C, C++, Perl, Perl-DBD, Python, Python-DB, Zope, PHP, Ruby, Ruby-DBD, Java and TCL, drop-in replacement libraries for MySQL and PostgreSQL clients, command line clients, a GUI configuration tool and extensive documentation. The APIs support advanced database operations such as bind variables, multi-row fetches, client-side result set caching and suspended transactions. It is ideal for speeding up database-driven web-based applications, accessing databases from unsupported platforms, migrating between databases, distributing access to replicated databases and throttling database access.

SQL Relay is ideal for:

  • speeding up database-driven web-based applications
  • enhancing the scalability of database-driven web-based applications
  • distributing access to replicated databases
  • throttling database access
  • accessing databases from unsupported platforms
  • migrating applications from one database to another

SQL Relay supports the following database backends:

  • Oracle
  • MySQL
  • mSQL
  • PostgreSQL
  • Sybase
  • MS SQL Server
  • IBM DB2
  • Interbase
  • Sybase
  • SQLite
  • ODBC
  • MS Access

The SQL Relay client API's support advanced database operations such as bind variables, multi-row fetches, client-side result set caching and suspended transactions. SQL Relay has native client API's for the following languages:

  • C
  • C++
  • Perl
  • Python
  • PHP
  • Ruby
  • Java
  • TCL
  • Zope
How does SQL Relay work?

SQL Relay's connection daemons log into and maintain sessions with databases. These connection daemons advertise themselves with a listener daemon which listens on an inet and/or unix port for client connections. When a client connects to the listener, if a connection daemon is available, the listener hands off the client to that connection. If no connection daemon is available, the client must wait in queue until one is. Once a client is handed off to a connection daemon, the client communicates to the database through the session maintained by that daemon.

How can SQL Relay improve the efficiency of my website?

Here are some examples of how SQL Relay can improve the efficiency of your web site.

Let's say you're running CGI's againt a transactional database such as PostgreSQL, MS SQL Server or Oracle. CGI's have to log into and out of the database each time they run. If you use SQL Relay to maintain persistent connections to the database and just log into and out of SQL Relay, you can reduce the amount of time wasted establishing database connections and handle more CGI requests per-second. This is both because the time-cost of connecting to SQL Relay is smaller than the time-cost of connecting to a transactional database, and because the SQL Relay client library is smaller than most database client libraries, resulting in a more lightweight CGI.

Let's say you're using Apache, PHP and Oracle and you determine by doing all sorts of analysis that you need to keep 30 Apache processes running to provide adequate response. Since most of your site isn't database-driven, on average, no more than 5 PHP's actually access the database simultaneously. Currently, you're using persistent connections to defeat the time-cost of logging into Oracle, but you have to maintain 30 connections (1 per web server process) which takes up a lot of memory on both the web server and database server and you really only need 5 connections. By using SQL Relay you can reduce the number of Oracle connections to the 5 that you need, continue to run 30 Apache processes and reclaim the wasted memory on both machines.

Many websites run a combination of PHP's and Perl modules. Perl modules can use Apache::DBI and PHP's have a persistent database connection system, but a PHP cannot use an Apache::DBI connection and a Perl module cannot use a PHP persistent connection. Thus in order to make sure that there are enough database connections for each platform, many more web-server processes have to be run, perhaps twice as many. If the PHP's and Perl modules used SQL Relay instead, they could share databse connections and reduce the number of web-server processes and database connections.

SQL Relay makes it easy to distribute load over replicated servers. A common scaling solution when using MySQL or PostgreSQL in a read-only web environment is to run several web servers with a dedicated database server for each web server or group of web servers and update all the databases simultaneously at scheduled intervals. This usually works pretty well, but sometimes database or web servers get runs of heavy load while others are idle. In other cases, an uneven number of machines is required. For example, your application may need 3 web servers but only 2 database servers or vice-versa. People usually just by 3 of each, wasting money. Moreover, in most cases, the servers have to be equivalently powerful machines. You can't usually just add another cheap machine that you have lying around into the pool. SQL Relay can connect to multiple, replicated or clustered database servers, providing web-based applications access to whichever server isn't busy. SQL Relay can also be configured to maintain more connections to more powerful machines and fewer connections to less powerful machines, enabling unevenly matched machines to be used in the same database pool. Collectively, these features allow you to save money by using only the exact number of servers that you need and by enabling you to use spare hardware in your database pools.

Where can I get it?

SQL relay can be downloaded Here


why use php5?

By Justin Silverton

New Object-orientated features

In the previous versions of PHP, objects and classes were supported, but only on a limited basis. Missing was the ability to de-reference objects that are returned from a method and implicit object cloning resulted in unexpected behavior.

The following are new features within php5

A) Public, private, protected class modifiers

These modifiers may be used on both properties and methods, and restrict access.

B) Interfaces and abstract classes and methods.

C) Object cloning

The scripting engine never automatically clones objects in PHP 5, whether they are assigned, passed by-value, or returned by-value. If you do need to clone an object, then you can use the following syntax: "clone $newobject" or a method called __clone() can be implemented, which will be called after an object's properties has been cloned.


D) Design Patterns


Supported in PHP 4, but now has new and improved features such as static properties and methods, private/public/protected modifiers, and interfaces.

E) XML and Soap

The soap protocol is becoming increasingly popular for communicating with web services. Many companies are implementing it to allow for easy access to data.

Improved mysql functionality

A new library, called mysqli, offers the following improvements over the old library:

A) SSL connectivity
B) prepared statements
C) Bound Input and Out parameters
D) Object orientated interface

Exception Handling

Exceptions allow you to have a greater degree of control over error handling, by separating the program logic. You no longer have to check the return value from a function.


Complete function list can be found here

Monday, February 20, 2006

another article on oracle/mysql

"In November, I looked at Oracle's purchase of InnoDB, as well as their release of Oracle Express, and the effect on MySQL. In short, I concluded that the positives for Oracle were clear, but that MySQL must be feeling outmaneuvered. Since InnoDB, with its full transactional capability, has become an integral part of their product offering, I suggested that both BerkleyDB (their first transactional storage engine, but which has never got beyond so-called gamma status) and MaxDB (what was SAPDB, which is a fully-featured database but does not yet integrate well with MySQL's other products) had both become critically important.
Shortly after Oracle purchased InnoDB, MySQL vice-president Richard Mason acknowledged that MySQL were "evaluating options to replace that functionality in some way," but that they were "not at the point yet where we can go public with what that plan is but we will be shortly."
However, since then Oracle has upped the ante even more. On February 14th, Oracle purchased Sleepycat Software, who provides MySQL with the Berkeley DB transactional storage engine. Furthermore, in the last few days, rumors have been flying that Oracle also intends to purchase both Zend ('the PHP Company'), as well as JBoss. I believe this is another smart series of moves by Oracle that can only benefit them......"


The rest can be found Here

Sunday, February 19, 2006

Oracle and open source

By Justin Silverton

In the past year or so, Oracle has recently started purchasing/bidding on open source companies/products:

Oracle buys sleepycat software

excerpt: "Sleepycat's Berkeley DB is embedded in several well-known open source products, including the Linux and BSD Unix operating systems, Apache Web server, OpenLDAP directory and OpenOffice productivity suite, Oracle said Tuesday"

Oracle buys innobase

excerpt: "Innobase is the developer of discrete transactional database technology, InnoDB, that is distributed under an open source license. "Oracle has long been a supporter of open source software such as Linux and Apache," said Charles Rozwat, Oracle's Executive Vice President in charge of Database and Middleware Technology. "Innobase is an innovative small company that develops open source database technology. Oracle intends to continue developing the InnoDB technology and expand our commitment to open source software. Oracle has already developed and contributed an open source clustered file system to Linux. We expect to make additional contributions in the future."

InnoDB is not a standalone database product: it is distributed as a part of the MySQL database. InnoDB's contractual relationship with MySQL comes up for renewal next year. Oracle fully expects to negotiate an extension of that relationship."


Oracle bids on mysql

excerpt: "MySQL, based in Sweden and Cupertino, Calif., announced in January that it's been profitable for two quarters. But it's not turning down outside money. MySQL announced Monday it raised $18.5 million in a third round of funding from Institutional Venture Partners, Intel Capital, Red Hat, SAP Ventures and Sumitomo's Presidio STX investment subsidiary.

Oracle's financial moves, however, are orders of magnitude grander. Its major buying spree resulted in the acquisitions of Siebel Systems for $5.8 billion and PeopleSoft for $10.3 billion."

What does this mean for open source?

Open source is starting to become a real threat to the commercial application companies of the world. Applications such as apache, mysql, postgres, and linux are gaining momentum and are becoming better and than than their commerical counterparts.

How can a company defend against the power of the community? The greatest strength of open source is the fact that it can't be bought or sold as a whole. Even if a new, closed source and proprietary version comes out of a project, the community can still continue developing the open sourced version.

a representitive from Oracle stated the following in a press release :

"innoDB is not a standalone database product: it is distributed as a part of the MySQL database. InnoDB's contractual relationship with MySQL comes up for renewal next year. Oracle fully expects to negotiate an extension of that relationship."

Oracle is a business with their stock holders as their main objective. Purchasing innobase, which is an integral part of the mysql database system, is the first step in taking it over. It seems okay right now, but if they start losing martketshare, there is no telling what they might do.

Another weapon large companies have against OSS is money and resources. This means they have the ability to hire the top developers of a project and basically take it off the map for awhile as a competitor.


recently, Microsoft did something like this and it backfired

using PHP in large websites - redone

by Justin Silverton

This was originally an article by Aaron Crane, but because of overwhelming amount of inaacurate and outdated information, I have decided to write a new and up-to-date article.


The following methods can help improve scalability with php applications.


1) object code caching

Each time a request comes to your server for a php script, it has to go through the compiler and then execute the object code. If this is cached, the 1st step is skipped and you end up with a faster and more responsive script.

There are many object code caching packages available on the Internet (some free, some commercial):


A) Ioncubehttp://www.ioncube.com/
B) Zend Encoderhttp://www.zend.com/products/zend_safeguard
C) Turckl MMCachehttp://freshmeat.net/projects/turck-mmcache/



2) Template systems

Template systems provide a different type of caching. Content caching. Template systems work well in a situation where there is static data on one or many of your pages that doesn't have to be reloaded. Caching systems also provide a separation of code and html, which will not only improve completion time of the overall project, but make it easier for future improvments. Most template systems for php are available for free:


A) Smarty Templateshttp://smarty.php.net/
B) Pear Templateshttp://pear.php.net/package/html_template_it/redirected
C) PHP savanthttp://phpsavant.com/yawiki/

3) Distributed object caching systems

The most widely used system of this type is memcached (http://www.danga.com/memcached/).

This type of system makes your overall site faster by caching the majority of your database data into a large memory pool.

an interesting excerpt from their site:

"Danga Interactive developed memcached to enhance the speed of LiveJournal.com, a site which was already doing 20 million+ dynamic page views per day for 1 million users with a bunch of webservers and a bunch of database servers. memcached dropped the database load to almost nothing, yielding faster page load times for users, better resource utilization, and faster access to the databases on a memcache miss."

4) PHP variables that can be set

variables_order = 'GPC'
register_argc_argv = 'Off'
register_globals = 'Off' (this is a good idea to keep off for security purposes as well)
always_populate_raw_post_data = 'Off'
magic_quotes_gpc = 'Off'

Disable Error Logging. This is a good idea to keep on when you are developing your scripts, but it has been known to decrease overall performance.

Use IP address to access your database. Although this is sometimes not possible, you will get a slight boost in lookup speed if the IP address is used to access your database rather than its hostname.

5) Output Compression

Almost all browsers these days support something called gzip compression. Gzip compression can decrease the overall size of your output by up to 80%, but with a tradeoff: cpu usage will go up by around 10%. The benefit of using this compression type is the fact that not only will your bandwidth be decreased, but your pages will load faster.

enabling it in php (add the following lines to php.ini):

zlib.output_compression = On
zlib.output_compression_level = (level) (where level is 1-9. Youy may want to try different values to see what is best for your system).

if you are using apache, you can also enable the mod_gzip module. It is highly configurable, with the ability to modify output based on MIME types, files, or browser settings.

6) Other things that may help

when using a database, only retrieve the data that you are actually going to use. This may sound like a no-brainer, but I have often times worked on projects where the original programmer used (select * from mytable) when they could have used (select fieldIneed from mytable).

index database tables whenever possible

Learn more about this Here

specific language tricks

An interesting blog article I found mentions many interesting tricks that can be used: http://ilia.ws/archives/12-PHP-Optimization-Tricks.html

an article on zend.com about measuring performance: http://www.zend.com/zend/trick/trick-optimizing-php.php

Monday, February 13, 2006

Using the iis 6 ftp service


By Justin Silverton

Install Internet Information Services and the FTP Service

Because FTP depends on Microsoft Internet Information Services (IIS), IIS and the FTP Service must be installed on the computer. To install IIS and the FTP Service, follow these steps.

NOTE: In Windows Server 2003, the FTP Service is not installed by default when you install IIS. If you already installed IIS on the computer, you must use the Add or Remove Programs tool in Control Panel to install the FTP Service.

1. Click Start, point to Control Panel, and then click Add or Remove Programs.
2. Click Add/Remove Windows Components.
3. In the Components list, click Application Server, click Internet Information Services (IIS) (but do not select or clear the check box), and then click Details.
4. Click to select the following check boxes (if they are not already selected):
Common Files
File Transfer Protocol (FTP) Service
Internet Information Services Manager
5. Click to select the check boxes next to any other IIS-related service or subcomponent that you want to install, and then click OK.
6. Click Next.
7. When you are prompted, insert the Windows Server 2003 CD-ROM into the computer's CD-ROM or DVD-ROM drive or provide a path to the location of the files, and then click OK.
8. Click Finish.
IIS and the FTP service are now installed. You must configure the FTP Service before you can use it.

Configure The FTP Service

To configure the FTP Service to allow only anonymous connections, follow these steps: 1. Start Internet Information Services Manager or open the IIS snap-in.
2. Expand Server_name, where Server_name is the name of the server.
3. Expand FTP Sites
4. Right-click Default FTP Site, and then click Properties.
5. Click the Security Accounts tab.
6. Click to select the Allow Anonymous Connections check box (if it is not already selected), and then click to select the Allow only anonymous connections check box.

When you click to select the Allow only anonymous connections check box, you configure the FTP Service to allow only anonymous connections. Users cannot log on by using user names and passwords.
7. Click the Home Directory tab.
8. Click to select the Read and Log visits check boxes (if they are not already selected), and then click to clear the Write check box (if it is not already cleared).
9. Click OK.
10. Quit Internet Information Services Manager or close the IIS snap-in.
The FTP server is now configured to accept incoming FTP requests. Copy or move the files that you want to make available to the FTP publishing folder for access. The default folder is drive:\Inetpub\Ftproot, where drive is the drive on which IIS is installed.

adding a virtual directory

This is probably one of the most confusing issues with the IIS ftp service. To create a virtual directory, do the following:

1) right click your new ftp server that you created from above (in iis manager) and go to new->virtual directory.
2) it will ask you for the alias (how people will access this directory and the location (which is the actual physical directory on your harddrive).
3) after this is created, you may try to login to your ftp server and see if your directories are listed. They won't be there.
4) Most FTP server use the actual file structure of your system to determine what directories to display to the user.

To allow your virtual directories to be seen, go into the home directory of your ftp site and create an empty directory with same name as your virtual one (the alias).

This works virtual directories take precidence over file-system directories.

using php and smarty templates

By Justin Silverton

Why use smarty templates?

One of Smartys primary design goals is to facilitate the separation of application code from presentation. Typically, the application code contains the business logic of your application, written and maintained in PHP code. This code is maintained by programmers. The presentation is the way your content is presented to the end user, which is written and maintained in template files. The templates are maintained by template designers.

At its most basic function, the application code collects content, assigns it to the template engine and displays it. The content might be something like the headline, tagline, author and body of a newspaper article. The application code has no concern how this content will be presented in the template. The template designer is responsible for the presentation. They edit the template files, adding markup and bringing it to completion. This typically involves things like HTML tags, cascading style sheets and other tools provided by the template engine.

This paradigm serves several purposes:

*) Designers can't break application code. They can mess with the templates all they want, but the code stays intact. The code will be tighter, more secure and easier to maintain.

*) Errors in the templates are confined to the Smartys error handling routines, making them as simple and intuitive as possible for the designer.

*) With presentation on its own layer, designers can modify or completely redesign it from scratch, all without intervention from the programmer.

*) Programmers aren't messing with templates. They can go about maintaining the application code, changing the way content is acquired, making new business rules, etc. without disturbing the presentation layer.

*) Templates are a close representation of what the final output will be, which is an intuitive approach. Designers don't care how the content got to the template. If you have extraneous data in the template such as an SQL statement, this opens the risk of breaking application code by accidental deletion or alteration by the designer.

*) You are not opening your server to the execution of arbitrary PHP code. Smarty has many security features built in so designers won't breach security, whether intentional or accidental. They can only do what they are confined to in the templates.

Although application code is separated from presentation, this does not necessarily mean that logic is separated. The application code obviously has logic, but the templates may have logic based on the condition that it is for presentation only. For example, if the designer wants to alternate table row colors or upper-case some assigned content, they can. This is presentation logic, something the programmer should not be concerned with. How often have you had some presentation displayed in a single column and then you wanted it in two or three columns, so the application code needs adjusting to accomodate this? A better approach is to assign the content in one single array and let the template handle the presentation. This will simplify your application and keep your templates flexible. Smarty supplies the tools to handle this kind of situation.

Getting Started with smarty

The first step is to download the smarty template engine Here

1. copy the following to a new file named "smartywrapper.php

// require the Smarty class
require_once('Smarty.class.php');

// extend the Smarty class
class smartywrapper extends Smarty {

//this will only work with php 5.X
function function __construct() {

// create the Smarty object
$this->Smarty();

// make sure these folders exist and the permissions are set accordingly
$this->template_dir = '/www/example.com/webapp/template/';
$this->compile_dir = '/www/example.com/webapp/compile/';
$this->config_dir = '/www/example.com/webapp/config/';
$this->cache_dir = '/www/example.com/webapp/cache/';
}
}

2. copy the following to a file named "smartytest.php"

// require the new wrapper class we just created from above
require_once('smartywrapper.php');

// create the Smarty_WebApp object
$smarty = new smartywrapper();

// assign a variable, first parameter is the var name, second is the value
$smarty->assign('test_var_1','this is a test');

//display the template file (all html can now be placed here instead of in your php files)
$smarty->display('my_template.tpl');

create a file called my_template.tpl and place it in the directory in $this->template_dir = '/www/example.com/webapp/template/'; from above:

This is a test page from smarty, my variable is: {$test_var_1}

launch smartytest.php from you webbrowser and if it is successful, you should see the following

output:

This is a test page from smarty, my variable is: this is a test

Conclusion

Smarty templates can not only be used to increase the overall speed of your php scripts through caching (more about caching can be found Here), but make it easier to develop large-scale applications through the separation of HTML code and php script.

php 5.0 and iis - authentication issues

by Justin Silverton

I installed php 5.0/iis 6 (the isapi dll manually) today on one of my new development servers, following the directions from the install.txt (and using the steps that I wrote about in a previous article). After I created a test php file and attempted to launch it from a web-browser, I was shown a username and password box.



if you are getting the message box above, it is most likely a permission problem.

The following can be done to fix it:

1) make sure the path has c:\php (where your php is installed)
-this can be done by going to start->settings->control panel->system, then clicking on the advanced tab, and finally clicking on "environment variables". The path variable is located within the second box on the page.

2) the following files need to have their permissions set to read by the user account IIS uses to launch files (typically IUSR_(your server name):

php.ini
php5ts.dll

Saturday, February 11, 2006

Is the End of Microsoft Near?

By Justin Silverton

Microft has had a pretty good run. They have gone from a small development shop in the late 1970s and early 80s to the largest software company in the world.

One of the reasons the windows operating system can now be seen on 80% of the world's computers is because of developer support. Any programmer from novice to expert has the ability to write an application and release it on the windows platform.

Recently, an article appeared over at boing boing: (http://www.boingboing.net/2006/01/30/msft_our_drm_licensi.html)

Here is an excerpt:

"Microsoft's DRM requires that device makers pay Microsoft a license fee for each device that plays back video encoded with its system. it also requires every such vendor to submit to a standardized, non-negotiable license agreement that spells out how the player must be implemented. This contract contains numerous items that limit the sort of business you're allowed to pursue, notably that you may not implement a Microsoft player in open source software.

The bombshell was Amir's explanation of the reason that his employer charges fees to license its DRM. According to Amir, the fee is not intended to recoup the expenses Microsoft incurred in developing their DRM, or to turn a profit. The intention is to reduce the number of licensors to a manageable level, to lock out "hobbyists" and other entities that Microsoft doesn't want to have to trouble itself with."

This is a step in the wrong direction and it really makes me wonder why in their right mind they would even consider doing this.

I guess it shouldn't come as a surprise. With Microsoft's track record as a convicted monopolist and their blatent strongarm tactics in the hardware and software industry, another step towards world domination of total domination is only inevitable.

what alternatives do we have?

1) Linux

I started using linux back in 96, when there was no such thing as kde (I believe KDE was just starting out as a project) or gnome and most people you ask would have no idea what linux even is. It has come a long way in 10 years, but I don't think it is ready to take the place of windows yet.

Don't get me wrong. Linux is a great operating system. I wish I could throw away all of my insecure and buggy windows machines tomorrow and never look back, but it's just not possible at this point. I think one of the main reasons I'm still using microsoft products, is driver support.
This isn't the fault of the developing force behind linux, but of the sheer force of windows. Most manufacturers don't want to put research and development into writing a driver for linux. The end result is a constant battle to keep up with the many pieces of hardware that need to be supported. Many drivers are created by reverse-engineering an existing driver.

If more manufacurers started supporting linux (at least 90%) It could be a Microsoft killer.

interested in linux? find a distro Here

2) OS X


OS X could very well be the next windows killer. In the past year or so, apple announced their compatibility with OS X and the intel platform. Although in its current state, os x cannot run on an out of the box PC, what's to stop it from doing so in the future? This could all be in apple's plan.

1) release intel version of os x
2) get driver support from manufacturers and fix compatiblity issues
3) profit


an interesting link about macs booting windows XP

more info on intel mac os x

using php and imagemagick

by justin silverton

What is imagemagick and why do i need it?

image magick is a free and useful tool that can do the following:

1) Convert an image from one format to another (e.g. PNG to JPEG
2) Resize, rotate, sharpen, color reduce, or add special effects to an image
3) Create a montage of image thumbnails
4) Create a transparent image suitable for use on the Web
5) Turn a group of images into a GIF animation sequence
6) Create a composite image by combining several separate image
7) Draw shapes or text on an image
8) Decorate an image with a border or frame
9) Describe the format and characteristics of an image

Accessing it from PHP

In my experience, image magick is most likely installed here (on *nix systems) (it also may be in a different area on your system) : /usr/bin/convert

as an example of how I used it, I needed to automatically create thumbnails of images that were being uploaded through and administrative interface for a photo gallery.

exec ("/usr/local/bin/convert -geometry 480X -quality 70 $sourcepath $destpath");

?>

notes: change /usr/local/bin to the directory on your system where it is installed.

$sourcepath: source image we want to convert (including image name)

$destpath: destination image name (including image name)

command line options

-adjoin join images into a single multi-image file

-affine matrix drawing transform matrix

-antialias remove pixel-aliasing

-append append an image sequence

-average average an image sequence

-background color background color

-blur geometry blur the image

-border geometry surround image with a border of color

-bordercolor color border color

-box color color for annotation bounding box

-cache threshold megabytes of memory available to the pixel cache

-gaussian geometry gaussian blur an image

-geometry geometry perferred size or location of the image

a full list can be found by executing convert --?

Download

Don't have imagemagick on your system? download it for free Here
It's free and licensed under the GNU

Friday, February 10, 2006

life advice from steve jobs

This is a little bit old, but I still find it interesting.

This is the text of the Commencement address by Steve Jobs, CEO of Apple Computer and of Pixar Animation Studios, delivered on June 12, 2005.

I am honored to be with you today at your commencement from one of the finest universities in the world. I never graduated from college. Truth be told, this is the closest I've ever gotten to a college graduation. Today I want to tell you three stories from my life. That's it. No big deal. Just three stories.

The first story is about connecting the dots.

I dropped out of Reed College after the first 6 months, but then stayed around as a drop-in for another 18 months or so before I really quit. So why did I drop out?

It started before I was born. My biological mother was a young, unwed college graduate student, and she decided to put me up for adoption. She felt very strongly that I should be adopted by college graduates, so everything was all set for me to be adopted at birth by a lawyer and his wife. Except that when I popped out they decided at the last minute that they really wanted a girl. So my parents, who were on a waiting list, got a call in the middle of the night asking: "We have an unexpected baby boy; do you want him?" They said: "Of course." My biological mother later found out that my mother had never graduated from college and that my father had never graduated from high school. She refused to sign the final adoption papers. She only relented a few months later when my parents promised that I would someday go to college.

And 17 years later I did go to college. But I naively chose a college that was almost as expensive as Stanford, and all of my working-class parents' savings were being spent on my college tuition. After six months, I couldn't see the value in it. I had no idea what I wanted to do with my life and no idea how college was going to help me figure it out. And here I was spending all of the money my parents had saved their entire life. So I decided to drop out and trust that it would all work out OK. It was pretty scary at the time, but looking back it was one of the best decisions I ever made. The minute I dropped out I could stop taking the required classes that didn't interest me, and begin dropping in on the ones that looked interesting.

It wasn't all romantic. I didn't have a dorm room, so I slept on the floor in friends' rooms, I returned coke bottles for the 5¢ deposits to buy food with, and I would walk the 7 miles across town every Sunday night to get one good meal a week at the Hare Krishna temple. I loved it. And much of what I stumbled into by following my curiosity and intuition turned out to be priceless later on. Let me give you one example:

Reed College at that time offered perhaps the best calligraphy instruction in the country. Throughout the campus every poster, every label on every drawer, was beautifully hand calligraphed. Because I had dropped out and didn't have to take the normal classes, I decided to take a calligraphy class to learn how to do this. I learned about serif and san serif typefaces, about varying the amount of space between different letter combinations, about what makes great typography great. It was beautiful, historical, artistically subtle in a way that science can't capture, and I found it fascinating.

None of this had even a hope of any practical application in my life. But ten years later, when we were designing the first Macintosh computer, it all came back to me. And we designed it all into the Mac. It was the first computer with beautiful typography. If I had never dropped in on that single course in college, the Mac would have never had multiple typefaces or proportionally spaced fonts. And since Windows just copied the Mac, its likely that no personal computer would have them. If I had never dropped out, I would have never dropped in on this calligraphy class, and personal computers might not have the wonderful typography that they do. Of course it was impossible to connect the dots looking forward when I was in college. But it was very, very clear looking backwards ten years later.

Again, you can't connect the dots looking forward; you can only connect them looking backwards. So you have to trust that the dots will somehow connect in your future. You have to trust in something - your gut, destiny, life, karma, whatever. This approach has never let me down, and it has made all the difference in my life.

My second story is about love and loss.

I was lucky - I found what I loved to do early in life. Woz and I started Apple in my parents garage when I was 20. We worked hard, and in 10 years Apple had grown from just the two of us in a garage into a $2 billion company with over 4000 employees. We had just released our finest creation - the Macintosh - a year earlier, and I had just turned 30. And then I got fired. How can you get fired from a company you started? Well, as Apple grew we hired someone who I thought was very talented to run the company with me, and for the first year or so things went well. But then our visions of the future began to diverge and eventually we had a falling out. When we did, our Board of Directors sided with him. So at 30 I was out. And very publicly out. What had been the focus of my entire adult life was gone, and it was devastating.

I really didn't know what to do for a few months. I felt that I had let the previous generation of entrepreneurs down - that I had dropped the baton as it was being passed to me. I met with David Packard and Bob Noyce and tried to apologize for screwing up so badly. I was a very public failure, and I even thought about running away from the valley. But something slowly began to dawn on me - I still loved what I did. The turn of events at Apple had not changed that one bit. I had been rejected, but I was still in love. And so I decided to start over.

I didn't see it then, but it turned out that getting fired from Apple was the best thing that could have ever happened to me. The heaviness of being successful was replaced by the lightness of being a beginner again, less sure about everything. It freed me to enter one of the most creative periods of my life.

During the next five years, I started a company named NeXT, another company named Pixar, and fell in love with an amazing woman who would become my wife. Pixar went on to create the worlds first computer animated feature film, Toy Story, and is now the most successful animation studio in the world. In a remarkable turn of events, Apple bought NeXT, I retuned to Apple, and the technology we developed at NeXT is at the heart of Apple's current renaissance. And Laurene and I have a wonderful family together.

I'm pretty sure none of this would have happened if I hadn't been fired from Apple. It was awful tasting medicine, but I guess the patient needed it. Sometimes life hits you in the head with a brick. Don't lose faith. I'm convinced that the only thing that kept me going was that I loved what I did. You've got to find what you love. And that is as true for your work as it is for your lovers. Your work is going to fill a large part of your life, and the only way to be truly satisfied is to do what you believe is great work. And the only way to do great work is to love what you do. If you haven't found it yet, keep looking. Don't settle. As with all matters of the heart, you'll know when you find it. And, like any great relationship, it just gets better and better as the years roll on. So keep looking until you find it. Don't settle.

My third story is about death.

When I was 17, I read a quote that went something like: "If you live each day as if it was your last, someday you'll most certainly be right." It made an impression on me, and since then, for the past 33 years, I have looked in the mirror every morning and asked myself: "If today were the last day of my life, would I want to do what I am about to do today?" And whenever the answer has been "No" for too many days in a row, I know I need to change something.

Remembering that I'll be dead soon is the most important tool I've ever encountered to help me make the big choices in life. Because almost everything - all external expectations, all pride, all fear of embarrassment or failure - these things just fall away in the face of death, leaving only what is truly important. Remembering that you are going to die is the best way I know to avoid the trap of thinking you have something to lose. You are already naked. There is no reason not to follow your heart.

About a year ago I was diagnosed with cancer. I had a scan at 7:30 in the morning, and it clearly showed a tumor on my pancreas. I didn't even know what a pancreas was. The doctors told me this was almost certainly a type of cancer that is incurable, and that I should expect to live no longer than three to six months. My doctor advised me to go home and get my affairs in order, which is doctor's code for prepare to die. It means to try to tell your kids everything you thought you'd have the next 10 years to tell them in just a few months. It means to make sure everything is buttoned up so that it will be as easy as possible for your family. It means to say your goodbyes.

I lived with that diagnosis all day. Later that evening I had a biopsy, where they stuck an endoscope down my throat, through my stomach and into my intestines, put a needle into my pancreas and got a few cells from the tumor. I was sedated, but my wife, who was there, told me that when they viewed the cells under a microscope the doctors started crying because it turned out to be a very rare form of pancreatic cancer that is curable with surgery. I had the surgery and I'm fine now.

This was the closest I've been to facing death, and I hope its the closest I get for a few more decades. Having lived through it, I can now say this to you with a bit more certainty than when death was a useful but purely intellectual concept:

No one wants to die. Even people who want to go to heaven don't want to die to get there. And yet death is the destination we all share. No one has ever escaped it. And that is as it should be, because Death is very likely the single best invention of Life. It is Life's change agent. It clears out the old to make way for the new. Right now the new is you, but someday not too long from now, you will gradually become the old and be cleared away. Sorry to be so dramatic, but it is quite true.

Your time is limited, so don't waste it living someone else's life. Don't be trapped by dogma - which is living with the results of other people's thinking. Don't let the noise of others' opinions drown out your own inner voice. And most important, have the courage to follow your heart and intuition. They somehow already know what you truly want to become. Everything else is secondary.

When I was young, there was an amazing publication called The Whole Earth Catalog, which was one of the bibles of my generation. It was created by a fellow named Stewart Brand not far from here in Menlo Park, and he brought it to life with his poetic touch. This was in the late 1960's, before personal computers and desktop publishing, so it was all made with typewriters, scissors, and polaroid cameras. It was sort of like Google in paperback form, 35 years before Google came along: it was idealistic, and overflowing with neat tools and great notions.

Stewart and his team put out several issues of The Whole Earth Catalog, and then when it had run its course, they put out a final issue. It was the mid-1970s, and I was your age. On the back cover of their final issue was a photograph of an early morning country road, the kind you might find yourself hitchhiking on if you were so adventurous. Beneath it were the words: "Stay Hungry. Stay Foolish." It was their farewell message as they signed off. Stay Hungry. Stay Foolish. And I have always wished that for myself. And now, as you graduate to begin anew, I wish that for you.

Stay Hungry. Stay Foolish.

Thank you all very much.

using java and mysql

by Paul DuBois

You can write MySQL applications in a variety of languages. The languages that most people use with MySQL are PHP and Perl, but a sometimes overlooked option is the MySQL Connector/J driver, which allows you to develop Java applications that interact with your MySQL server.
MySQL Connector/J works within the framework of the Java JDBC interface, an API that allows Java programs to use database servers in a portable way. JDBC is based on an approach similar to that used in the design of Perl and Ruby DBI modules, Python's DB-API module, and

PHP's PEAR::DB class. This approach uses a two-tier architecture:
The top level is visible to application programs and presents an abstract interface for connecting to and using database engines. The application interface does not depend on details specific to particular engines.

The lower level consists of drivers for individual database engines. Each driver handles the details necessary to map the abstract application interface onto operations that a specific engine will understand.The JDBC interface allows developers to write applications that can be used with different databases with a minimum of porting effort. Once a driver for a given server engine is installed, JDBC applications can communicate with any server of that type. By using MySQL Connector/J, your Java programs can access MySQL databases.

Note: MySQL Connector/J is the successor to the MM.MySQL driver. If you have JDBC programs written for MM.MySQL, they should work with MySQL Connector/J as well, although you may want to update the driver class name used in your programs. Just replace instances of org.gjt.mm.mysql in your Java source files with com.mysql.jdbc and recompile.

Preliminary Requirements

To use Java applications with MySQL, you may need to install some additional software:
If you want to compile and run Java programs, you'll need a Java compiler (such as javac or jikes) and a runtime environment. If these are not already installed on your system, you can get them by obtaining a Java Software Development Kit (SDK) from java.sun.com.

If you want only to run precompiled applications, no compiler is necessary, but you'll still need a Java Runtime Environment (JRE). This too may be obtained from java.sun.com.This article assumes that you'll write and compile your own programs, and thus that you have a Java SDK installed. Once you compile a Java program, however, you can deploy it to other machines, even ones that have only a runtime environment. This works even in heterogenous installations, because Java is platform-independent. Applications compiled on one platform can be expected to work on other platforms. For example, you can develop on a Linux box and deploy on Windows

Connecting to the MySQL Server

To connect to the MySQL server, register the JDBC driver you plan to use, then invoke its getConnection() method. The following short program, Connect.java, shows how to connect to and disconnect from a server running on the local host. It accesses a database named test, using a MySQL account with a user name and password of testuser and testpass: import java.sql.*;

public class Connect
{
public static void main (String[] args)
{
Connection conn = null;
try
{
String userName = "testuser";
String password = "testpass";
String url = "jdbc:mysql://localhost/test";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection (url, userName, password);
System.out.println ("Database connection established");
}
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
}
finally
{
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
}
}

Compile Connect.java to produce a class file Connect.class that contains executable Java code: % javac Connect.java
Then invoke the class file as follows and it should connect to and disconnect from your MySQL server: % java Connect
Database connection established
Database connection terminated
If you have trouble compiling Connect.java, double check that you have a Java Software Development Kit installed and make sure that the MySQL Connector/J driver is listed in your CLASSPATH environment variable.

The arguments to getConnection() are the connection URL and the user name and password of
a MySQL account. As illustrated by Connect.java, JDBC URLs for MySQL consist of jdbc:mysql:// followed by the name of the MySQL server host and the database name. An alternate syntax for specifying the user and password is to add them as parameters to the end of the connection URL: jdbc:mysql://localhost/test?user=testuser&password=testpass
When you specify a URL using this second format, getConnection() requires only one argument.

For example, the code for connecting to the MySQL server in Connect.java could have been written like this: String userName = "testuser";
String password = "testpass";
String url = "jdbc:mysql://localhost/test?user="
+ userName
+ "&password="
+ password;
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection (url);

getConnect() returns a Connection object that may be used to interact with MySQL by issuing queries and retrieving their results. (The next section describes how to do this.) When you're done with the connection, invoke its close() method to disconnect from the MySQL server.

To increase the portability of your applications, you can store the connection parameters (host, database, user name, and password) in a Java properties file and read the properties at runtime. Then they need not be listed in the program itself. This allows you to change the server to which the program connects by editing the properties file, rather than by having to recompile the program.

Issuing Queries

To process SQL statements in a JDBC-based application, create a Statement object from your Connection object. Statement objects support an executeUpdate() method for issuing queries that modify the database and return no result set, and an executeQuery() method for queries that do return a result set. The query-processing examples in this article use the following table, animal, which contains an integer id column and two string columns, name and category: CREATE TABLE animal
(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id),
name CHAR(40),
category CHAR(40)
)
id is an AUTO_INCREMENT column, so MySQL automatically assigns successive values 1, 2, 3, ... as records are added to the table.
Issuing Queries That Return No Result Set
The following example obtains a Statement object from the Connection object, then uses it to create and populate the animal table. DROP TABLE, CREATE TABLE, and INSERT all are statements that modify the database, so executeUpdate() is the appropriate method for issuing them:

Statement s = conn.createStatement ();
int count;
s.executeUpdate ("DROP TABLE IF EXISTS animal");
s.executeUpdate (
"CREATE TABLE animal ("
+ "id INT UNSIGNED NOT NULL AUTO_INCREMENT,"
+ "PRIMARY KEY (id),"
+ "name CHAR(40), category CHAR(40))");
count = s.executeUpdate (
"INSERT INTO animal (name, category)"
+ " VALUES"
+ "('snake', 'reptile'),"
+ "('frog', 'amphibian'),"
+ "('tuna', 'fish'),"
+ "('racoon', 'mammal')");
s.close ();
System.out.println (count + " rows were inserted");
The executeUpdate() method returns the number of rows affected by a query. As shown above, the count is used to report how many rows the INSERT statement added to the animal table.

A Statement object may be used to issue several queries. When you're done with it, invoke its close() method to dispose of the object and free any resources associated with it

Issuing Queries That Return a Result Set

For statements such as SELECT queries that retrieve information from the database, use executeQuery(). After calling this method, create a ResultSet object and use it to iterate through the rows returned by your query. The following example shows one way to retrieve the contents of the animal table:

Statement s = conn.createStatement ();
s.executeQuery ("SELECT id, name, category FROM animal");
ResultSet rs = s.getResultSet ();

int count = 0;
while (rs.next ())
{
int idVal = rs.getInt ("id");
String nameVal = rs.getString ("name");
String catVal = rs.getString ("category");
System.out.println (
"id = " + idVal
+ ", name = " + nameVal
+ ", category = " + catVal);
++count;
}
rs.close ();
s.close ();

System.out.println (count + " rows were retrieved");

executeQuery() does not return a row count, so if you want to know how many rows a result set contains, you should count them yourself as you fetch them.
To obtain the column values from each row, invoke getXXX() methods that match the column data types. The getInt() and getString() methods used in the preceding example return integer and string values. As the example shows, these methods may be called using the name of a result set column. You can also fetch values by position. For the result set retrieved by the SELECT query in the example, id, name, and category are at column positions 1, 2 and 3 and thus could have been obtained like this:

int idVal = rs.getInt (1);
String nameVal = rs.getString (2);
String catVal = rs.getString (3);

ResultSet objects, like Statement objects, should be closed when you're done with them.

To check whether or not a column value is NULL, invoke the result set object's wasNull() method after fetching the value. For example, you could check for a NULL value in the name column like this: String nameVal = rs.getString ("name");

if (rs.wasNull ())
nameVal = "(no name available)";

Using Placeholders

Sometimes it's necessary to construct queries from values containing characters that require special treatment. For example, in queries, string values are written enclosed within quotes, but any quote characters in the string itself should be doubled or escaped with a backslash to avoid creating malformed SQL. In this case, it's much easier to let JDBC handle the escaping for you, rather than fooling around trying to do so yourself. To use this approach, create a different kind of statement (a PreparedStatement), and refer to the data values in the query string by means of placeholder characters. Then tell JDBC to bind the data values to the placeholders and it will handle any special characters automatically.

Suppose you have two variables nameVal and catVal from which you want to create a new record in the animal table. To do so without regard to whether or not the values contain special characters, issue the query like this:

PreparedStatement s;
s = conn.prepareStatement (
"INSERT INTO animal (name, category) VALUES(?,?)");
s.setString (1, nameVal);
s.setString (2, catVal);
int count = s.executeUpdate ();
s.close ();

System.out.println (count + " rows were inserted");
The '?' characters in the query string act as placeholders--special markers indicating where data values should be placed. The setString() method takes a placeholder position and a string value and binds the value to the appropriate placeholder, performing any special-character escaping that may be necessary. The method you use to bind a value depends on the data type. For example, setString() binds string values and setInt() binds integer values.

Error Handling

If you want to trap errors, execute your JDBC operations within a try block and use an exception handler to display information about the cause of any problems that occur. JDBC provides getMessage() and getErrorCode() methods that may be invoked when an exception occurs to obtain the error message and the numeric error code. The following example deliberately issues a malformed query. When it runs, the executeQuery() method fails and raises an exception that is handled in the catch block: try
{
Statement s = conn.createStatement ();
s.executeQuery ("XYZ"); // issue invalid query
s.close ();
}
catch (SQLException e)
{
System.err.println ("Error message: " + e.getMessage ());
System.err.println ("Error number: " + e.getErrorCode ());
}

smiletag 2.3 released

what is smiletag?

smiletag is a free (GPL License) shoutbox written in PHP.Available as general purpose version, WordPress plugin, Joomla / Mambo module and Drupal module version, smiletag is an interactive, easy to use, mini-message board with powerful template system.
Powerful template system, easy-to-modify templates using only simple tags, no programming skills required. Lot of themes available.

features

Smart auto-refresh, automagically refreshes whenever a new message is posted, this is done using Ajax technology.

Message Moderation, if enabled you can take control for every submitted message before they appear in the shoutbox.

Admin Panel, easily edit/delete messages, moderate, ban, add smilies, configure and more. Try the admin panel demo.

No database is needed, uses flat file (XML) for storage.

Profanity filters, easily add your own custom words to filter as well.

Flood guard, stop spammer from flooding your board.

Valid XHTML, outputs Valid XHTML 1.0 Transitional code.

IP Address/Nick banning, support for both manual and automatic banning.

Customizable smilies, you can add your own images as many as you want.

Time Zone Control, sets the time zone to any GMT offset.

Multi-language support.

Email/URL recognition, automatically convert any email or url into link.

Custom CSS File, you have complete control for your board look and feel.

Alternate custom text, more than just alternating background color, you can alternate any text to switch for each row.

Filters HTML tags and blank messages.

Message formatting, allow bold, italic and underline.

Custom Header and Footer, put any text at the top and bottom of your board.

Timestamp, easily change the format using simple rule.

Logs visitor IP Address.

Auto rotate each message, in order to avoid a large file from staying on your server.

Configurable number of messages to display.

Configurable message length.

It's free and comes with complete source code.

smiletag can be downloaded Here

Thursday, February 09, 2006

ezsql 2.0 released

Overview

ezSQL is a class that makes it ridiculously easy to use mySQL, Oracle8, SQLite (PHP), within your PHP script. Includes lots of examples making it very easy to understand how to work with databases. ezSQL has excellent debug functions making it lightning-fast to see what’s going on in your SQL code. ezSQL can dramatically decrease development time and in most cases will streamline your code and make things run faster.
Features

ezSQL is a widget that makes it ridiculously easy for you to use mySQL, Oracle8, InterBase/FireBird, PostgreSQL, SQLite (PHP), SQLite (C++) or MS-SQL database(s) within your PHP/C++ scripts (more db's coming soon)


It is one php file that you include at the top of your script. Then, instead of using standard php database functions listed in the php manual, you use a much smaller (and easier) set of ezSQL functions.


It automatically caches query results and allows you to use easy to understand functions to manipulate and extract them without causing extra server overhead


It has excellent debug functions making it lightning-fast to see what's going on in your SQL code


Most ezSQL functions can return results as Objects, Associative Arrays, or Numerical Arrays


It can dramatically decrease development time and in most cases will streamline your code and make things run faster as well as making it very easy to debug and optimise your database queries.


Works with Smarty templating language


It is a small class and will not add very much overhead to your website.

Download ezSQL completely Free from here , also check out EZ Results Paging Class ezSQL's sister class that makes result paging a snip.

Wednesday, February 08, 2006

Debugging Php

by David Sklar

Whether you're a PHP newbie or a wizard, your programs are going to have bugs in them. Nobody's perfect.

This article gives you some techniques for finding and fixing the problems in your programs. It covers three topics:


1) How to get the PHP interpreter to report the errors that interest you.
2) How to locate basic syntax errors in your program.
3) How to check the values of variables as your program is running.

Configuring Error Reporting

First of all, you need to configure the PHP interpreter so that when an error happens, you can see information about it. The error info can be sent along with program output to the web browser. It can also be included in the web server error log. A common way to set things up is to have error output go to the web browser when you're debugging your program, and then to the web server error log once the program is finished and (supposedly) working properly. That way, web site users can't see any potentially sensitive data included with error output.

To make error messages display in the browser, set the display_errors configuration directive to On. To send errors to the web server error log, set log_errors to On. You can set them both to On if you want error messages in both places.
An error message that the PHP interpreter generates falls into one of five different categories:


Parse error: A problem with the syntax of your program, such as leaving a semicolon off of the end of a statement. The interpreter stops running your program when it encounters a parse error.

Fatal error: A severe problem with the content of your program, such as calling a function that hasn't been defined. The interpreter stops running your program when it encounters a fatal error.
Warning: An advisory from the interpreter that something is fishy in your program, but the interpreter can keep going. Using the wrong number of arguments when you call a function causes a warning.

Notice: A tip from the PHP interpreter, playing the role of Miss Manners. For example, printing a variable without first initializing it to some value generates a notice.

Strict notice: An admonishment from the PHP interpreter about your coding style. Most of these have to do with esoteric features that changed between PHP 4 and PHP 5, so you're not likely to run into them too much.

You don't have to be notified about all of the different error categories. The error_reporting configuration directive controls which kinds of errors the PHP interpreter reports. The default value for error_reporting is E_ALL & ~E_NOTICE & ~E_STRICT, which tells the interpreter to report all errors except notices and strict notices.

PHP defines some constants you can use to set the value of error_reporting so that only errors of certain types get reported: E_ALL (for all errors except strict notices), E_PARSE (parse errors), E_ERROR (fatal errors), E_WARNING (warnings), E_NOTICE (notices), and E_STRICT (strict notices).

Because strict notices are rare (and new to PHP 5), they are not included in E_ALL. To tell the PHP interpreter that you want to hear about everything that could possibly be an error, set error_reporting to E_ALL E_STRICT.

Fixing Parse Errors

The first time you write a PHP program, you discover that the PHP interpreter is extremely picky. If you leave out a necessary semicolon or start a string with a single quote but end it with a double quote, the interpreter doesn't run your program. It throws up its (virtual) hands, complains about a parse error, and leaves you stuck in the debugging wilderness.

This can be one of the most frustrating things about programming when you're getting started. Everything has to be phrased and punctuated just so in order for the PHP interpreter to accept it. One thing that helps this process along is writing your programs in an editor that is PHP-aware, such as BBEdit, Emacs, XEmacs, Komodo, Dreamweaver, PHPEd, PHPEdit, or Zend Studio.

These editors do syntax highlighting. This is a feature that changes the color of different parts of your program based on what those parts are. For example, strings are pink, keywords such as if and while are blue, comments are grey, and variables are black. Syntax highlighting makes it easier to detect things like a string that's missing its closing quote: the pink text continues past the line that the string is on, all the way to the end of the file (or to the next quote that appears later in the program).

Another feature of these editors is quote and bracket matching. This helps to make sure that your quotes and brackets are balanced. When you type a closing delimiter such as }, the editor highlights the opening { that it matches. Different editors do this in different ways, but typical methods are to flash the cursor at the location of the opening {, or bold the { } pair for a short time. This behavior is helpful for pairs of punctuation marks that go together: single and double quotes that delimit strings, parentheses, square brackets, and curly braces.

These editors also show the line numbers of your program files. When you get an error message from the PHP interpreter complaining about a parse error in line 35 in your program, you can focus on the right place to look for your error.
Parse errors happen when the PHP interpreter comes upon something unexpected in your program.

Consider this broken program:

Inspecting Program Data

Once you clear the parse error hurdle, you still may have some work to do before you reach the finish line. A program can be syntactically correct but logically flawed. Just as the sentence "The tugboat chewed apoplectically with six subtle buffaloes" is grammatically correct but meaningless nonsense, you can write a program that the PHP interpreter doesn't find any problems with, but doesn't do what you expect.
If your program is acting funny, add some checkpoints that display the values of variables. That way, you can see where the program's behavior diverges from your expectations. The following program incorrectly attempts to calculate the total cost of a few items:

Going Further

Once you've got error reporting set up as you like it, and you know how to find parse errors, and you can inspect program data, you're on your way to a fruitful debugging career. However, a fully fleshed-out PHP programmer's toolbox consists of much more than just the tips in this article. Chapter 12 of Learning PHP 5, "Debugging," includes some additional debugging techniques. For more advanced debugging possibilities, check out PHP extensions such as XDebug and apd. Some of the PHP-aware editors listed in this article also include integrated debugging capabilities.

Tuesday, February 07, 2006

php vs. java

by Jack Herrington

PHP scales. There, I said it. The word on the street is that "Java scales and PHP doesn't." The word on the street is wrong, and PHP needs someone to stand up and tell the truth: that it does scale.

Those with a closed mind can head straight to the inevitable flame war located at the end of this article. Those with an open mind who are interested in taking their web development skills and putting them to use building applications in the cross-platform, easy-to-write, easy-to-maintain, scalable, and robust PHP platform, but were hesitant because of the scalability myth, should read on. It starts by looking at the term scalability.

What is Scalability?

There are a number of different aspects of scalability. It always starts with performance, which is what we will cover in this article. But it also covers issues such as code maintainability, fault tolerance, and the availability of programming staff.

These are all reasonable issues, and should be covered whenever you are choosing the development platform for any large project. But in order to convey a convincing argument in this small space, I need to reduce the term scalability to its core concern: performance.

Language and Database Performance

Both Java and PHP run in virtual machines, which means that neither perform as well as compiled C or C++. In the great language shootout, Java beat PHP on most of the performance benchmarks, even substantially on some. However, overall the two languages were not an order of magnitude different. In addition, an older version of PHP was used in the test, and substantial performance improvements have been made since and are continuing to be made.
Another area of performance concern is in the connection to the database. This is a misnomer, however, as the majority of the time spent in a database query is on the database server end, processing the query, and the transmit time to marshal the data between the server and the client. PHP's connectivity to the database consists of either a thin layer on top of the C data access functions, or a database abstraction layer called PEAR::DB. There is nothing to suggest that there is any PHP-specific database access performance penalty.

Yet another area of efficiency concern is in the connection between the language and the web server. In the CGI model, the program or interpreter is booted on each request. In the in-process model, the interpreter stays around after each request. One of the original Java-versus-scripting-languages (e.g. PHP) benchmarks pit in-process Java against CGI invocation on the server. In the CGI model, each page incurred the overhead of the startup and shutdown of the interpreter. Even at the time, the comparison was unfair, as production machines used server-scripting extensions (such as PHP), which run in-process and stay loaded between each page fetch. There is no performance penalty for loading the interpreter and compiled pages remain in memory.

With these basic efficiency questions out of the way, it's time to look at the overall architecture of the web application

Comparing Architectures

There are three basic web architectures in common use today: two-tier, logical three-tier, and physical three-tier. Engineers give them different names and slightly different mechanics, so to be clear about what I mean, I will illustrate the three architectures.

J2EE Web Server Architecture

Perhaps the second most contentious part of this article is my definition of a J2EE web server application architecture. Externally to the Java community, the application structure looks clear: JSPs talk to EJBs, which talk to the database. Within the Java community, the standard J2EE topology is anything but clear. A comparison is only valid between two things, so to decide whether "Java scales and PHP doesn't," I need to be clear about what a Java web application server is.
I'll take the two most common interpretations of J2EE architecture. The first is Sun's EJB 1.0 architecture, and the second is the EJB 2.0 architecture. Shown below is Sun's EJB 1.0 architecture for web application servers:



This is classic physical three-tier architecture, and it pays the performance price. I've highlighted the portions of the architecture that involve network traffic, either via database connection, an overhead shared by PHP, or by Remote Method Invocation (RMI), an overhead not shared by PHP.

To be fair, the connection between the web server and the servlet engine can be avoided with modern application servers and web servers, such as Tomcat and Apache 2.0. At the time when the first versions of the JSP and EJB standards were released, the prevalent web server was (and still is) Apache 1.x, which had a process model that was not compatible with Java's threading model. This meant that a small stub was required on the web server side to communicate with the servlet engine. The remains a non-trivial performance overhead for those that decide to pay it, and was a significant performance overhead when the first scalability comparisons were made.
A much more significant source of overhead was in the RMI connection between the servlet engine and the EJB layer. A page showing ten fields from twenty objects would make two hundred RMI calls before it was completed. This overhead was removed with the EJB 2.0 standard, which introduced local interfaces. This topology is shown below:



This is logical three-tier architecture. The web server box has been removed because more recent web servers are not separated from the servlet code (e.g. Tomcat, Apache 2.0, etc.). As you will see when we compare this model to the PHP model, EJB 2.0 moved Java web application server development closer to the successful, and scalable, PHP model.

PHP Web Server Architecture

PHP has always been capable of running the gamut between a two-tier architecture and a logical three-tier architecture. Early versions of PHP could abstract the business and database access logic into a functional second tier. More recent versions can abstract the business logic with objects, and with PHP 5, these objects can use public, protected, and private access control.

A modern PHP architecture, strikingly similar to the EJB 2.0 model, is shown below:



This is logical three-tier architecture, and this is how modern PHP applications are written. As with Java web servers, the PHP code is in-process with the web server, so there is no overhead in the server talking to the PHP code.

The PHP page acts as a broker between second-tier business objects and Smarty templates, which format the page for presentation. As with the JSP "best practice," the Smarty templates are only capable of displaying the data presented, with rudimentary looping and conditional control structures.

But this is all about the design of the server. What about the architecture of the application itself?

Stateful and Stateless Architecture

The lack of an external, stateful object store, where the application can hold session state, is often voiced as a scalability concern. PHP can use the database as the back-end session store. There is little performance difference, because a network access is required in both cases. An argument can be made that the external object store allows for any arbitrary data to be stored conveniently; however, this is easily offset by the fact that the object store itself is a single point of failure. If the object store is replicated across multiple web servers, that becomes an issue of data replication and cache coherency, which is a very complex problem.

Another familiar Java pattern is the use of a local persistent object store on each web server. The user is limited to a single server by use of sticky sessions on the router. The same could be done in PHP: a local, persistent data store. But this is an anti-pattern anyway, because a sticky session-based server pool is prone to overloading of a single web server. Or should the server go down, the result is the denial of service to a group of customers.

The ideal multi-server model is a pod architecture, where the router round-robins each of the machines and there is only a minimal session store in the database. Transient user interface information is stored in hidden variables on the web page. This allows for the user to run multiple web sessions against the server simultaneously, and alleviates the "back button issue" in web user interfaces.

This section has covered some very complex issues in web application server design. Scalability is mainly about the architecture of the application layer, and there is no one true panacea architecture that will work for all application architectures. The key to success is not in any particular technology, but in simplifying your server model and understanding all of the components of the application layer, from the HTML and HTTP on the front end to the SQL in the back end. Both PHP and Java are flexible enough to create scalable applications for those who spend the time to optimize their application architecture.

The Convergence of Web Application Architecture

This article started by asserting that PHP scales. When the tag-line "Java scales and scripting languages don't" was born, it was based on EJB 1.0, an architecture that most Java architects would consider absurd, based on its high overhead. Based on EJB 1.0, Java's performance was much worse than that of scripting languages. It is only the addition of local interfaces in EJB 2.0 that makes the J2EE architecture perform well.

The argument for PHP scalability is further simplified, however, by the fact that both PHP and J2EE architecture (as well as others) are converging on the same design. And if "J2EE scales" given this simpler, logical three-tier architecture, then it follows that PHP does as well.
The performance principle for scalability is simple: if you want to scale, then you have to serve web pages quickly. To serve web pages quickly, you either have to do less, or do what you do faster. Faster is a non-starter, because Java is not so much faster than PHP that it makes much of a difference. Doing less is the key. By using a logical three-tier architecture and by reducing the number of queries and commands sent to the database, we can get web applications that scale, both in Java and in PHP.

For the open-minded developer, there is a world of applications that can be built quickly, cheaply, robustly, and scalably with PHP. Services such as Amazon, Yahoo, Google, and Slashdot have known about scripting languages for years and used them effectively in production. Yahoo even adopted PHP as its language of choice for development. Don't believe the hype in the white papers that says that PHP isn't for real applications or doesn't scale.

I'm sure that what I have said in this article will be picked to death and ridiculed by some. I stand by what I have said. The idea that PHP does not scale is clearly false at the performance level. In fact, we should have never even gotten to the point where this article was necessary, because as engineers, we should recognize that the argument that one language clearly "scales better" than another is, on its face, ridiculous. As engineers and architects, we need to look objectively at technologies and use a factual and rational basis to make technology decisions.