Archive for August, 2007

Web hosting services - 585Chapter 32DebuggingCompile-time bugsPHP is a compiled language it s compiled

Friday, August 24th, 2007

585Chapter 32DebuggingCompile-time bugsPHP is a compiled language it s compiled just before it executes, so the compilation isn t asobvious as it is in C or Java. A compile-time bug is obvious to the Zend Engine, which does the compiling. The compilerwill raise an objection, often with a line number, and you can go fix the problem. Examples of compile-time errors are mistyped variable names, forgotten semicolons, and mismatchedparentheses. Run-time bugsA run-time bug doesn t appear until after your program is under way, and may result fromsome outside condition, such as unexpected input from a user or unanticipated behavior by a database. These have to be tested for, as they usually won t make themselves evident toprogrammers under all conditions. Logical bugsLogical bugs are perhaps the most difficult of all to spot and can be very difficult to fix if theyresult from an error in thinking. Say you wanted to launch a space probe and have it enter orbit around Mars. However, becauseyour navigation algorithm didn t allow for metric input from those pesky Europeans, yourspace probe crashed into the Martian surface. The software did exactly as it was told, which, strictly speaking, was to drive the rocket into Mars. That s a logical error. The point: Make sure your programs not only generate output, but generate the correct output. Get out the calculator and make sure the program s results are right, or compare its results tovalues known to be good. And don t use PHP to program spacecraft, just to be safe. For a guide to the most common symptoms of the most common compile-time and run-timebugs, see Chapter 11. Using Web Server LogsBecause most PHP programs result in some sort of HTML page, which is in turn served by an HTTP server such as Apache or Microsoft Internet Information Server (IIS), it is possiblefor errors to be introduced by the Web server software. For that reason, it is important to befamiliar with the way in which your Web server manages error reporting and logging and toknow how to access and interpret the logs you need. ApacheThe Apache HTTP Server maintains two log files in plain text format. They are: .Apache/logs/access.log: Notes every HTTP request for a file, including its date, time, and result (success or failure, as indicated by a numeric status code). The access logalso records the IP address from which each request came. .Apache/logs/error.log: Records error conditions only. Cross- Reference36
Looking for affordable and reliable webhost to host and run your business application? Then look no more and go to servlet web hosting services.

584Part IIIAdvanced Features and TechniquesTry to isolate the (Web design online)

Thursday, August 23rd, 2007

584Part IIIAdvanced Features and TechniquesTry to isolate the problemIf you can narrow the problem down to a single library or function, you ve made significantprogress in locating the cause. Use special echo()and print_r()calls to output trace infor- mation frequently. This will allow you to see when troublesome changes are taking place andwhen variables stop holding the values you think they re holding. You can also use a visual debugger (like Zend Studio, discussed later in this chapter) to moni- tor programs and their members as they execute. Simplify, then build upIt sounds obvious, but if you re having trouble with a given function or feature, cut it out (eitherliterally or with comments) and make sure everything runs without it. Then replace dynamicdata with static data (replace a database query with simple variable assignment statements). Get it working right under simple conditions, and add complexity in stages, testing all the wayto see when errors appear. Check the obviousWe ve all heard the story about the call to tech support in which the customer complains thathe can t see his mouse pointer move, and after lots of diagnostics it turns out that the machineisn t plugged in. It s probably apocryphal, but in any case make sure your Web server is work- ing properly on its own, and that a basic Hello, World script renders properly. You can alsoadd phpinfo()to the end of a simple test script to get a lot of information about your PHPinterpreter s version and environment details. Speaking of version, make sure you re not trying to do something that requires register_ globals(the infamous setting in php.ini) to be on. That setting is set to noby default, as ofPHP4.2, and it s tripped up more than one programmer. Document your solutionIt s extraordinarily common: You struggle with an error condition for hours (or longer) andfinally reach a solution. At that point, don t immediately head out to celebrate. Take a minuteto document what happened and what the solution was. That way, you ll be ready when thesame problem pops up again and it will. After fixing, re-testIt s not unusual to fix a problem and in doing so break something else. That s why it s impor- tant to retest your system beyond the scope of the bug you were originally after. This alsopoints out why it s important to isolate bugs as much as possible it limits the scope of re-testing you have to do. A Menagerie of BugsA number of different kinds of bugs plague programmers. Some bugs are both simple innature and easily found (as is the case with syntax errors and spelling mistakes). Others aresignificantly more difficult to catch, which is why this chapter is here.
If you are looking for affordable and reliable webhost to host and run your business application visit our ftp web hosting services.

DebuggingDebugging finding and eliminating errors is part (Web server version) of softwaredevelopment. As

Wednesday, August 22nd, 2007

