Archive for August, 2007

574Part IIIAdvanced Features and TechniquesLet s look at (Web hosting script) the

Thursday, August 16th, 2007

574Part IIIAdvanced Features and TechniquesLet s look at the example covered in Listing 31-3 and consider using custom exceptions. Peoplesigning in using this code may forget to include the usr prefix in their user name, so if it smissing you might want to try adding it and validating again rather than immediately haltingthe program. Listing 31-3:Recovering using custom exceptionsgetMessage()); } } catch(LengthException $ex) { // retrieve the message from the exception object$msg = ($ex->getMessage()); } //define custom exception classesclass PrefixException extends Exception { function __construct($message) { parent::Exception($message); } } class LengthException extends Exception { function __construct($message) {
Note: In case you are looking for affordable and reliable webhost to host and run your j2ee application check Vision J2ee Web Hosting services.

573Chapter 31Exceptions and Error Handling Here, a standard, (Web hosting solutions)

Thursday, August 16th, 2007

573Chapter 31Exceptions and Error HandlinggetMessage()); // customizable error code$code = ($ex->getCode()); // name of the file that threw the exception$file = ($ex->getFile()); // line number containing the exception$line = ($ex->getLine()); echo Error no. $code: $msg in file $file on line $line ; } ?> Here, a standard, PHP style error message is displayed. However, you as the programmer candisplay anything that you like or can even change application behavior based on the specificerror. Note that, although in this example the code that throws the exception is the only thing in thetryblock, we could have had arbitrarily complex code that calls a function defined in a differ- ent file, which throws an exception only some of the time. Whenever an exception is thrown, control will revert to the catchblock associated with the try. Multiple catch blocks can be used to deal successfully with more than one type of exception. We ll look at an example in the following section. Defining your own Exception subclassesPHP also allows you to define your own classes that inherit from the Exception class. Nowyou no longer have to rely on the getMessage()function for information on the specific typeof error that was generated. Subclasses can be defined as in the following example:
Note: If you are looking for cheap and reliable webhost to host and run your mysql application check mysql web server services.

Shared web hosting - 572Part IIIAdvanced Features and TechniquesListing 31-2(continued) } //

Wednesday, August 15th, 2007

572Part IIIAdvanced Features and TechniquesListing 31-2(continued) } // throw an exception if the user ID is not the proper length if ((strlen($user_id) < 9)) { throw new Exception( $user_id is less than the required length ); } if (validate($user_id)) { // user ID was found in the database return true; } else // the specified user ID does not exist in the databasereturn false; } } ?> Don t be thrown by the use of the word throw. In this case, it is used to create a new Exceptionobject. Now errors that have nothing to do with normal flow are handled as separate excep- tions rather than mingling with the rest of the application. The try/catch blockExceptions are caught and handled using a try/catch control construct. You will want toinclude any code that may generate an error or exception within the try()construction. Whenever any exception is thrown by the code, the try()block execution is terminated, andthe remaining code within the try()construction is not executed. The catch()block is thenconsulted to find the proper type of exception, and the exception is then dealt with accordingto the code within that particular catch block. We now have different conditions based uponthe type of exception that was thrown, rather than one general, nonspecific error. Throwing an exceptionOne of the nice things about using exceptions is the ability to display as much or as little information as you need. There are several methods available for use with an Exceptionobject, which you can use to create your own error messages or to deal with conditionsaccordingly. The following code shows how you might throw and immediately catch a generic exception, and then take apart the Exception object to recover the message, error code, and originatingfile and line number.
We would like to recommend you tested and proved virtual web hosting services, which you will surely find to be of great quality.

Crystaltech web hosting - 571Chapter 31Exceptions and Error HandlingAs you can see,

Monday, August 13th, 2007

