Extending and Embedding PHP By Sara Golemon Publisher: Sams Pub Date: May 30, 2006 Print ISBN-10: 0-672-32704-X Print ISBN-13: 978-0-672-32704-9 Pages: 456 Table of Contents | Index In just a few years PHP has rapidly evolved from a small niche language to a powerful web development tool Now in use on over 14 million Web sites, PHP is more stable and extensible than ever However, there is no documentation on how to extend PHP; developers seeking to build PHP extensions and increase the performance and functionality of their PHP applications are left to word of mouth and muddling through PHP internals without systematic, helpful guidance Although the basics of extension writing are fairly easy to grasp, the more advanced features have a tougher learning curve that can be very difficult to overcome This is common at any moderate to high-traffic site, forcing the company hire talented, and high-priced, developers to increase performance With Extending and Embedding PHP, Sara Golemon makes writing extensions within the grasp of every PHP developer, while guiding the reader through the tricky internals of PHP Extending and Embedding PHP By Sara Golemon Publisher: Sams Pub Date: May 30, 2006 Print ISBN-10: 0-672-32704-X Print ISBN-13: 978-0-672-32704-9 Pages: 456 Table of Contents | Index Copyright Foreword About the Author We Want to Hear from You! Reader Services Introduction Chapter 1 The PHP Life Cycle It All Starts with the SAPI Starting Up and Shutting Down Life Cycles Zend Thread Safety Summary Chapter 2 Variables from the Inside Out Data Types Data Values Data Creation Data Storage Data Retrieval Data Conversion Summary Chapter 3 Memory Management Memory Reference Counting Summary Chapter 4 Setting Up a Build Environment Building PHP Configuring PHP for Development Compiling on UNIX Compiling on Win32 Summary Chapter 5 Your First Extension Anatomy of an Extension Building Your First Extension Building Statically Functional Functions Summary Chapter 6 Returning Values The return_value Variable Returning Values by Reference Summary Chapter 7 Accepting Parameters Automatic Type Conversion with zend_parse_parameters() Arg Info and Type-hinting Summary Chapter 8 Working with Arrays and HashTables Vectors Versus Linked Lists Zend Hash API zval* Array API Summary Chapter 9 The Resource Data Type Complex Structures Persistent Resources The Other refcounter Summary Chapter 10 PHP4 Objects The Evolution of the PHP Object Type Implementing Classes Working with Instances Summary Chapter 11 PHP5 Objects Evolutionary Leaps Methods Properties Interfaces Handlers Summary Chapter 12 Startup, Shutdown, and a Few Points in Between Cycles Exposing Information Through MINFO Constants Extension Globals Userspace Superglobals Summary Chapter 13 INI Settings Declaring and Accessing INI Settings Summary Chapter 14 Accessing Streams Streams Overview Opening Streams Accessing Streams Static Stream Operations Summary Chapter 15 Implementing Streams PHP Streams Below the Surface Wrapper Operations Implementing a Wrapper Manipulation Inspection Summary Chapter 16 Diverting the Stream Contexts Filters Summary Chapter 17 Configuration and Linking Autoconf Looking for Libraries Enforcing Module Dependencies Speaking the Windows Dialect Summary Chapter 18 Extension Generators ext_skel PECL_Gen Summary Chapter 19 Setting Up a Host Environment The Embed SAPI Building and Compiling a Host Application Re-creating CLI by Wrapping Embed Reusing Old Tricks Summary Chapter 20 Advanced Embedding Calling Back into PHP Dealing with Errors Initializing PHP Overriding INI_SYSTEM and INI_PERDIR Options Capturing Output Extending and Embedding at Once Summary Appendix A A Zend API Reference Parameter Retrieval Classes Objects Exceptions Execution INI Settings Array Manipulation Hash Tables Resources/Lists Linked Lists Memory Constants Variables Miscellaneous API Function Summary Appendix B PHPAPI Core PHP Streams API Extension APIs Summary Appendix C Extending and Embedding Cookbook Skeletons Code Pantry Summary Appendix D Additional Resources Open Source Projects Places to Look for Help Summary Index Copyright Extending and Embedding PHP Copyright © 2006 by Sams Publishing All rights reserved No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher No patent liability is assumed with respect to the use of the information contained herein Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions Nor is any liability assumed for damages resulting from the use of the information contained herein Library of Congress Catalog Card Number: 2004093741 Printed in the United States of America First Printing: June 2006 09 08 07 06 4 3 2 1 Trademarks All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized Sams Publishing cannot attest to the accuracy of this information Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark Warning and Disclaimer Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied The information provided is on an "as is" basis The author and the publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book Bulk Sales Sams Publishing offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales For more information, please contact U.S Corporate and Government Sales 1-800-382-3419 corpsales@pearsontechgroup.com For sales outside of the U.S., please contact International Sales international@pearsoned.com Acquisitions Editors Betsy Brown Shelley Johnston Development Editor Damon Jordan Managing Editor Charlotte Clapp Project Editor Dan Knott Copy Editor Kate Givens Indexer Erika Millen Proofreader Susan Eldridge Technical Editor Brian France Publishing Coordinator Vanessa Evans Multimedia Developer Dan Scherf Interior Designer Gary Adair Cover Designer Alan Clements Page Layout Juli Cook Dedication To my partner Angela, who waited with patience and constancy while I ignored her night after night making this title a reality And to my family, who gave me strength, courage, and confidence, and made me the person I am today Foreword If you had told me when I submitted my first patch to the PHP project that I'd be writing a book on the topic just three years later, I'd have called you something unpleasant and placed you on /ignore However, the culture surrounding PHP development is so welcoming, and so thoroughly entrapping, that looking back my only question is "Why aren't there more extension developers?" The short (easy) answer, of course, is that while PHP's documentation of userspace syntax and functions isin every waysecond to none, the documentation of its internals is far from complete and consistently out of date Even now, the march of progress towards full Unicode support in PHP6 is introducing dozens of new API calls and changing the way everyone from userspace scripters to core developers looks at strings and binary safety The response from those of us working on PHP who are most familiar with its quirks is usually, "Use the source." To be fair, that's a valid answer because nearly every method in the core, and the extensions (both bundled and PECL), are generously peppered with comments and formatted according to strict, well followed standards that are easy to read once you're used to it But where do new developers start? How do they find out what PHP_LONG_MACRO_NAME() does? And what, precisely, is the difference between a zval and a pval? (Hint: There isn't one; they're the same variable type) This book aims to bring the PHP internals a step closer to the level of accessibility that has made the userspace language so popular By exposing the well planned and powerful APIs of PHP and the Zend Engine, we'll all benefit from a richer pool of talented developers both from the commercial ranks and within the open source community userspace superglobals auto_global_callback declaring UU-encode Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Z] V$ views values, returning passing by reference call-time pass-by-ref compile-time pass-by-ref reference values return_value_ptr variable return_value_used variable var_dump() function 2nd variables $_FILE $_GET $_POST $GLOBALS converting creating data types automatic type conversion with zend_parse_parameters() determining IS_ARRAY IS_BOOL IS_DOUBLE IS_LONG IS_NULL IS_OBJECT IS_RESOURCE IS_STRING type-hinting data values initial variables, setting loose typing retrieving return_value_ptr return_value_used serializing to string values storing strings, populating unserializing string values to Zend API calls varstream.c file vectors views, php_stream_get_line visibility flags (methods) VLD (Vulcan Logic Decoder) vspprintf() function Vulcan Logic Decoder (VLD) Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Z] WARNING() macro win32build.zip file Windows systems compilers compiling PHP on config.w32 file extensions, building statically tools wrappers (streams) 2nd dir_opener() implementation mkdir() opendir() 2nd php_varstream_mkdir() php_varstream_rename() php_varstream_rmdir() php_varstream_unlink() rename() rmdir() stream_closer() stream_opener() stream_stat() unlink() URL parsing url_stat() writing change on write copy on write streams 2nd 3rd WRONG_PARAM_COUNT macro Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Z] xport parameter (php_stream_xport_create() function) Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Z] Z_ARRVAL() macro Z_ARRVAL_P() macro Z_ARRVAL_PP() macro Z_OBJCE() macro Z_OBJCE_P() macro Z_OBJPROP() macro Z_TYPE() macro Z_TYPE_P() macro Z_TYPE_PP() macro Zend [See also macros, OBJCE; specific functions.] array manipulation classes constants exceptions execution hash tables INI settings linked lists memory miscellaneous functions objects parameter retrieval properties resources/lists thread safety thread-safe data pools when not to thread variables ZendMM (Zend Memory Management) allocator functions memory_limit setting (php.ini) persistent allocations Zend Value [See zval (Zend Value).] ZEND_ACC_ABSTRACT flag ZEND_ACC_FINAL flag ZEND_ACC_PRIVATE flag ZEND_ACC_PROTECTED flag ZEND_ACC_PUBLIC flag ZEND_ACC_STATIC flag zend_alter_ini_entry() function 2nd ZEND_ARG_ARRAY_INFO() macro ZEND_ARG_INFO() macro ZEND_ARG_OBJ_INFO() macro ZEND_ARG_PASS_INFO() macro zend_bailout() function ZEND_BEGIN_ARG_INFO() macro 2nd ZEND_BEGIN_ARG_INFO_EX() macro 2nd ZEND_BEGIN_MODULE_GLOBALS() macro zend_catch blocks zend_class_entry zend_class_entry *get_class_entry() handler zend_class_entry structure initializing registering zend_class_implements() function zend_copy_parameters_array() function zend_declare_class_constant() function zend_declare_class_constant_bool() function zend_declare_class_constant_double() function zend_declare_class_constant_long() function zend_declare_class_constant_string() function zend_declare_class_constant_stringl() function zend_declare_property() function zend_declare_property_bool() function zend_declare_property_double() function zend_declare_property_ex() function zend_declare_property_long() function zend_declare_property_null() function zend_declare_property_string() function zend_declare_property_stringl() function zend_disable_class() function zend_disable_function() function ZEND_END_ARG_INFO() macro 2nd ZEND_END_MODULE_GLOBALS() macro zend_end_try blocks zend_error() function zend_eval_string() function 2nd zend_eval_string_ex() function zend_exception_get_default() function zend_execute_scripts() function zend_fetch_class() function zend_fetch_list_dtor_id() function zend_fetch_resource() function 2nd 3rd 4th ZEND_FETCH_RESOURCE2() macro zend_function_entry structure zend_get_class_entry() function zend_get_constant() function zend_get_error_exception() function zend_get_hash_value() function zend_get_module_version() function zend_get_object_classname() function zend_get_parameters() function 2nd zend_get_parameters_array() function zend_get_parameters_array_ex() function 2nd zend_get_parameters_ex() function 2nd 3rd zend_get_std_object_handlers() function zend_hash_add() 2nd zend_hash_apply() 2nd ZEND_HASH_APPLY_KEEP return value (hash apply) ZEND_HASH_APPLY_REMOVE return value (hash apply) ZEND_HASH_APPLY_STOP return value (hash apply) zend_hash_apply_with_argument() 2nd zend_hash_apply_with_arguments() 2nd zend_hash_clean() 2nd zend_hash_compare() 2nd zend_hash_copy() 2nd zend_hash_del() 2nd zend_hash_destroy() 2nd zend_hash_exists() 2nd zend_hash_find() 2nd zend_hash_func() zend_hash_get_current_data_ex() zend_hash_get_current_key() zend_hash_get_current_key_ex() 2nd zend_hash_get_current_key_type_ex() zend_hash_graceful_destroy() zend_hash_graceful_reverse_destroy() zend_hash_index_del() 2nd 3rd zend_hash_index_exists() 2nd zend_hash_index_find() 2nd zend_hash_index_update() 2nd zend_hash_init() 2nd zend_hash_init_ex() zend_hash_internal_pointer_end_ex() zend_hash_internal_pointer_reset_ex() zend_hash_merge() 2nd zend_hash_merge_ex() 2nd zend_hash_minmax() 2nd zend_hash_move_backwards_ex() zend_hash_move_forward_ex() zend_hash_next_free_element() 2nd zend_hash_next_index_insert() zend_hash_next_insert() zend_hash_num_elements() zend_hash_quick_add() 2nd zend_hash_quick_exists() 2nd zend_hash_quick_find() 2nd zend_hash_quick_update() 2nd zend_hash_reverse_apply() zend_hash_sort() 2nd zend_hash_update() 2nd zend_hash_update_current_key_ex() function zend_ini_double() function zend_ini_entry stucture zend_ini_long() function ZEND_INI_MH() macro zend_ini_string() function zend_is_callable() function zend_is_callable_ex() function zend_is_true() function zend_list_addref() function zend_list_delete() function 2nd zend_list_find() function 2nd zend_list_insert() function zend_llist_add_element() function zend_llist_apply() function zend_llist_apply_with_argument() function zend_llist_apply_with_arguments() function zend_llist_apply_with_del() function zend_llist_clean() function zend_llist_copy() function zend_llist_count() function zend_llist_del_element() function zend_llist_destroy() function zend_llist_get_first_ex() function zend_llist_get_last_ex() function zend_llist_get_next_ex() function zend_llist_get_prev_ex() function zend_llist_init() function zend_llist_prepend_element() function zend_llist_remove_tail() function zend_llist_sort() function zend_lookup_class() function zend_lookup_class_ex() function zend_make_callable() function zend_mangle_property_name() function 2nd zend_module_entry structure 2nd 3rd ZEND_NUM_ARGS() macro 2nd zend_object_store_get_object() function zend_object_value clone_obj() method zend_objects_get_address() function zend_parse_method_parameters() function zend_parse_method_parameters_ex() function zend_parse_parameters() function 2nd 3rd data types forced separation IS_NULL versus NULL modifiers optional parameters type specifiers zend_parse_parameters_ex() function zend_qsort() function zend_read_property() function zend_read_static_property() function zend_register_auto_global() function 2nd zend_register_constant() function zend_register_double_constant() function zend_register_internal_class() function 2nd zend_register_internal_class_ex() function zend_register_internal_interface() function zend_register_list_destructors() function zend_register_list_destructors_ex() function 2nd zend_register_long_constant() function zend_register_resource() function zend_register_string_constant() function zend_register_stringl_constant() function zend_restore_ini_entry() function zend_rsrc_list_get_rsrc_type() function zend_set_memory_limit() function zend_set_timeout() function zend_strndup() function zend_throw_error_exception() function zend_throw_exception() function zend_throw_exception_ex() function zend_throw_exception_object() function zend_try blocks zend_unset_timeout() function zend_update_property() function zend_update_property_bool() function zend_update_property_double() function zend_update_property_long() function zend_update_property_null() function zend_update_property_string() function zend_update_property_stringl() function zend_update_static_property() function zend_update_static_property_bool() function zend_update_static_property_double() function zend_update_static_property_long() function zend_update_static_property_null() function zend_update_static_property_string() function zend_update_static_property_stringl() function ZEND_VERIFY_RESOURCE() macro zend_zval_type_name() function ZendMM (Zend Memory Management) allocator functions memory_limit setting (php.ini) persistent allocations zval (Zend Value) converting creating data types determining IS_ARRAY IS_BOOL IS_DOUBLE IS_LONG IS_NULL IS_OBJECT IS_RESOURCE IS_STRING data values exchanging streams for retrieving storing zval **get_property_ptr_ptr() handler zval *get() handler zval *read_dimension() handler zval *read_property() handler zval* Array API array creation array population zval_add_ref() function ZVAL_BOOL() macro zval_copy_ctor() function ZVAL_DOUBLE() macro zval_dtor() function 2nd ZVAL_LONG() macro 2nd zval_ptr_dtor() function 2nd ZVAL_RESOURCE() macro ZVAL_STRINGL() macro ZVAL_TRUE() macro .. .Extending and Embedding PHP By Sara Golemon Publisher: Sams Pub Date: May 30, 2006 Print ISBN- 10: 0-672-32704-X Print ISBN- 13: 978-0-672-32704-9 Pages: 456... Additional Resources Open Source Projects Places to Look for Help Summary Index Copyright Extending and Embedding PHP Copyright © 2006 by Sams Publishing All rights reserved No part of this book shall be reproduced,... Constants Variables Miscellaneous API Function Summary Appendix B PHPAPI Core PHP Streams API Extension APIs Summary Appendix C Extending and Embedding Cookbook Skeletons Code Pantry Summary Appendix D