DebuggingDebugging finding and eliminating errors is part of softwaredevelopment. As a PHP programmer, you should be aware of allthe tools available to you as you seek to eliminate malfunctioning ele- ments in your software systems. There are many such tools, not least because PHP applications usually rely on the capabilities of several servers (such as an HTTPserver and a database management server), each of which typicallycomes equipped with its own logging and reporting capabilities withwhich it keeps its users hip to what s happening. Plus, PHP has a con- siderable error-reporting facility of its own (you can choose to haveerror messages printed alongside normal output or logged to a file for more discreet analysis). The language also has a number of func- tions with which you can have your programs generate custom errorreports, and at the very least you can use conditional print statementsto monitor the activity of programs (and the values of variables withinthem) as they execute. On top of the built-in error-reporting capabilities of PHP and its sup- porting technologies, PHP programmers now have access to the sortsof debugging tools that programmers working with other languageshave had for years. Chief among these is the Zend debugging environ- ment, which allows you to monitor variable values, set breakpoints, and step through programs at any pace you like. This chapter aims to introduce you to the tools and techniques avail- able to you as you work to perfect your PHP software. General Troubleshooting StrategiesThe two basic elements of a debugging effort are figuring out what swrong, and then fixing it (without breaking something else as a sideeffect of your solution). It doesn t matter whether you re diagnosing aPHP program, a telephone switch, an electronic circuit, or a Buick certain principles apply regardless. Bear these ideas in mind as youtry to figure out what ails your software. Change one thing at a timeIt s a basic rule of experimentation: You can t be sure what caused agiven effect if there are multiple variables. Make a single change; thenexamine the output and see if the unwanted behavior is fixed. If not, try one more change (possibly changing the first one back to the wayit was). 3232CHAPTER …In This ChapterUsing Web server logsPHP error reportingError-reporting functionsDiagnostic printstatementsVisual debugging tools …
Note: If you are looking for cheap and reliable webhost to host and run your mysql application check mysql web server services.

581Chapter 31Exceptions and Error Handlingerror_log()accepts one of four (Ftp web hosting)

Tuesday, August 21st, 2007

581Chapter 31Exceptions and Error Handlingerror_log()accepts one of four integers as the second parameter, which sets the messagetype in conjunction with the third, or location, parameter: 0 uses the operating system s system logging mechanism1 sends the error to a specified e-mail address (extra headers may be added as afourth parameter) 2 sends the error through PHP s debugging connection (remote debugging must beenabled) 3 error message is appended to a destination error log fileSummaryError handling continues to become easier and more uniform with the ongoing developmentof PHP. The Exception class provides a means of separating error conditions, or exceptions, from the flow of the application. Using the try/catch block and custom-defined Exception sub- classes, errors can be intercepted and even recovered. Previous versions of PHP also provide a measure of error handling and reporting. User errorscan be triggered as an alternative to throwing an exception, and custom error handlers canprovide a better user experience as well as useful debugging information. Logging and debug- ging are crucial to successful exception and error handling. …
Visit our web design programs services for an affordable and reliable webhost to suit all your needs.

Web hosting solutions - 580Part IIIAdvanced Features and TechniquesLogging and DebuggingAs mentioned

Monday, August 20th, 2007

580Part IIIAdvanced Features and TechniquesLogging and DebuggingAs mentioned earlier, exception handling and error reporting can turn your debugging effortsinto a nightmare if not executed with care. An error that is difficult to track down can becomealmost impossible when it has been suppressed or rerouted carelessly. With a bit of planning, however, exceptions and error handlers can greatly simplify maintenance of an application. Previously, we have examined the process of dealing with errors primarily as a means ofavoiding disruption for the user. The same process can also be applied to enable logging anddebugging for the programmer. Within your catch()control block, include a call to a built-infunction such as error_log(), with any relevant information that might aid in the debuggingprocess: } catch(Exception $ex) { // the input string passed to the object$msg = ($ex->getMessage()); // 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()); // write to error log$log_msg = Error $code in $file at line $line: $msg : . time(); error_log ($log_msg, 3, /var/tmp/php_error.log ); //print to screenecho Error no. $code: $msg in file $file on line $line ; } The process is similar when using a custom error handler:
You need excellent and relaible webhost company to host your web applications? Then pay a visit to Inexpensive Web Hosting services.

Business web hosting - 579Chapter 31Exceptions and Error HandlingFigure 31-3:A custom error

Sunday, August 19th, 2007

579Chapter 31Exceptions and Error HandlingFigure 31-3:A custom error handler preserves the interface. Triggering a user errorPHP4 can be used to trigger a user error, which is roughly equivalent to throwing an excep- tion in PHP5. An error of any type can be thrown by passing an error message and an optionalerror-level constant: The triggered error is best used in conjunction with a custom error handler. Once this error isthrown, your defined error handler will be used to provide a formatted error message to theuser. Note that the error-level constant defaults to E_USER_NOTICE, which is ignored unlessyou have specifically set error reporting otherwise.
We would like to recommend you tested and proved virtual web hosting services, which you will surely find to be of great quality.

578Part IIIAdvanced Features and TechniquesDefining (Top web site) an error handlerThere s

Sunday, August 19th, 2007

578Part IIIAdvanced Features and TechniquesDefining an error handlerThere s an important question to ask at this point: What information do you want displayed tothe user when an error occurs? Usually, it s not important, or even preferred, to display detailsof the inner workings of your application to an end user; not to mention that errors look uglyon a Web page. By creating a function that designs a custom error message, then setting thatfunction as the default error handler, you can avoid the awkward and unprofessional displayof errors to a user. First, let s create a function and determine what information we would like to provide. We willneed to accept as input parameters the error type, message, filename, and line number.

; echo Error: ; echo

; echo We re sorry, but an error has occurred . in this page. ; echo Please access the Help . page, ; echo or try again later. ; echo

; echo

; echo Error type: $err_type: $err_msg in $err_file . at line $err_line ; echo

; } ?> We have elected, in this case, to provide information on the specific error and where itoccurred. Depending on the situation, we may want to provide very little information to theuser other than the fact that an error has occurred and provide information on what to trynext. Now that we have defined our custom error handler, we simply need to refer to the functionwithin the code using the set_error_handler()function: set_error_handler( error_msg ); With this code in place, all errors that are enabled by the error-reporting level will directthrough our custom function, with the unfortunate exception of a fatal error. See Figure 31-3for an example of such an error being displayed.
Searching for affordable and proven webhost to host and run your servlet applications? Go to Linux Web Hosting services and you will find it.

