1 / 23

PHP Bible

PHP Bible. Chapter 11: Basic PHP Gotchas. Summary. Installation-related problems Blank and incomplete pages Parse errors Permissions problems Unbound variables Function problems Math problems. Installation-related problems.

lambrose
Download Presentation

PHP Bible

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. PHP Bible Chapter 11: Basic PHP Gotchas

  2. Summary • Installation-related problems • Blank and incomplete pages • Parse errors • Permissions problems • Unbound variables • Function problems • Math problems

  3. Installation-related problems • Of course none of these problems will appear on the class' webserver, we'll go over some of the more common ones • Symptom: Text of file displayed in browser window • If your seeing your PHP script instead of the output HTML, check that you are accessing the site by http rather than the file system (e.g. http://localhost/mypage.php instead of file:/home/mypage.php) • Symptom: PHP blocks showing up as text • Filename extensions used for PHP are not associated to the PHP engine or you didn't give the file a PHP extension (e.g. .php) • Symptom: Server or host not found/Page cannot be displayed • DNS or web-server configuration issue. Try pinging the host by name & IP. If the name doesn't resolve but the IP does, it's a DNS issue. If the name resolves & pings, it's a web-server config issue where the server is probably not bound correctly to port 80

  4. Rendering problems • Symptom: Totally blank page • Probably an HTML problem where you are not outputting the proper HTML tags. Try viewing the source in the browser to see what errant code was output • Symptom: Document contains no data • PHP module may not be working correctly (try browsing another page in the same directory). Your code may not be outputting any HTML. Your PHP may be crashing before output can be generated (insert some print statements throughout your code so you can see where it is failing). • Symptom: Incomplete or unintended page • Usually bad HTML (view your HTML output, save it to a file, and run it through an HTML validation tool) • Symptom: PHP code showing up in browser • May be missing a PHP start tag

  5. Failures to load page • Symptom: Page cannot be found • If other things are working, you are probably misspelling the file name (capitalization must match, spaces, etc.) • Symptom: Failed opening [file] for inclusion • Misspelled included file name, incorrect directory permissions, path not set correctly for include files in php.ini

  6. Parse errors • Symptom: Parse error message (e.g. Parse error: parse error in myfile.php on line 30) • Category of errors arising from mistyped or syntactically incorrect PHP code • Line number may or may not have • Missing semicolon • Missing dollar sign preceding a variable name • Mode issues (failing to close a PHP section then trying to output HTML • Unescaped quotes (trying to put a quote symbol into a string without putting a backslash in front of it) • Unterminated strings (failing to close off a quoted string can result in parse errors located far away) • Anything else

  7. Unbound variables • Symptom: Variable not showing up in print string • Variable probably not assigned. Check spelling & capitalization • Variable also may be out of scope. If accessing global variable from within a function, use the global construct • Symptom: Numerical variable unexpectedly zero • Same as above

  8. Function problems • Symptom: Call to undefined function • Name may be misspelled, or function definition is missing • If function is located in an included file, the included file may not have been found (switch to using require_once) • Declaring the function as a variable (function $my_func()) • Using parenthesis in array indices ($my_array(5)) • Symptom: Cannot redeclare function • Two definitions exist with the same function name • Using include or require instead of include_once or require_once • Symptom: Wrong parameter count • Too many arguments or too few when calling a function

  9. Math problems • Symptom: Division-by-zero warning • Dividing by or using a function that divides by a variable that is unbound or which had been assigned a value of 0 • Unexpected arithmetic result • Check for unbound variables and precedence confusions. Add parentheses if you think precedence may be causing the problem • Symptom: NaN or NAN • Means Not a Number which is a misnomer. It is a number which has no value (not even 0), any equality tests with other numbers will return false (even when comparing it with the value NaN) • Generally the result of a numeric, yet invalid value being passed into a PHP function (e.g. passing 45.0 into acos()) • Any equations where the NaN value is a part of the equation will result in a NaN value

  10. Time-outs • Any download can occasionally time out before a complete page can be delivered. However, this shouldn't be happening frequently on your local development server. If it does, you may have an issue that has nothing to do with slow Internet connections or server overload. • Most "interesting" reason for a time-out is an infinite loop • Moster "interesting" reason for a time-out is infinite recursion (function which calls itself without having a way of stopping the process) • Can also be the result of resource requests timing out (e.g. running a query on a DB back-end which takes too long to return). Directives can be given to PHP in files which have long queries, etc. to wait longer for the query to return.

  11. PHP Style – Summary • How to earn style points • Commenting code • Writing maintainable code • Mixing HTML and PHP • Separating function from design

  12. Uses of style • Primary goal of any program is, of course, functionality • There is a vast difference, however, between simply whipping up something that will work and writing well-formed code that can be clearly understood by others • PHP programmers confront all the same style issues that other programmers do • Readability: You understood what you meant when you wrote it, but what about the next person who reads it (even if it's you) • Maintainability: What happens when your health site needs to change from using Fahrenheit to Celsius (don't just replace 100s of occurrences of 98.6) • Robustness: Your site works fine when it gets input it expects, but what happens when it gets inputs you don't expect? • Conciseness/efficiency: Fast code is better than slow code, and generally code with fewer keystrokes is better than with more keystrokes

  13. Readability • Before a PHP script can aspire to be maintainable or elegant, it has to be human-readable • It helps to start by making your HTML readable with tools like HTML Tidy (http://tidy.sourceforge.net/) • It also helps to select a good text/source code editor that suits your tastes. One which supports syntax highlighting can go a long way towards helping to eliminate some syntax errors • Indent your code so that code which is executed at the same level is indented to the same level. Increase the indent of code which is subordinated to another clause • Leave blank lines between different sections of your code

  14. Comments • Putting comments in your code is just like flossing your teeth: important for health and hygiene, the object of many good intentions, all too often skipped "just this once," and long regretted later if not done • You must explain: • Anything with future "what the heck was I thinking?" potential • Nothing you suspect might be a temporary expedient • Anything that will lead to dire consequences if tampered with by morons • You should also note in your comments: • Date file was originally created, name of the author, date file was most recently altered, name of the alterer, and explanation of the reason for the changes (will result in a list of changes made to the file), any other files or programs which depend on this file, intended purpose of the file and its constituent parts, things you might want to mention in documentation for the application, reason you want to save something that isn't being used

  15. File and variable names • Longer is generally better than shorter (unlike what we said earlier about the conciseness of your code) because it is more informative. • Break up long names with underscores or capitalization • $name_of_favorite_beer • $NameOfFavoriteBeer (aka CamelCaps) • Usually left to personal preference, but try to be consistent. However, it should be noted that CamelCaps don't work so well when you have an acronym in the variable or file name (PHPFile) • Situations arise in which you will want to keep using the same variable name in multiple contexts, however this should generally be avoided

  16. PEAR coding standards • PEAR is a software repository for PHP and PHP extensions (see http://pear.php.net) which enforces a specific set of guidelines for code that is deposited there: • Use <?php … ?> • Indent code by four spaces per level (no tabs) • Caveat: I disagree with this and prefer using tabs • Put a space between control structures (if, while) and the parenthesis that starts the test clause • Don't put a space between function names and the parenthesis that starts the parameter or argument list • Put the initial curly brace of a function definition (or any statement block) on its own line, rather than immediately following the argument list • Use // and /* … */ instead of # for comments

  17. Maintainability • Maintainability is often times in conflict with all other goals, especially speed. • There are 3 key points to making maintainable code • The things that are most likely to change should be the easiest to find (e.g. at the beginning of the file) • Changing those things should not have unpredictable effects • Each change should only have to be made in one place • One thing which is likely to change are "magic numbers." These are numbers that may be buried deep in your code which may need to be changed as circumstances change (e.g. hard-coding interest rates in formulas, etc.). • Instead use constants or variables for holding those values and put their definitions at the top of the program file along with a comment describing their use/purpose

  18. Functions • Utilizing functions effectively adds not only to the maintainability of a website, but can greatly enhance its readability, robustness, and conciseness • Always look for opportunities to bundle PHP code into a function, especially in cases where it might be reused • Try to keep function definitions short. If it gets too long, think about breaking it up into multiple functions • Always load/write all of your functions prior to calling them • For frequently-used functions, function groups, or common text (e.g. HTML headers/footers) or variable & constant definitions, store them in a separate file(s) which gets included at the beginning of each of your programs.

  19. Robustness • The two commandments (Moses broke the other 8) of robustness are: • Code should detect unexpected situations and respond gracefully rather than dying • If code must die, better that it die informatively • Robustness can be enhanced through the utilization of functions for common code which may result in a high number of failures due to user input, resource availability, etc. by performing tests on the requests within the function which would then be called every time the input is received or the resource is requested • set_error_handler() is a new feature in PHP 4 which allows the programmer to intercept arbitrary errors and specify a function that decides how to handle them • All user input should always be checked and converted to the appropriate type or string to ensure that it is within the bounds of your application

  20. Conciseness and Efficiency • Concise code accomplishes a given task in the smallest number of lines or keystrokes • Efficient code runs using a small amount of execution time or system resources (e.g. RAM) • Don't reinvent the wheel: don't rewrite code that duplicates a language-level facility (e.g. use the languages sort instead of writing your own) • Discover the bottleneck: 90% of the application's time is usually spent in 10% of the code. Use microtime() to find the slow code • Focus on DB queries: usually the biggest time sink for PHP sites with DB back ends • Focus on the innermost loop: they will be executed the most frequently and would get the greatest gain from optimization

  21. Conciseness: the downside • Conciseness rarely implies efficiency • Eliminating characters from your code (e.g. variable names, etc.) will result in no gains in the execution time of your application • Conciseness usually trades off with readability • Each keystroke you omit might be the one that would have let someone figure out what the heck you were thinking when you wrote the code

  22. Conciseness tips • Use return values and side effects at the same time while ($row = mysql_fetch_array($query_handle)) print($row['id_num']."<BR>\n"); • Be wary of using the assignment operator (=) in a boolean expression. Usually, the equality operator (==) is what was intended, but not always (as in the example above) • Use unary increment and assignment operators • ++, --, +=, *=, .=, etc. • Reuse functions • Not only more concise, but makes maintenance much easier • Use short-circuiting boolean expressions • Be especially wary of the order of execution

  23. Separating code from design • Templates and page consistency • Use PHP to load consistent navigation and page formatting HTML constructs • Use a PHP template system (e.g. YATS - Yet Another Template System located at http://yats.sourceforge.net) • Create web page classes (using OOP techniques) to layout your page design and then each web page would create an instance of the base or sub-class which would then add in the specific content and also could modify the specifics of the navigation, etc.

More Related