Programming PHP

Book description

PHP is a simple yet powerful open-source scripting language for creating dynamic web content. The millions of web sites powered by PHP are testament to its popularity and ease of use. PHP is used by both programmers, who appreciate its flexibility and speed, and web designers, who value its accessibility and convenience. Programming PHP is an authoritative guide to PHP 4 and is filled with the unique knowledge of the creator of PHP, Rasmus Lerdorf. This book explains PHP language syntax and programming techniques in a clear and concise manner, with numerous examples that illustrate both correct usage and common idioms. The book also includes style tips and practical programming advice that will help you become not just a PHP programmer, but a good PHP programmer. Programming PHP covers everything you need to know to create effective web applications with PHP. Contents include:

  • Detailed information on the basics of the PHP language, including data types, variables, operators, and flow control statements

  • Separate chapters on the fundamental topics of functions, strings, arrays, and objects

  • Coverage of common PHP web application techniques, such as form processing and validation, session tracking, and cookies

  • Material on interacting with relational databases, such as MySQL and Oracle, using the database-independent PEAR DB library

  • Chapters on generating dynamic images, creating PDF files, and parsing XML files with PHP

  • Advanced topics, like creating secure script, error handling, performance tuning, and writing your own C language extensions to PHP

  • A handy quick reference to all the core functions in PHP and all the standard extensions that ship with PHP

  • Table of contents

    1. Programming PHP
      1. Preface
        1. Audience for This Book
        2. Structure of This Book
        3. Conventions Used in This Book
        4. Comments and Questions
        5. Acknowledgments
          1. Rasmus Lerdorf
          2. Kevin Tatroe
          3. Bob Kaehms
          4. Ric McGredy
      2. 1. Introduction to PHP
        1. What Does PHP Do?
        2. A Brief History of PHP
          1. The Evolution of PHP
          2. The Growth of PHP
        3. Installing PHP
        4. A Walk Through PHP
          1. Configuration Page
          2. Forms
          3. Databases
          4. Graphics
          5. From the Shell
      3. 2. Language Basics
        1. Lexical Structure
          1. Case Sensitivity
          2. Statements and Semicolons
          3. Whitespace and Line Breaks
          4. Comments
            1. Shell-style comments
            2. C++ comments
            3. C comments
          5. Literals
          6. Identifiers
            1. Variable names
            2. Function names
            3. Class names
            4. Constants
          7. Keywords
        2. Data Types
          1. Integers
          2. Floating-Point Numbers
          3. Strings
          4. Booleans
          5. Arrays
          6. Objects
          7. Resources
          8. NULL
        3. Variables
          1. Variable Variables
          2. Variable References
          3. Variable Scope
            1. Local scope
            2. Global scope
            3. Static variables
            4. Function parameters
          4. Garbage Collection
        4. Expressions and Operators
          1. Number of Operands
          2. Operator Precedence
          3. Operator Associativity
          4. Implicit Casting
          5. Arithmetic Operators
          6. String Concatenation Operator
          7. Autoincrement and Autodecrement Operators
          8. Comparison Operators
          9. Bitwise Operators
          10. Logical Operators
          11. Casting Operators
          12. Assignment Operators
            1. Assignment
            2. Assignment with operation
          13. Miscellaneous Operators
        5. Flow-Control Statements
          1. if
          2. switch
          3. while
          4. for
          5. foreach
          6. declare
          7. exit and return
        6. Including Code
        7. Embedding PHP in Web Pages
          1. XML Style
          2. SGML Style
          3. ASP Style
          4. Script Style
          5. Echoing Content Directly
      4. 3. Functions
        1. Calling a Function
        2. Defining a Function
        3. Variable Scope
          1. Global Variables
          2. Static Variables
        4. Function Parameters
          1. Passing Parameters by Value
          2. Passing Parameters by Reference
          3. Default Parameters
          4. Variable Parameters
          5. Missing Parameters
        5. Return Values
        6. Variable Functions
        7. Anonymous Functions
      5. 4. Strings
        1. Quoting String Constants
          1. Variable Interpolation
          2. Single-Quoted Strings
          3. Double-Quoted Strings
          4. Here Documents
        2. Printing Strings
          1. echo
          2. print( )
          3. printf( )
            1. Format modifiers
            2. Type specifiers
          4. print_r( ) and var_dump( )
        3. Accessing Individual Characters
        4. Cleaning Strings
          1. Removing Whitespace
          2. Changing Case
        5. Encoding and Escaping
          1. HTML
            1. Entity-quoting all special characters
            2. Entity-quoting only HTML syntax characters
            3. Removing HTML tags
            4. Extracting meta tags
          2. URLs
            1. RFC 1738 encoding and decoding
            2. Query-string encoding
          3. SQL
          4. C-String Encoding
        6. Comparing Strings
          1. Exact Comparisons
          2. Approximate Equality
        7. Manipulating and Searching Strings
          1. Substrings
          2. Miscellaneous String Functions
          3. Decomposing a String
            1. Exploding and imploding
            2. Tokenizing
            3. sscanf( )
          4. String-Searching Functions
            1. Searches returning position
            2. Searches returning rest of string
            3. Searches using masks
            4. Decomposing URLs
        8. Regular Expressions
          1. The Basics
          2. Character Classes
          3. Alternatives
          4. Repeating Sequences
          5. Subpatterns
        9. POSIX-Style Regular Expressions
          1. Character Classes
          2. Anchors
          3. Functions
            1. Matching
            2. Replacing
            3. Splitting
        10. Perl-Compatible Regular Expressions
          1. Delimiters
          2. Match Behavior
          3. Character Classes
          4. Anchors
          5. Quantifiers and Greed
          6. Non-Capturing Groups
          7. Backreferences
          8. Trailing Options
          9. Inline Options
          10. Lookahead and Lookbehind
          11. Cut
          12. Conditional Expressions
          13. Functions
            1. Matching
            2. Replacing
            3. Splitting
            4. Filtering an array with a regular expression
            5. Quoting for regular expressions
          14. Differences from Perl Regular Expressions
      6. 5. Arrays
        1. Indexed Versus Associative Arrays
        2. Identifying Elements of an Array
        3. Storing Data in Arrays
          1. Adding Values to the End of an Array
          2. Assigning a Range of Values
          3. Getting the Size of an Array
          4. Padding an Array
        4. Multidimensional Arrays
        5. Extracting Multiple Values
          1. Slicing an Array
          2. Splitting an Array into Chunks
          3. Keys and Values
          4. Checking Whether an Element Exists
          5. Removing and Inserting Elements in an Array
        6. Converting Between Arrays and Variables
          1. Creating Variables from an Array
          2. Creating an Array from Variables
        7. Traversing Arrays
          1. The foreach Construct
          2. The Iterator Functions
          3. Using a for Loop
          4. Calling a Function for Each Array Element
          5. Reducing an Array
          6. Searching for Values
        8. Sorting
          1. Sorting One Array at a Time
          2. Natural-Order Sorting
          3. Sorting Multiple Arrays at Once
          4. Reversing Arrays
          5. Randomizing Order
        9. Acting on Entire Arrays
          1. Calculating the Sum of an Array
          2. Merging Two Arrays
          3. Calculating the Difference Between Two Arrays
          4. Filtering Elements from an Array
        10. Using Arrays
          1. Sets
          2. Stacks
      7. 6. Objects
        1. Terminology
        2. Creating an Object
        3. Accessing Properties and Methods
        4. Declaring a Class
          1. Declaring Methods
          2. Declaring Properties
          3. Inheritance
          4. Constructors
          5. References
        5. Introspection
          1. Examining Classes
          2. Examining an Object
          3. Sample Introspection Program
        6. Serialization
      8. 7. Web Techniques
        1. HTTP Basics
        2. Variables
        3. Server Information
        4. Processing Forms
          1. Methods
          2. Parameters
          3. Automatic Quoting of Parameters
          4. Self-Processing Pages
          5. Sticky Forms
          6. Multivalued Parameters
          7. Sticky Multivalued Parameters
          8. File Uploads
          9. Form Validation
        5. Setting Response Headers
          1. Different Content Types
          2. Redirections
          3. Expiration
          4. Authentication
        6. Maintaining State
          1. Cookies
          2. Sessions
            1. Session basics
            2. Alternatives to cookies
            3. Custom storage
          3. Combining Cookies and Sessions
        7. SSL
      9. 8. Databases
        1. Using PHP to Access a Database
        2. Relational Databases and SQL
        3. PEAR DB Basics
          1. Data Source Names
          2. Connecting
          3. Error Checking
          4. Issuing a Query
          5. Fetching Results from a Query
            1. Returning the row
            2. Storing the row
            3. Inside a row array
            4. Finishing the result
          6. Disconnecting
        4. Advanced Database Techniques
          1. Placeholders
          2. Prepare/Execute
          3. Shortcuts
          4. Details About a Query Response
          5. Sequences
          6. Metadata
          7. Transactions
        5. Sample Application
          1. Database Tables
          2. Database Connection
          3. Administrator’s Page
          4. Adding a Business
          5. Displaying the Database
      10. 9. Graphics
        1. Embedding an Image in a Page
        2. The GD Extension
        3. Basic Graphics Concepts
        4. Creating and Drawing Images
          1. The Structure of a Graphics Program
          2. Changing the Output Format
          3. Testing for Supported Image Formats
          4. Reading an Existing File
          5. Basic Drawing Functions
        5. Images with Text
          1. Fonts
          2. TrueType Fonts
        6. Dynamically Generated Buttons
          1. Caching the Dynamically Generated Buttons
          2. A Faster Cache
        7. Scaling Images
        8. Color Handling
          1. Using the Alpha Channel
          2. Identifying Colors
          3. True Color Color Indexes
          4. Text Representation of an Image
      11. 10. PDF
        1. PDF Extensions
        2. Documents and Pages
          1. A Simple Example
          2. Initializing the Document
          3. Setting Metadata
          4. Creating a Page
          5. Outputting Basic Text
          6. Terminating and Streaming a PDF Document
        3. Text
          1. Coordinates
          2. Text Functions
          3. Text Attributes
          4. Fonts
          5. Embedding Fonts
        4. Images and Graphics
          1. Images
          2. Graphics
          3. Patterns
          4. Templates
        5. Navigation
          1. Bookmarks and Thumbnails
          2. Links
        6. Other PDF Features
          1. Note Annotations
          2. Attaching Files to a PDF Document
          3. Page Transitions
      12. 11. XML
        1. Lightning Guide to XML
        2. Generating XML
        3. Parsing XML
          1. Element Handlers
          2. Character Data Handler
          3. Processing Instructions
          4. Entity Handlers
            1. External entities
            2. Unparsed entities
          5. Default Handler
          6. Options
            1. Character encoding
            2. Case folding
          7. Using the Parser
          8. Errors
          9. Methods as Handlers
          10. Sample Parsing Application
        4. Transforming XML with XSLT
        5. Web Services
          1. Servers
          2. Clients
      13. 12. Security
        1. Global Variables and Form Data
          1. Initialize Variables
          2. Set variables_order
        2. Filenames
          1. Check for Relative Paths
          2. Restrict Filesystem Access to a Specific Directory
        3. File Uploads
          1. Distrust Browser-Supplied Filenames
          2. Beware of Filling Your Filesystem
          3. Surviving register_globals
        4. File Permissions
          1. Get It Right the First Time
          2. Session Files
          3. Don’t Use Files
          4. Safe Mode
        5. Concealing PHP Libraries
        6. PHP Code
        7. Shell Commands
        8. Security Redux
      14. 13. Application Techniques
        1. Code Libraries
        2. Templating Systems
        3. Handling Output
          1. Output Buffering
          2. Compressing Output
        4. Error Handling
          1. Error Reporting
          2. Error Suppression
          3. Triggering Errors
          4. Defining Error Handlers
            1. Logging in error handlers
            2. Output buffering in error handlers
        5. Performance Tuning
          1. Benchmarking
          2. Profiling
          3. Optimizing Execution Time
          4. Optimizing Memory Requirements
          5. Reverse Proxies and Replication
            1. Reverse-proxy cache
            2. Load balancing and redirection
            3. MySQL replication
            4. Putting it all together
      15. 14. Extending PHP
        1. Architectural Overview
        2. What You’ll Need
          1. The PHP Source
          2. Software Tools
        3. Building Your First Extensions
          1. Command-Line PHP
          2. Planning Your Extension
          3. Creating a Skeleton Extension
          4. Fleshing Out the Skeleton
          5. Compiling Your Extension
            1. Standalone extensions
            2. Compiling the extension into PHP
          6. Testing Your Extension
        4. The config.m4 File
          1. No External Dependencies
          2. External Dependencies
        5. Memory Management
        6. The pval/zval Data Type
          1. MAKE_STD_ZVAL( )
          2. SEPARATE_ZVAL( )
          3. zval_copy_ctor( )
          4. Accessor Macros
        7. Parameter Handling
          1. A Simple Example
          2. A More Complex Example
          3. An Example with Variable Argument List
        8. Returning Values
          1. Simple Types
          2. Arrays
          3. Objects
        9. References
        10. Global Variables
          1. SAPI Globals (SG)
          2. Executor Globals (EG)
          3. Internal Extension Globals
        11. Creating Variables
        12. Extension INI Entries
        13. Resources
        14. Where to Go from Here
      16. 15. PHP on Windows
        1. Installing and Configuring PHP on Windows
          1. Going Straight to the Source
          2. Configuring PHP with a Web Server
            1. Configuration common to all Microsoft installations
            2. Using the PHP installer to automatically configure PHP
            3. Manually configuring PWS
            4. Manually configuring Apache
            5. Other installers and prepackaged distributions
          3. Adding Extensions to the Base Distribution
        2. Writing Portable Code for Windows and Unix
          1. Determining the Platform
          2. Handling Paths Across Platforms
          3. The Environment
          4. Sending Mail
          5. Server-Specific Functions
          6. Remote Files
          7. End-of-Line Handling
          8. End-of-File Handling
          9. External Commands
          10. Common Platform-Specific Extensions
        3. Interfacing with COM
          1. Background
          2. PHP Functions
          3. Determining the API
          4. Completing a Word Document
          5. Reading and Writing Excel Files
        4. Interacting with ODBC Data Sources
          1. Configuring a DSN
          2. Accessing Excel Data
          3. Limitations of Excel as a Database
          4. Working with Access
      17. A. Function Reference
        1. PHP Functions by Category
        2. Alphabetical Listing of PHP Functions (a-e)
          1. abs
          2. acos
          3. addcslashes
          4. addslashes
          5. array
          6. array_count_values
          7. array_diff
          8. array_filter
          9. array_flip
          10. array_intersect
          11. array_keys
          12. array_map
          13. array_merge
          14. array_merge_recursive
          15. array_multisort
          16. array_pad
          17. array_pop
          18. array_push
          19. array_rand
          20. array_reduce
          21. array_reverse
          22. array_search
          23. array_shift
          24. array_slice
          25. array_splice
          26. array_sum
          27. array_unique
          28. array_unshift
          29. array_values
          30. array_walk
          31. arsort
          32. asin
          33. asort
          34. assert
          35. assert_options
          36. atan
          37. atan2
          38. base64_decode
          39. base64_encode
          40. base_convert
          41. basename
          42. bin2hex
          43. bindec
          44. call_user_func
          45. call_user_func_array
          46. call_user_method
          47. call_user_method_array
          48. ceil
          49. chdir
          50. checkdate
          51. checkdnsrr
          52. chgrp
          53. chmod
          54. chop
          55. chown
          56. chr
          57. chroot
          58. chunk_split
          59. class_exists
          60. clearstatcache
          61. closedir
          62. closelog
          63. compact
          64. convert_cyr_string
          65. copy
          66. cos
          67. count
          68. count_chars
          69. crc32
          70. create_function
          71. crypt
          72. current
          73. date
          74. decbin
          75. dechex
          76. decoct
          77. define_syslog_variables
          78. deg2rad
          79. dirname
          80. disk_free_space
          81. disk_total_space
          82. dl
          83. doubleval
          84. each
          85. echo
          86. empty
          87. end
          88. ereg
          89. ereg_replace
          90. eregi
          91. eregi_replace
          92. error_log
          93. error_reporting
          94. escapeshellarg
          95. escapeshellcmd
          96. exec
          97. exp
          98. explode
          99. extension_loaded
          100. extract
        3. Alphabetical Listing of PHP Functions (f-i)
          1. fclose
          2. feof
          3. fflush
          4. fgetc
          5. fgetcsv
          6. fgets
          7. fgetss
          8. file
          9. file_exists
          10. fileatime
          11. filectime
          12. filegroup
          13. fileinode
          14. filemtime
          15. fileowner
          16. fileperms
          17. filesize
          18. filetype
          19. flock
          20. floor
          21. flush
          22. fopen
          23. fpassthru
          24. fputs
          25. fread
          26. fscanf
          27. fseek
          28. fsockopen
          29. fstat
          30. ftell
          31. ftruncate
          32. func_get_arg
          33. func_get_args
          34. func_num_args
          35. function_exists
          36. fwrite
          37. get_browser
          38. get_cfg_var
          39. get_class
          40. get_class_methods
          41. get_class_vars
          42. get_current_user
          43. get_declared_classes
          44. get_defined_constants
          45. get_defined_functions
          46. get_defined_vars
          47. get_extension_funcs
          48. get_html_translation_table
          49. get_included_files
          50. get_loaded_extensions
          51. get_magic_quotes_gpc
          52. get_meta_tags
          53. get_object_vars
          54. get_parent_class
          55. get_required_files
          56. get_resource_type
          57. getcwd
          58. getdate
          59. getenv
          60. gethostbyaddr
          61. gethostbyname
          62. gethostbynamel
          63. getlastmod
          64. getmxrr
          65. getmyinode
          66. getmypid
          67. getprotobyname
          68. getprotobynumber
          69. getrandmax
          70. getrusage
          71. getservbyname
          72. getservbyport
          73. gettimeofday
          74. gettype
          75. gmdate
          76. gmmktime
          77. gmstrftime
          78. header
          79. headers_sent
          80. hebrev
          81. hebrevc
          82. highlight_file
          83. highlight_string
          84. hexdec
          85. htmlentities
          86. htmlspecialchars
          87. ignore_user_abort
          88. implode
          89. import_request_variables
          90. in_array
          91. ini_alter
          92. ini_get
          93. ini_restore
          94. ini_set
          95. intval
          96. ip2long
          97. iptcparse
          98. is_array
          99. is_bool
          100. is_dir
          101. is_double
          102. is_executable
          103. is_file
          104. is_float
          105. is_int
          106. is_integer
          107. is_link
          108. is_long
          109. is_null
          110. is_numeric
          111. is_object
          112. is_readable
          113. is_real
          114. is_resource
          115. is_scalar
          116. is_string
          117. is_subclass_of
          118. is_uploaded_file
          119. is_writable
          120. is_writeable
          121. isset
        4. Alphabetical Listing of PHP Functions (j-q)
          1. join
          2. key
          3. key_exists
          4. krsort
          5. ksort
          6. lcg_value
          7. levenshtein
          8. link
          9. linkinfo
          10. list
          11. localeconv
          12. localtime
          13. log
          14. log10
          15. long2ip
          16. lstat
          17. ltrim
          18. mail
          19. max
          20. md5
          21. metaphone
          22. method_exists
          23. microtime
          24. min
          25. mkdir
          26. mktime
          27. move_uploaded_file
          28. mt_getrandmax
          29. mt_rand
          30. mt_srand
          31. natcasesort
          32. natsort
          33. next
          34. nl2br
          35. number_format
          36. ob_end_clean
          37. ob_end_flush
          38. ob_get_contents
          39. ob_get_length
          40. ob_gzhandler
          41. ob_implicit_flush
          42. ob_start
          43. octdec
          44. opendir
          45. openlog
          46. ord
          47. pack
          48. parse_ini_file
          49. parse_str
          50. parse_url
          51. passthru
          52. pathinfo
          53. pclose
          54. pfsockopen
          55. php_logo_guid
          56. php_sapi_name
          57. php_uname
          58. phpcredits
          59. phpinfo
          60. phpversion
          61. pi
          62. popen
          63. pos
          64. pow
          65. prev
          66. print
          67. print_r
          68. printf
          69. putenv
          70. quoted_printable_decode
          71. quotemeta
        5. Alphabetical Listing of PHP Functions (r-z)
          1. rad2deg
          2. rand
          3. range
          4. rawurldecode
          5. rawurlencode
          6. readdir
          7. readfile
          8. readlink
          9. realpath
          10. register_shutdown_function
          11. register_tick_function
          12. rename
          13. reset
          14. restore_error_handler
          15. rewind
          16. rewinddir
          17. rmdir
          18. round
          19. rsort
          20. rtrim
          21. serialize
          22. set_error_handler
          23. set_file_buffer
          24. set_magic_quotes_runtime
          25. set_time_limit
          26. setcookie
          27. setlocale
          28. settype
          29. shell_exec
          30. shuffle
          31. similar_text
          32. sin
          33. sizeof
          34. sleep
          35. socket_get_status
          36. socket_set_blocking
          37. socket_set_timeout
          38. sort
          39. soundex
          40. split
          41. spliti
          42. sprintf
          43. sql_regcase
          44. sqrt
          45. srand
          46. sscanf
          47. stat
          48. str_pad
          49. str_repeat
          50. str_replace
          51. strcasecmp
          52. strchr
          53. strcmp
          54. strcoll
          55. strcspn
          56. strftime
          57. stripcslashes
          58. stripslashes
          59. strip_tags
          60. stristr
          61. strlen
          62. strnatcasecmp
          63. strnatcmp
          64. strncmp
          65. strpos
          66. strrchr
          67. strrev
          68. strrpos
          69. strspn
          70. strstr
          71. strtok
          72. strtolower
          73. strtotime
          74. strtoupper
          75. strtr
          76. strval
          77. substr
          78. substr_count
          79. substr_replace
          80. symlink
          81. syslog
          82. system
          83. tan
          84. tempnam
          85. time
          86. tmpfile
          87. touch
          88. trigger_error
          89. trim
          90. uasort
          91. ucfirst
          92. ucwords
          93. uksort
          94. umask
          95. uniqid
          96. unlink
          97. unpack
          98. unregister_tick_function
          99. unserialize
          100. unset
          101. urldecode
          102. urlencode
          103. user_error
          104. usleep
          105. usort
          106. var_dump
          107. version_compare
          108. vprintf
          109. vsprintf
          110. wordwrap
          111. zend_logo_guid
          112. zend_version
      18. B. Extension Overview
        1. Optional Extensions Listing
          1. Apache
          2. aspell
          3. BCMath Arbitrary Precision Mathematics
          4. bzip2 Compression
          5. Calendar
          6. CCVS
          7. clibpdf
          8. COM
          9. ctype
          10. CURL
          11. Cybercash
          12. CyberMUT
          13. dBase
          14. DBM
          15. DBM-Style Database Abstraction
          16. dbx
          17. DOM XML
          18. EXIF
          19. FDF
          20. filePro
          21. FriBiDi
          22. FTP
          23. gettext
          24. GMP
          25. Hyperwave
          26. ICAP
          27. iconv
          28. IMAP, POP3, and NNTP
          29. Informix
          30. Ingres II
          31. InterBase
          32. IRC Gateway
          33. Java
          34. Kerberos
          35. LDAP
          36. MCAL
          37. mcrypt
          38. mhash
          39. Microsoft SQL Server
          40. Ming
          41. mnoGoSearch
          42. mSQL
          43. MySQL
          44. ODBC
          45. Oracle
          46. OvrimosSQL
          47. pdflib
          48. Verisign Payflow Pro
          49. PostgreSQL
          50. pspell
          51. Readline
          52. Recode
          53. Satellite CORBA Client
          54. shmop
          55. SNMP
          56. sockets
          57. SWF
          58. Sybase
          59. System V Semaphore and Shared Memory
          60. vpopmail
          61. WDDX
          62. XML Parser
          63. XSLT
          64. YAZ
          65. YP/NIS
          66. ZIP Files
          67. zlib Compression
      19. Index
      20. Colophon

    Product information

    • Title: Programming PHP
    • Author(s):
    • Release date: March 2002
    • Publisher(s): O'Reilly Media, Inc.
    • ISBN: 9781565926103