Web hosting - 577Chapter 31Exceptions and Error HandlingFigure 31-2:Native PHP Fatal

Saturday, August 18th, 2007

577Chapter 31Exceptions and Error HandlingFigure 31-2:Native PHP Fatal error terminates execution of the page. Each type of error is also represented by a constant that can be referred to within your code: E_USER_NOTICE, E_USER_WARNING, and E_USER_ERROR. The error-reporting level can be man- ually defined within a script, as in these examples: //report only fatal errorserror_reporting(E_USER_ERROR); //report warnings and fatal errorserror_reporting(E_USER_WARNING | E_USER_ERROR); //report all errors, including noticeserror_reporting(E_ALL); Suppressing error reporting to avoid printed errors can lead to hair loss during the debuggingprocess! You will instead want to deal with an error handler, for the most part. Because notices never make it to the client, and don t impair functionality, you re almostalways safe in disregarding them for error handling purposes. Conversely, the custom errorhandler cannot handle fatal errors; PHP considers them serious enough to terminate thescript, no questions asked. So the usefulness of the custom error handling function is gener- ally limited to warnings. The primary use of this function is to avoid printing program-eseerror messages for the end user and disrupting the flow of the application. Caution35
Check Tomcat Web Hosting services for best quality webspace to host your web application.

576Part IIIAdvanced (Web server type) Features and TechniquesOther Methods of Error

Friday, August 17th, 2007

576Part IIIAdvanced Features and TechniquesOther Methods of Error HandlingIf you re still using PHP4 or an older version, or are not comfortable dealing with classes andobjects, there are several error handling functions that have been available in PHP for sometime, including native PHP errors, defining an error handler, and triggering a user error. Native PHP errorsPHP generates three types of errors, depending on severity: .Notice:These errors are not serious and do not create a serious problem. By defaultthey are suppressed, unless the logging level is changed in the php.ini file. .Warning:Failed code has created an error, but does not terminate execution. Usuallythe error is displayed, but the script continues to run. (See Figure 31-1.) Figure 31-1:Native PHP Warning allows the page to finish rendering. .Fatal error:A serious error condition has rendered the script unable to run. A fatalerror terminates the script. (See Figure 31-2.)
You need excellent and relaible webhost company to host your web applications? Then pay a visit to Inexpensive Web Hosting services.

Free web hosts - 575Chapter 31Exceptions and Error Handlingparent::Exception($message); } } echo

Friday, August 17th, 2007

575Chapter 31Exceptions and Error Handlingparent::Exception($message); } } echo $msg; 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 PrefixException( $user_id does not contain the proper prefix. ); } // throw an exception if the user ID is not the proper length if ((strlen($user_id) < 9)) { throw new LengthException( $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; } } ?> Note that we attempted to recover from the missing prefixerror condition. You can easily dealwith individual types of errors now that they have been defined separately. Limitations of Exceptions in PHPThe Exception object is completely new in PHP5 and as such is still in the rough stages ofdevelopment. As of this writing, PHP does not support the use of finally()or throws() methods as do Java and other languages. Also, unlike other languages, native PHP errors including errors, which are normally printed to the client-side browser are not yet mappedto exceptions. Because of this, for example, a SQL statement error within a try/catch blockwill not automatically throw an exception that can be caught and dealt with. This handy func- tionality will most likely be included in a future version of PHP, so it s worth mentioning andkeeping an eye out for. Some of these errors can be dealt with using techniques described inthe next section.
If you are looking for affordable and reliable webhost to host and run your business application visit our ftp web hosting services.