571Chapter 31Exceptions and Error HandlingAs you can see, any number of conditions might cause the is_valid_user()function toreturn a value of false, only one of which actually pertains to the question of whether theuser exists in the database. Using exceptions, you can more easily distinguish among types of errors and deal with them according to the nature of each error. The Exception classThe new Exception class is built into PHP5 and ready for use with any code on a PHP5 server. Rather than using Boolean functions as in the preceding example, an instance of Exceptioncan be created or thrown within the code. Listing 31-2 shows what Listing 31-1 might look like after rewriting to use exception-handling. Listing 31-2:Error-handling using exceptionsgetMessage()); } function is_valid_user ($user_id) { // throw an exception if the user ID does not begin // with usr $pre_str = usr ; if ((strpos($user_id, $pre_str) === false) || (strpos($user_id, $pre_str) != 0)) { throw new Exception( $user_id does not contain the proper prefix. ); Continued35
If you are searching for cheap webhost for your web application, please visit MySQL5 Web Hosting services.

570Part IIIAdvanced Features and TechniquesTake a look (Web hosting solutions) at

Monday, August 13th, 2007

570Part IIIAdvanced Features and TechniquesTake a look at some sample code that contains some error detection as it might be handled inPHP4 or earlier. We are retrieving a POST variable containing a user s ID, which must be atleast nine characters in length and begin with the usr prefix. Once the variable is checkedfor these conditions, we pass it to a function that will verify the existence of the user withinthe site database. Listing 31-1:Error-handling without exceptions
We recommend high quality webhost to host and run your jsp application: christian web host services.

Free web host - Exceptions andError HandlingUntil now, programmers have been very

Sunday, August 12th, 2007

Exceptions andError HandlingUntil now, programmers have been very creative in figuring outhow to deal with error cases within PHP, whether setting andprinting error strings or using and abusing the limited error reportingsystem. Despite its many useful features, PHP has not contained agood system for comprehensively dealing with errors. Fortunately, this is beginning to change with PHP5. Error Handling in PHP5If you are familiar with structured programming languages, such as Cand Java, you have probably grown accustomed to the various built- in objects that allow you to handle errors and exceptions. If so, you llbe happy to note that PHP5 now includes, for the first time, an excep- tion-handling object, and that the syntax is very similar to existinglanguages like Java. In fact, once you learn a bit of syntax you canbegin handling errors and exceptions much as you have been withother object-oriented languages. However, if you have been primarily using PHP, and are unfamiliarwith other languages, the idea of exception handling may be new to you. Exception handling is a powerful tool that you will come toappreciate once you understand the concept and put it to good usein your code. This new built-in function will enable you to debugerror conditions, recover from unexpected situations, and present a clean interface to your end users without printing errors to thescreen. Errors and exceptionsIt is helpful to think of an exception, not merely as an error. An excep- tion, as the name implies, is any condition experienced by your pro- gram that is unexpected or not handled within the normal scope ofyour code. Generally, an exception is not a fatal error that should haltprogram execution, but a condition that can be detected and dealtwith in order to continue properly. Exceptions, when properly used, can greatly increase the reliability ofyour application, and cut down on debugging headaches. However, poorly handled or ill-defined exceptions can create more problemsthan they solve by obscuring the source of an error. Plan on takingthe time to properly determine and execute your exception handlingmethod, and you will be amply rewarded. 3131CHAPTER …In This ChapterError handling in PHP5The Exception classThe try/catch blockThrowing an exceptionOther methods of errorhandlingLogging and debugging …
In case you need quality webspace to host and run your web applications, try our personal web hosting services.

568Part IIIAdvanced Features and (Space web hosting) TechniquesRecent distributions of PHP

Saturday, August 11th, 2007

568Part IIIAdvanced Features and TechniquesRecent distributions of PHP have also offered an optimized php.inithat sets variables formaximum speed at the possible expense of other virtues. If you choose to use this file, pleasetake the time to understand the effects of its changes in other words, don t just slap onyour server and then ask where your HTTP_*_VARSvalues went. SummaryThe good thing and the bad thing about PHP configuration are the same: There are a wholeheck of a lot of options and more than one way to set many of them. The Unix Apache moduleis particularly rich in choices, but the development team has labored long and hard to makePHP as customizable as possible. There are three main ways to configure PHP. The first is via build-time flags, which are onlyavailable to those who build from source. Many of these directives are only necessary pre- conditions, meaning they set default conditions that need to be confirmed or can be reversedelsewhere. The second is via Apache configuration files (httpd.confand .htaccess), whichare only available to users of Apache server. The third is via the php.inifile, which comeswith every PHP distribution. The php.inifile experienced a few significant changes with PHP4, but hopefully has stabi- lized somewhat with PHP5. One of the most important is the capability to disable functionson an individual basis. Certain features of PHP3 and PHP2 are beginning to be deprecated inthis file, such as register_globals. And the php.iniis no longer an absolute necessity onWindows versions of PHP now recognize default values even without the file being presentin the Windows path. After you ve run PHP for a while, you may wish to tune its performance. PHP4 and 5 are con- siderably faster at the same tasks than PHP3, and in general script execution time isn t thebottleneck to total performance but you may want to maximize the efficiency of your PHP- enabled server anyway. The main tool available to measure performance is simply echoingmicrotime()at intervals throughout a script. With this simple method, you can try to nar- row down and improve the parts of your scripts that are taking the most time. This does notmeasure anything outside PHP that may affect its performance; for that, you need externaltools such as ab(Apache Benchmark). Tools to help speed up PHP are becoming widely available. One of the most intriguing isZend s Accelerator, which promises at a minimum to double pages served on the same hard- ware. There are also alternatives available without cost. …
Note: If you are looking for cheap and reliable webhost to host and run your mysql application check mysql web server services.

Web design portfolio - 567Chapter 30ConfigurationUsing microtime()to measure PHP tells you only

Saturday, August 11th, 2007

567Chapter 30ConfigurationUsing microtime()to measure PHP tells you only what happens between the time PHPbegins working on the first measured line of code and the time it finishes working on the lastmeasured line of code. It does not tell you how long your Web server is taking to spawn achild process or your CGI to start up, how much latency your server is suffering from, whattraffic conditions at your Web farm are like, or a lot of other things that affect real-world per- formance at least as much if not more that actual PHP processing time. To find out that kindof thing, you need measuring tools far beyond PHP. A good start for Apache on Unix is theprogram called ab(aka Apache Benchmark tool), which ships with Apache. Now that you know how long the various parts of your script are taking, you can take steps to improve performance. Actually, a little logic should tell you that functions that touch otherfiles or call other daemons should take longer than those that are self-contained within a dis- crete file. So database calls, includeand requirestatements, objects with inheritance, andXML parsing are just going to take longer than simple arithmetic or echoing a string. Butbecause these advanced functionalities are the best part of PHP, obviously it would be point- less to get rid of them for the sake of squeezing out a few more microseconds. What you can and should do instead is hunt and destroy gross programming errors that causeunnecessary latency. Infinite loops, you know, are never very stylish. If you can notice a scriptrunning slowly with the naked eye, especially on a localhost, it s cause for concern whipout the microtime and find out where it s going wrong. Pay special attention to known bottle- necks such as: using regex instead of explode()in a tight loop; object-oriented programmingwhere it s not needed; bad use of SQL; including multiple instances of the same files; and longloops. Although it would be better to eliminate all errors in the code itself, you can also help mattersby setting the Apache or PHP timeout and max-memory configuration variables as low as pos- sible. Come on no Web page should need a 300-second timeout and you know it. Anotherconfiguration setting that may have a good effect on extremely slow scripts is ignore_user_ abortin php.ini. CautionOptimizers and cachesUntil recently, speed-shavers had few options but homemade metrics like the microtime() function just described. But now, intriguing tools are beginning to become widely used toincrease PHP performance. One that is available without cost is the Zend Optimizer. This tool makes multiple passes over aPHP script and replaces slower constructs with faster ones that have the same effect. However, the Zend Optimizer is rumored to mostly help inexperienced coders: If you already write tightPHP, it may not be able to add much value. Another Zend product which promises to affect performance positively is the Zend Accelerator. This product apparently compiles and stores a version of each page in memory, reducing diskreads and redundant compilation and thus speeding Web service. Reliable reports claim that theAccelerator can deliver from two to ten times improvement in number of requests handled. Boththe Zend Accelerator and the Zend Optimizer are availabe at the Zend Web site, www.zend.com. There are also optimizing and caching products available without cost. Two popular choices are Nick Lindridge s PHP Accelerator (www.php-accelerator.co.uk) and APC (http://apc. communityconnect.com).
In case you need affordable webhost to host your website, our recommendation is ecommerce web host services.

Sex offenders web site - 566Part IIIAdvanced Features and Techniquessession.save-handler = filesSee Chapter

Thursday, August 9th, 2007

566Part IIIAdvanced Features and Techniquessession.save-handler = filesSee Chapter 24 for details on this setting. Except in rare circumstances, you will not want tochange this setting. ignore_user_abort = [On/Off] This setting controls what happens if a site visitor clicks the browser s Stop button. The defaultis On, which means that the script continues to run to completion or timeout. If the setting ischanged to Off, the script will abort. This setting only works in module mode, not CGI. Improving PHP PerformanceThere are two schools of thought about Web performance. The first is that PHP script perfor- mance, theoretical Web server speed, chip clock speed, server RAM, and almost everythingelse is made irrelevant by throughput issues so why sweat the small stuff? The other is thatthere s no thrill quite like that of shaving a few microseconds off your script execution time. This section is basically useless for proponents of the former view. Before you can improve your performance, you have to measure it. Commercial profilingtools are just starting to hit the marketplace Zend Studio, which we discuss in Chapter 32, includes a profiling component but relatively few PHP users utilize them yet. We default, therefore, to the time-honored programming performance metric: measuring microseconds. Whip up a little function like this: function exec_time() { $mtime = explode( , microtime()); $msec = (double)$mtime[0]; $sec = (double)$mtime[1]; return $sec + $msec; } This function just reformats microtime output into a double for easier subtraction. Paste orinclude it at the top of the script you d like to measure. Now divide the main body of yourscript into sections and scatter calls to exec_time()at strategic points, like so: The next time you hit the Web page, voil ! A self-timing PHP script, at your service.
We recommend cheap and reliable webhost to host and run your web applications: Coldfusion Web Hosting services.

Web hosting reseller - 565Chapter 30Configurationregister_globals = OffThis setting allows you to

Thursday, August 9th, 2007

565Chapter 30Configurationregister_globals = OffThis setting allows you to decide whether you wish to register EGPCS variables as global. This is now deprecated, and as of PHP4.2, this flag is set to Offby default. Use superglobalarrays instead. All the major code listings in this book use superglobal arrays. gpc_order = GPCDeprecated. magic_quotes_gpc = OnThis setting escapes quotes in incoming GET/POST/COOKIEdata. If you use a lot of formswhich possibly submit to themselves or other forms and display form values, you may needto set this directive to Onor prepare to use addslashes()on string-type data. magic_quotes_runtime = OffThis setting escapes quotes in incoming database and text strings. Remember that SQL addsslashes to single quotes and apostrophes when storing strings and does not strip them offwhen returning them. If this setting is Off, you will need to use stripslashes()when out- putting any type of string data from a SQL database. If magic_quotes_sybaseis set to On, this must be Off. magic_quotes_sybase = OffThis setting escapes single quotes in incoming database and text strings with Sybase-style sin- gle quotes rather than backslashes. If magic_quotes_runtimeis set to On, this must be Off. auto-prepend-file = [path/to/file] If a path is specified here, PHP must automatically include()it at the beginning of everyPHP file. Includepath restrictions do apply. auto-append-file = [path/to/file] If a path is specified here, PHP must automatically include()it at the end of every PHPfile unless you escape by using the exit()function. Includepath restrictions do apply. include_path = [DIR] If you set this value, you will only be allowed to include or require files from these directories. The includedirectory is generally under your document root; this is mandatory if you re run- ning in safe mode. Set this to .in order to include files from the same directory your script is in. Multiple directories are separated by colons: .:/usr/local/apache/htdocs:/usr/ local/lib. doc_root = [DIR] If you re using Apache, you ve already set a document root for this server or virtual host inhttpd.conf. Set this value here if you re using safe mode or if you want to enable PHP onlyon a portion of your site (for example, only in one subdirectory of your Web root). upload_tmp_dir = [DIR] Do not uncomment this line unless you understand the implications of HTTP uploads!
You want to have a cheap webhost for your apache application, then check apache web hosting services.