Programming PHP, 3rd Edition

Book description

This updated edition teaches everything you need to know to create effective web applications with the latest features in PHP 5.x. You’ll start with the big picture and then dive into language syntax, programming techniques, and other details, using examples that illustrate both correct usage and common idioms.

If you have a working knowledge of HTML, the authors’ many style tips and practical programming advice will help you become a top-notch PHP programmer.

  • Get an overview of what’s possible with PHP programs
  • Learn language fundamentals, including data types, variables, operators, and flow control statements
  • Understand functions, strings, arrays, and objects
  • Apply common web application techniques, such as form processing, data validation, session tracking, and cookies
  • Interact with relational databases like MySQL or NoSQL databases such as MongoDB
  • Generate dynamic images, create PDF files, and parse XML files
  • Learn secure scripts, error handling, performance tuning, and other advanced topics
  • Get a quick reference to PHP core functions and standard extensions

Publisher resources

View/Submit Errata

Table of contents

  1. Programming PHP
  2. Dedication
  3. A Note Regarding Supplemental Files
  4. Foreword
  5. Preface
    1. Audience
    2. Assumptions This Book Makes
    3. Contents of This Book
    4. Conventions Used in This Book
    5. Using Code Examples
    6. Safari® Books Online
    7. How to Contact Us
    8. Acknowledgments
      1. Kevin Tatroe
      2. Peter MacIntyre
  6. 1. Introduction to PHP
    1. What Does PHP Do?
    2. A Brief History of PHP
      1. The Evolution of PHP
      2. The Widespread Use of PHP
    3. Installing PHP
    4. A Walk Through PHP
      1. Configuration Page
      2. Forms
      3. Databases
      4. Graphics
  7. 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. Callbacks
      9. 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. Auto-increment and Auto-decrement 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. try...catch
      7. declare
      8. exit and return
      9. goto
    6. Including Code
    7. Embedding PHP in Web Pages
      1. Standard (XML) Style
      2. SGML Style
      3. ASP Style
      4. Script Style
      5. Echoing Content Directly
  8. 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
      6. Type Hinting
    5. Return Values
    6. Variable Functions
    7. Anonymous Functions
  9. 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 3986 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
      6. Delimiters
      7. Match Behavior
      8. Character Classes
      9. Anchors
      10. Quantifiers and Greed
      11. Noncapturing Groups
      12. Backreferences
      13. Trailing Options
      14. Inline Options
      15. Lookahead and Lookbehind
      16. Cut
      17. Conditional Expressions
      18. Functions
        1. Matching
        2. Replacing
        3. Splitting
        4. Filtering an array with a regular expression
        5. Quoting for regular expressions
      19. Differences from Perl Regular Expressions
  10. 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
    11. Iterator Interface
  11. 6. Objects
    1. Terminology
    2. Creating an Object
    3. Accessing Properties and Methods
    4. Declaring a Class
      1. Declaring Methods
      2. Declaring Properties
      3. Declaring Constants
      4. Inheritance
      5. Interfaces
      6. Traits
      7. Abstract Methods
      8. Constructors
      9. Destructors
    5. Introspection
      1. Examining Classes
      2. Examining an Object
      3. Sample Introspection Program
    6. Serialization
  12. 7. Web Techniques
    1. HTTP Basics
    2. Variables
    3. Server Information
    4. Processing Forms
      1. Methods
      2. Parameters
      3. Self-Processing Pages
      4. Sticky Forms
      5. Multivalued Parameters
      6. Sticky Multivalued Parameters
      7. File Uploads
      8. 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
  13. 8. Databases
    1. Using PHP to Access a Database
    2. Relational Databases and SQL
      1. PHP Data Objects
        1. Making a connection
        2. Interaction with the database
        3. PDO and prepared statements
        4. Transactions
    3. MySQLi Object Interface
      1. Retrieving Data for Display
    4. SQLite
    5. Direct File-Level Manipulation
    6. MongoDB
      1. Retrieving Data
      2. Inserting More Complex Data
  14. 9. Graphics
    1. Embedding an Image in a Page
    2. Basic Graphics Concepts
    3. 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
    4. Images with Text
      1. Fonts
      2. TrueType Fonts
    5. Dynamically Generated Buttons
      1. Caching the Dynamically Generated Buttons
      2. A Faster Cache
    6. Scaling Images
    7. Color Handling
      1. Using the Alpha Channel
      2. Identifying Colors
      3. True Color Indexes
      4. Text Representation of an Image
  15. 10. PDF
    1. PDF Extensions
    2. Documents and Pages
      1. A Simple Example
      2. Initializing the Document
      3. Outputting Basic Text Cells
    3. Text
      1. Coordinates
      2. Text Attributes
      3. Page Headers, Footers, and Class Extension
      4. Images and Links
      5. Tables and Data
  16. 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. Parsing XML with DOM
    5. Parsing XML with SimpleXML
    6. Transforming XML with XSLT
  17. 12. Security
    1. Filter Input
    2. Cross-Site Scripting
      1. SQL Injection
    3. Escape Output
      1. Filenames
        1. Check for relative paths
    4. Session Fixation
    5. File Uploads
      1. Distrust Browser-Supplied Filenames
      2. Beware of Filling Your Filesystem
      3. Surviving register_globals
    6. File Access
      1. Restrict Filesystem Access to a Specific Directory
      2. Get It Right the First Time
      3. Don’t Use Files
      4. Session Files
      5. Concealing PHP Libraries
    7. PHP Code
    8. Shell Commands
    9. More Information
    10. Security Recap
  18. 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
  19. 14. PHP on Disparate Platforms
    1. Writing Portable Code for Windows and Unix
      1. Determining the Platform
      2. Handling Paths Across Platforms
      3. The Server Environment
      4. Sending Mail
      5. End-of-Line Handling
      6. End-of-File Handling
      7. External Commands
      8. Common Platform-Specific Extensions
    2. Interfacing with COM
      1. Background
      2. PHP Functions
      3. Determining the API
  20. 15. Web Services
    1. REST Clients
      1. Responses
      2. Retrieving Resources
      3. Updating Resources
      4. Creating Resources
      5. Deleting Resources
    2. XML-RPC
      1. Servers
      2. Clients
  21. 16. Debugging PHP
    1. The Development Environment
    2. The Staging Environment
    3. The Production Environment
    4. php.ini Settings
    5. Manual Debugging
    6. Error Log
    7. IDE Debugging
    8. Additional Debugging Techniques
  22. 17. Dates and Times
  23. A. Function Reference
    1. PHP Functions by Category
      1. Arrays
      2. Classes and Objects
      3. Date and Time
      4. Directories
      5. Errors and Logging
      6. Program Execution
      7. Filesystem
      8. Data Filtering
      9. Functions
      10. PHP Options/Info
      11. Mail
      12. Math
      13. Miscellaneous Functions
      14. Network
      15. Output Buffering
      16. Session Handling
      17. Streams
      18. Strings
      19. PHP Language Tokenizer
      20. URLs
      21. Variables
    2. Alphabetical Listing of PHP Functions
      1. abs
      2. acos
      3. acosh
      4. addcslashes
      5. addslashes
      6. array_change_key_case
      7. array_chunk
      8. array_combine
      9. array_count_values
      10. array_diff
      11. array_diff_assoc
      12. array_diff_key
      13. array_diff_uassoc
      14. array_diff_ukey
      15. array_fill
      16. array_fill_keys
      17. array_filter
      18. array_flip
      19. array_intersect
      20. array_intersect_assoc
      21. array_intersect_key
      22. array_intersect_uassoc
      23. array_intersect_ukey
      24. array_key_exists
      25. array_keys
      26. array_map
      27. array_merge
      28. array_merge_recursive
      29. array_multisort
      30. array_pad
      31. array_pop
      32. array_product
      33. array_push
      34. array_rand
      35. array_reduce
      36. array_replace
      37. array_replace_recursive
      38. array_reverse
      39. array_search
      40. array_shift
      41. array_slice
      42. array_splice
      43. array_sum
      44. array_udiff
      45. array_udiff_assoc
      46. array_udiff_uassoc
      47. array_uintersect
      48. array_uintersect_assoc
      49. array_uintersect_uassoc
      50. array_unique
      51. array_unshift
      52. array_values
      53. array_walk
      54. array_walk_recursive
      55. arsort
      56. asin
      57. asinh
      58. asort
      59. assert
      60. assert_options
      61. atan
      62. atan2
      63. atanh
      64. base_convert
      65. base64_decode
      66. base64_encode
      67. basename
      68. bin2hex
      69. bindec
      70. call_user_func
      71. call_user_func_array
      72. ceil
      73. chdir
      74. checkdate
      75. checkdnsrr
      76. chgrp
      77. chmod
      78. chown
      79. chr
      80. chroot
      81. chunk_split
      82. class_alias
      83. class_exists
      84. class_implements
      85. class_parents
      86. clearstatcache
      87. closedir
      88. closelog
      89. compact
      90. connection_aborted
      91. connection_status
      92. constant
      93. convert_cyr_string
      94. convert_uudecode
      95. convert_uuencode
      96. copy
      97. cos
      98. cosh
      99. count
      100. count_chars
      101. crc32
      102. create_function
      103. crypt
      104. current
      105. date
      106. date_default_timezone_set
      107. date_default_timezone_get
      108. date_parse
      109. date_parse_from_format
      110. date_sun_info
      111. date_sunrise
      112. date_sunset
      113. debug_backtrace
      114. debug_print_backtrace
      115. decbin
      116. dechex
      117. decoct
      118. define
      119. define_syslog_variables
      120. defined
      121. deg2rad
      122. dir
      123. dirname
      124. disk_free_space
      125. disk_total_space
      126. each
      127. echo
      128. empty
      129. end
      130. error_get_last
      131. error_log
      132. error_reporting
      133. escapeshellarg
      134. escapeshellcmd
      135. exec
      136. exp
      137. explode
      138. expm1
      139. extension_loaded
      140. extract
      141. fclose
      142. feof
      143. fflush
      144. fgetc
      145. fgetcsv
      146. fgets
      147. fgetss
      148. file
      149. file_exists
      150. fileatime
      151. filectime
      152. file_get_contents
      153. filegroup
      154. fileinode
      155. filemtime
      156. fileowner
      157. fileperms
      158. file_put_contents
      159. filesize
      160. filetype
      161. filter_has_var
      162. filter_id
      163. filter_input
      164. filter_input_array
      165. filter_list
      166. filter_var
      167. filter_var_array
      168. floatval
      169. flock
      170. floor
      171. flush
      172. fmod
      173. fnmatch
      174. fopen
      175. forward_static_call
      176. forward_static_call_array
      177. fpassthru
      178. fprintf
      179. fputcsv
      180. fread
      181. fscanf
      182. fseek
      183. fsockopen
      184. fstat
      185. ftell
      186. ftruncate
      187. func_get_arg
      188. func_get_args
      189. func_num_args
      190. function_exists
      191. fwrite
      192. gc_collect_cycles
      193. gc_disable
      194. gc_enable
      195. gc_enabled
      196. get_browser
      197. get_called_class
      198. get_cfg_var
      199. get_class
      200. get_class_methods
      201. get_class_vars
      202. get_current_user
      203. get_declared_classes
      204. get_declared_interfaces
      205. get_declared_traits
      206. get_defined_constants
      207. get_defined_functions
      208. get_defined_vars
      209. get_extension_funcs
      210. get_headers
      211. get_html_translation_table
      212. get_included_files
      213. get_include_path
      214. get_loaded_extensions
      215. get_meta_tags
      216. getmygid
      217. getmyuid
      218. get_object_vars
      219. get_parent_class
      220. get_resource_type
      221. getcwd
      222. getdate
      223. getenv
      224. gethostbyaddr
      225. gethostbyname
      226. gethostbynamel
      227. gethostname
      228. getlastmod
      229. getmxrr
      230. getmyinode
      231. getmypid
      232. getopt
      233. getprotobyname
      234. getprotobynumber
      235. getrandmax
      236. getrusage
      237. getservbyname
      238. getservbyport
      239. gettimeofday
      240. gettype
      241. glob
      242. gmdate
      243. gmmktime
      244. gmstrftime
      245. header
      246. header_remove
      247. headers_list
      248. headers_sent
      249. hebrev
      250. hebrevc
      251. hex2bin
      252. hexdec
      253. highlight_file
      254. highlight_string
      255. htmlentities
      256. html_entity_decode
      257. htmlspecialchars
      258. htmlspecialchars_decode
      259. http_build_query
      260. hypot
      261. idate
      262. ignore_user_abort
      263. implode
      264. inet_ntop
      265. inet_pton
      266. in_array
      267. ini_get
      268. ini_get_all
      269. ini_restore
      270. ini_set
      271. interface_exists
      272. intval
      273. ip2long
      274. is_a
      275. is_array
      276. is_bool
      277. is_callable
      278. is_dir
      279. is_executable
      280. is_file
      281. is_finite
      282. is_float
      283. is_infinite
      284. is_int
      285. is_link
      286. is_nan
      287. is_null
      288. is_numeric
      289. is_object
      290. is_readable
      291. is_resource
      292. is_scalar
      293. is_string
      294. is_subclass_of
      295. is_uploaded_file
      296. is_writable
      297. isset
      298. key
      299. krsort
      300. ksort
      301. lcfirst
      302. lcg_value
      303. lchgrp
      304. lchown
      305. levenshtein
      306. link
      307. linkinfo
      308. list
      309. localeconv
      310. localtime
      311. log
      312. log10
      313. log1p
      314. long2ip
      315. lstat
      316. ltrim
      317. mail
      318. max
      319. md5
      320. md5_file
      321. memory_get_peak_usage
      322. memory_get_usage
      323. metaphone
      324. method_exists
      325. microtime
      326. min
      327. mkdir
      328. mktime
      329. money_format
      330. move_uploaded_file
      331. mt_getrandmax
      332. mt_rand
      333. mt_srand
      334. natcasesort
      335. natsort
      336. next
      337. nl_langinfo
      338. nl2br
      339. number_format
      340. ob_clean
      341. ob_end_clean
      342. ob_end_flush
      343. ob_flush
      344. ob_get_clean
      345. ob_get_contents
      346. ob_get_flush
      347. ob_get_length
      348. ob_get_level
      349. ob_get_status
      350. ob_gzhandler
      351. ob_implicit_flush
      352. ob_list_handlers
      353. ob_start
      354. octdec
      355. opendir
      356. openlog
      357. ord
      358. output_add_rewrite_var
      359. output_reset_rewrite_vars
      360. pack
      361. parse_ini_file
      362. parse_ini_string
      363. parse_str
      364. parse_url
      365. passthru
      366. pathinfo
      367. pclose
      368. pfsockopen
      369. php_ini_loaded_file
      370. php_ini_scanned_files
      371. php_logo_guid
      372. php_sapi_name
      373. php_strip_whitespace
      374. php_uname
      375. phpcredits
      376. phpinfo
      377. phpversion
      378. pi
      379. popen
      380. pow
      381. prev
      382. print_r
      383. printf
      384. proc_close
      385. proc_get_status
      386. proc_nice
      387. proc_open
      388. proc_terminate
      389. property_exists
      390. putenv
      391. quoted_printable_decode
      392. quoted_printable_encode
      393. quotemeta
      394. rad2deg
      395. rand
      396. range
      397. rawurldecode
      398. rawurlencode
      399. readdir
      400. readfile
      401. readlink
      402. realpath
      403. realpath_cache_get
      404. realpath_cache_size
      405. register_shutdown_function
      406. register_tick_function
      407. rename
      408. reset
      409. restore_error_handler
      410. restore_exception_handler
      411. restore_include_path
      412. rewind
      413. rewinddir
      414. rmdir
      415. round
      416. rsort
      417. rtrim
      418. scandir
      419. serialize
      420. set_error_handler
      421. set_exception_handler
      422. set_include_path
      423. set_time_limit
      424. setcookie
      425. setlocale
      426. setrawcookie
      427. settype
      428. sha1
      429. sha1_file
      430. shell_exec
      431. shuffle
      432. similar_text
      433. sin
      434. sinh
      435. sleep
      436. sort
      437. soundex
      438. sprintf
      439. sqrt
      440. srand
      441. sscanf
      442. stat
      443. str_getcsv
      444. str_ireplace
      445. str_pad
      446. str_repeat
      447. str_replace
      448. str_rot13
      449. str_shuffle
      450. str_split
      451. str_word_count
      452. strcasecmp
      453. strcmp
      454. strcoll
      455. strcspn
      456. strftime
      457. stripcslashes
      458. stripslashes
      459. strip_tags
      460. stripos
      461. stristr
      462. strlen
      463. strnatcasecmp
      464. strnatcmp
      465. strncasecmp
      466. strncmp
      467. strpbrk
      468. strpos
      469. strptime
      470. strrchr
      471. strrev
      472. strripos
      473. strrpos
      474. strspn
      475. strstr
      476. strtok
      477. strtolower
      478. strtotime
      479. strtoupper
      480. strtr
      481. strval
      482. substr
      483. substr_compare
      484. substr_count
      485. substr_replace
      486. symlink
      487. syslog
      488. system
      489. sys_getloadavg
      490. sys_get_temp_dir
      491. tan
      492. tanh
      493. tempnam
      494. time
      495. time_nanosleep
      496. time_sleep_until
      497. timezone_name_from_abbr
      498. timezone_version_get
      499. tmpfile
      500. token_get_all
      501. token_name
      502. touch
      503. trait_exists
      504. trigger_error
      505. trim
      506. uasort
      507. ucfirst
      508. ucwords
      509. uksort
      510. umask
      511. uniqid
      512. unlink
      513. unpack
      514. unregister_tick_function
      515. unserialize
      516. unset
      517. urldecode
      518. urlencode
      519. usleep
      520. usort
      521. var_dump
      522. var_export
      523. version_compare
      524. vfprintf
      525. vprintf
      526. vsprintf
      527. wordwrap
      528. zend_logo_guid
      529. zend_thread_id
      530. zend_version
  24. Index
  25. About the Authors
  26. Colophon
  27. Copyright

Product information

  • Title: Programming PHP, 3rd Edition
  • Author(s): Rasmus Lerdorf, Kevin Tatroe, Peter MacIntyre
  • Release date: February 2013
  • Publisher(s): O'Reilly Media, Inc.
  • ISBN: 9781449392772