1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu Building a monitoring system into your scripts ppt

71 505 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 71
Dung lượng 2,62 MB

Nội dung

AUGUST 2003 VOLUME II - ISSUE The Magazine For PHP Professionals Maintenance from the Outset Building a monitoring system into your scripts An Introduction to Ming Create amazing Flash applications on-the-fly An Introduction to cURL Discover the ins and outs of this indispensable tool Transforming XML to PDF with the help of LaTeX Embedding Assembler in PHP Case studies in Client/Server Applications www.phparch.com Take your PHP to new lows Get Ready For php | Cruise See inside for details March 1st - March 5th 2004 Plus: Tips & Tricks, Product Reviews and much more ! EW N Existing subscribers can upgrade to the Print edition and save! Login to your account for more details Buy now and save $10 off the price of any subscription† Visit: http://www.phparch.com/print for more information or to subscribe online php|architect Subscription Dept P.O Box 3342 Markham, ON L3R 9Z4 Canada Name: Address: City: State/Province: ZIP/Postal Code: Country: php|architect The Magazine For PHP Professionals Your charge will appear under the name “Marco Tabini & Associates, Inc.” The first issue of your subscription will be mailed to you in September, 2003 Please allow up to weeks for your subscription to be established *US Pricing is approximate and for illustration purposes only Choose a Subscription type: Canada/USA $ 81.59 $67.99 CAD ($59.99 $49.99 US*) International Surface $108.99 $94.99 CAD ($79.99 $69.99 US*) International Air $122.99 $108.99 CAD ($89.99 $79.99 US*) Payment type: VISA Mastercard Credit Card Number: Expiration Date: E-mail address: Phone Number: American Express Signature: Date: *By signing this order form, you agree that we will charge your account in Canadian dollars for the “CAD” amounts indicated above Because of fluctuations in the exchange rates, the actual amount charged in your currency on your credit card statement may vary slightly †Limited time offer expires August 31st, 2003 To subscribe via snail mail - please detach this form, fill it out and mail to the address above or fax to +1-416-630-5057 We’ve got you covered, from port to sockets php | Cruise Port Canaveral • Coco Cay • Nassau March 1st - March 5th 2004 Signup now and save $100.00! Hurry, space is limited Visit us at www.phparch.com/cruise for more details Andrei Zmievski - Andrei's Regex Clinic, James Cox - XML for the Masses, Wez Furlong - Extending PHP, Stuart Herbert - Safe and Advanced Error Handling in PHP5, Peter James - mod_rewrite: From Zero to Hero, George Schlossnagle - Profiling PHP, Ilia Alshanetsky - Programming Web Services, John Coggeshall - Mastering PDFLib, Jason Sweat - Data Caching Techniques Plus: Stream socket programming, debugging techniques, writing high-performance code, data mining, PHP 101, safe and advanced error handling in PHP5, programming smarty, and much, much more! TABLE OF CONTENTS php|architect Departments Features 10 Editorial Transforming XML to PDF with LaTeX Stephan Schmidt I N D E X What’s New! 16 26 Ming & PHP Seth Wilson Granted! Announcing the winners of the 2003 php|architect Grant Program 33 29 Sockets: Part Eugene Otto Datanamic DeZign for Databases Peter James 65 Tips & Tricks 41 Peter James John W Holmes 69 Bits & Pieces Grokking cURL 48 Maintenance from The Outset Graeme Foster 71 exit(0); Expect More From php|a Marco Tabini 57 Embedding Assembler in PHP Igor Gorelik August 2003 · PHP Architect · www.phparch.com EDITORIAL E D I T O R I A L R A N T S I could not be happier right now As I sit here at my laptop, writing this editorial, by my side sits a glass of beer that I made from scratch, not quite a month ago I’m inspired by the similarities that exist between the evolution of php|architect as a powerhouse publication and de facto standard source of PHP knowledge, and the creation of what is now a simple glass of lovely ale I brew with real grain and real hops None of this ‘just add water’ stuff I’ve never done it, and I won’t I suppose it’s fine if you just want a ‘quick and dirty’ beer However, I have an overwhelming feeling that my integrity as a brewer would be sacrificed for ‘ease’ (I call it ‘laziness’), and it doesn’t sit well with me I want honest beer I want to know how the wort was produced, and where it came from Indeed, I want to be intimately associated with the very essence of the finished product For better, or for worse I found this same spirit in the publisher of php|architect, who I’ve now come to know as both a good friend and close business associate, Marco Tabini Marco understood my leanings toward things that were, for lack of a better term, ‘organic’ or ‘untainted’ I wanted material written by doers I shunned several articles by professional writers whose writing lacked the spirit that we’ve by now become accustomed to at php|architect; the spirit of someone who has fought and lost battles on their way to great discoveries using PHP Other writers, in comparison, appear to have ‘just added water’ We’ve made it a goal to avoid such articles Of course, it is the ‘road less traveled’, but we feel it has made all the difference, and you’ve let us know that we’re right Of course, brewing from scratch comes with its headaches Brewing from scratch means more steps are involved, the materials are handled and transferred more often, and more opportunities exist for molds and bacterias to be introduced into the beer While I’ve so far been able to avoid that, and produce very drinkable beer, it is not without its flaws The one I’m drinking now took on a bit of a ‘chill haze’ after being bottled, for example; a minor problem that doesn’t affect anything but the aesthetic qualities of the beer As I continue to brew and master the craft, I’ll inevitably fix the ‘chill haze’ problem, while introducing others Eventually, it all works out, and you achieve ‘excellent beer’ August 2003 · PHP Architect · www.phparch.com php|architect Volume II - Issue August, 2003 Publisher Marco Tabini Editor-in-Chief Brian K Jones brian@phparch.com Editorial Team Arbi Arzoumani Brian Jones Eddie Peloke Peter James Marco Tabini Graphics & Layout Arbi Arzoumani, William Martin Managing Editor Emanuela Corso Authors Greame Foster, Igor Gorelik, Peter James, Eugene Otto, Stephan Schmidt, Marco Tabini, Seth Wilson php|architect (ISSN 1705-1142) is published twelve times a year by Marco Tabini & Associates, Inc., P.O Box 3342, Markham, ON L3R 6G6, Canada Although all possible care has been placed in assuring the accuracy of the contents of this magazine, including all associated source code, listings and figures, the publisher assumes no responsibilities with regards of use of the information contained herein or in all associated material Contact Information: General mailbox: Editorial: Subscriptions: Sales & advertising: Technical support: info@phparch.com editors@phparch.com subs@phparch.com sales@phparch.com support@phparch.com Copyright © 2002-2003 Marco Tabini & Associates, Inc — All Rights Reserved EDITORIAL Such is the case with this magazine as well We’re not perfect We haven’t ever claimed to be perfect, and as a team, I don’t think any of us could ever foresee a day when there isn’t at least the slightest bit of ‘haze’ However, it is the attitude of this team that as long as there is not perfection, there is work to be done, and so we’re constantly busy, if not with fingers to the keyboard, then with developing ideas or analyzing weaknesses It is this attitude, and the fact that it permeates every digital thread of the publication, that will earn us whatever critical acclaim may await us Finally, beer and brewing is a learning process I was fortunate enough that my buddy Matt was an already experienced brewer without a convenient location to brew, and I was a homeowner with a large back yard and a willingness to learn Matt and I have known each other since childhood, and we work well together We understand each other and relate to each other better than most other people we know This makes for a great working relationship, partially because we grew out of the ‘polite friendship’ stage somewhere around age 14 We constantly question and debate Our beer thus far has been better for it This type of working relationship is invaluable in creating anything of any quality In striving for quality of material in php|architect, anyone who has written for our editorial team will note that I take a decidedly different approach The approach is largely the brainchild of Marco and I, who have somehow been able to achieve a vigorous and successful working relationship Constantly questioning and debating each other, we’re always playing ‘devil’s advocate’ to insure that, in the end, we’ve done right by all parties involved In the process we’ve learned what makes this monster we’ve created tick, and how to channel our efforts to add even more value to our readership Our ability to come to a ‘meeting of the minds’ on all aspects of the publication has brought us not only to where we are now, but will influence the direction of the publication in the future – for better, or for worse In reality, at the end of the day, it’s our ability to tell each other that our ideas completely suck that has made all the difference! But there is another ingredient in our recipe at php|architect It’s the ‘recognition’ phase Recognition of a person’s ‘highest and best use’ August 2003 · PHP Architect · www.phparch.com We seek people to join our team who we feel we can work with, and we eventually move everyone into a position where their interests and skills are put to work to produce the best ‘stuff’ that they can As I’ve mentioned from the very beginning, editorial work is not my highest and best use No matter how much I love editing and the editorial process, the reality is that a) I’m not a hardcore coder, and b) I’m not a hardcore editor! It is with these words that I am proud to pass the Editor in Chief torch to the very capable Peter James Peter has accomplished much in his relatively short time as Senior Editor at php|architect, affecting both the outward appearance of the magazine, as well as the backend procedures for coordinating the editorial process All by his own initiative, and all without a thought for anything but the good of the publication Furthermore, as if this weren’t enough, he still constantly asks for more responsibility, and a greater role in the magazine’s creation Finally, I came to the conclusion that the only way for Pete to anything more was to take my job, which would allow me to be applied to my highest and best use as well So from now on, it will be Pete’s job to try hard to give you all a reason to read the editorial column that I’m still convinced is a pretentious waste of paper (be it digital or ‘dead tree’ in form) I’ll not be far, mind you! I’m taking on a new role that will also produce some really cool and exciting new (but as yet unmentionable) ‘stuff’ in the not too distant future I’m excited at the opportunity, though I’ll always make myself available on those sleepless nights when Pete can’t get some ‘damned Linux code’ to validate or something I wish Pete a lot of luck, and thank him for the hard work he’s done, along with the rest of the production crew who have helped php|architect become what we are today, and what we will be tomorrow I also thank all of the readers for the feedback and guidance along the way .until we meet again brian php|Cruise ‘04 10 Transforming XML to PDF with LaTeX 16 Ming & PHP 33 Sockets: Part 41 Grokking cURL 48 Maintenance from The Outset 57 Embedding Assembler in PHP What’s New! 26 Granted! 29 Datanamic DeZign for Databases 65 Tips & Tricks 69 Bits & Pieces 71 e x i t ( ) ; What’s New! S T U F F PHP 4.3.3 RC3 PHP.net announced the release of PHP 4.3.2 release candidate “This should be the last release candidate prior to the final 4.3.3 release Please test this release as much as possible, so that any remaining issues can be uncovered and resolved.” Bug fixes include: • escapeshellcmd() can now handle quoted arguments • exit code lost when exit() called from register_shutdown_function() • methods misidentified as constructors • and much more N E W Visit php.net to download or view the change log Apache 2.0.47 The Apache Software Foundation and the Apache HTTP Server Project announce the tenth public release of the Apache 2.0 HTTP Server This is a security, bug fix and minor upgrade release Due to security issues, any sites using Apache versions prior to Apache 2.0.47 should upgrade to Apache 2.0.47 Security issues: a Fixed a bug in the handling of accept errors by the prefork MPM when handling accept errors, which could allow a denial of service attack if multiple listeners are configured b Fixed a bug in the optional renegotiation code in mod_ssl which could cause cipher suite restrictions to be ignored if optional renegotiation is enabled August 2003 · PHP Architect · www.phparch.com c Fix of denial of service attack in mod_proxy’s handling of DNS results New features: Added support for a “prefer-language” environment variable to mod_negotiation” To download, visit Apache.org ionCube and the Cerberus Encoder ionCube.com announced the release of the ionCube 3.0 The ionCube standalone PHP encoder is a high performance encoding solution for PHP, offering encoding of compiled code to deliver the maximum security and run-time performance for encoded file, and features to allow easy integration into build and release systems, and also websites for just-in-time software delivery New Version 3.0 advantages: a Customizing of Loader event messages b Restricting encoded files to only cooperate with other encoded files that have certain ‘properties’ c Improved encoding performance In addition to Version 3.0, Ioncube has released the Cerberus Encoder This is the same as the full featured encoder, but adds the ability to restrict files to a MAC address For more information, visit ionCube.com NEW STUFF Databases MySQL and PostgreSQL both announced new releases this month PHPNuke 6.7 PHPNuke.org announced the release of version 6.7 PHPNuke is a PHP based content management system This newest version fixes XSS and other vulnerabilities and security bugs like path disclosure, and adds associated topics to the News module There are many cosmetic changes and minor bugs fixed, and the Update folder was reorganized You can get more information or download from PHPNuke.org PostgreSQL 7.3.4 PostgreSQL.org announced the release of their latest version 7.3.4 This version addressed a potentially serious (although rare) server startup failure that was recently reported This release is critical for users of PostgreSQL version 7.3.3, and highly recommended for all other PostgreSQL users The latest version can be downloaded from the PostgreSQL FTP site PHPEdit 0.7.1.131 PHPEdit.net announced the release of PHPEdit 0.7.1.131 It’s still a development version but takes one step further to the stable release It contains proposal #2, #3 and #7 of the PHPEdit Community PHPEdit invites all users to report problems or tweaks in 0.7.1.131 to the PHPEdit Community PHPEdit also asks all users to vote for requests they want to be in the next release to the Community Visit PHPEdit.net to download patUser 2.1.2 and 2.20 Beta PHP Application Tools announced the release of patUser 2.1.2 and 2.20 Beta New in this version: bugs, notices and warnings removed Warning: this is the last version of patUser supporting patDbc, as we are switching to PEAR::DB Version 2.2.0 is the new branch supporting PEAR:DB - but keep in mind that it is still BETA! If you are willing to test it, feel free to send your bug reports to gERD directly “ For more information or to download, visit PHP-Tools.de MySQL 4.0.14 MySQL.com announces the release of version 4.0.14 This release is a maintenance release for the current production version and includes functionality such as: a Enabled `INSERT’ from `SELECT’ when the table into which the records are inserted is also a table listed in the `SELECT’ b Changed optimiser slightly to prefer index lookups over full table scans c `FLUSH LOGS’ now rotates relay logs in addition to the other types of logs it already rotated For the full list of additions and bug fixes, or to download, visit MySQL.com php|a August 2003 · PHP Architect · www.phparch.com Transforming XML to PDF with LaTeX F E A T U R E By Stephan Schmidt Types of documents XML is commonly used to store several types of information Not only developers use it in their daily work to store configurations or define protocols, it is also a great way to structure your everyday documents, like letters, books, or articles Even if they can be read with any text editor (XML is an ASCII format), XML documents are not the first choice when it comes to documents that you'd like to read in your free time The mixture of tags, attributes and plain text may confuse you while you are trying to get to the actual information XML was designed to be read by machines, not humans XML does not contain any layout but only the structure of the raw data or content An XML document consists of several tags (like HTML) which describe the information contained within the tags Any program may use these tags to decide what to with the text information between these tags This could mean a program is able to prioritize parts of a document, if it had to create a search index or something similar Humans tend to decide what to with the information they read according to how it has been laid out If you are reading an article, you will surely recognize that the headline has some significance in the context of the rest of the article, as it is printed in bold and large letters August 2003 · PHP Architect · www.phparch.com So if information has to be accessed by computers and humans, the best solution would be to present both species the same information in different formats The first choice of delivering information to a machine is nowadays XML, while PDF can be read with almost every client and operating system, and can easily be printed, which enables you to take the information to wherever you'd like without the need for a computer As we're living in the age of automation, you will not want to create both versions of the information on your own but use your friendly neighbourhood webserver and scripting language (PHP) for it This article will explain one way to achieve this without a single drop of sweat Transforming documents To automate the generation of one version of the two required documents, you have to define which version should be created manually and which one should be generated by an application This problem is solved in the blink of an eye, as the previous section explained REQUIREMENTS PHP Version: 4.x and above O/S: Linux Additional Software: LaTex Code Directory: N/A 10 Embedding Assembler in PHP F E A T U R E By Igor Gorelik Overview Assembler is used for many purposes: optimizing program size and speed, low level hardware programming, and a lot of other capabilities that are difficult or impossible to implement in high level languages(HLL) [1] Inline assembler allows you to use assembly language’s power within programs coded with HLL such as Pascal, C/C++ or Basic For example, in MS Visual C++, assembler insertions looks like this: asm{ mov eax, 0x01234567 mov edx, 0x89ABCDEF xor eax, edx } The same code in Borland Pascal style looks like this: asm mov eax, $01234567 mov edx, $89ABCDEF xor eax, edx mov eax, var1 ; eax = add eax, 75 ; eax = 80 push eax call SomeFunctionName ; calling for SomeFunctionName function } Where “SomeFunctionName” could be a Windows API function name for example A few months ago I thought I’d try to implement inline assembler in PHP I didn’t really have a practical need for it, but I thought that it could be interesting I decided to try to make an inline assembler extension for PHP under Windows Developing an assembler translator is not a trivial task, so I decided to lean on one of the open-source assemblers for help I chose Flat Assembler(FASM) [2] FASM is an open-source assembler compiler written in assembly language and is available under Windows and Linux Some of FASM’s features include: end; REQUIREMENTS Moreover, the inline assembler allows you to use identifiers from the HLL’s “namespace” in assembler statements, like this: long var1 = 5; asm{ August 2003 · PHP Architect · www.phparch.com PHP Version: 4.x O/S: Windows Additional Software: FASM Code Directory: assembler 57 FEATURES • • • • Embedding Assembler in PHP 16 and 32 bit code MMX and FPU instructions set Binary, MZ, PE, COFF output file formats Trivial hardware and software requirements Newer versions also support SSE, SSE2 and AMD 3DNow! instructions FASM uses Intel assembly syntax For other features see FASM’s manual This article describes the full process of making an inline assembler PHP extension and examples of how it might be used It’s assumed that the reader knows something about assembly language, PHP, PHP-extensions and the Win32 platform Recompiling FASM The first thing I had to is recompile FASM into a COFF(Common Object File Format) file so I could link it to my extension (written in C++) That COFF-file must have one public function ( compile_asm() ) which will be called by my extension Input parameters for compile_asm() will be a pointer to some assembly code (dword) and the length of this code in bytes (dword) The output value will be a pointer to the compiled binary code (dword) Input and output parameters will be passed through the processor’s registers: Register Purpose functions it will just return and nothing happens The next function I’ve changed is exit_program(), which FASM calls when an error occurs, terminating the program Let this function return 0, so if any errors occur during the compilation, compile_asm() will return zero: exit_program: xor add extension’s will be 3rd eax, eax ; eax = esp, ; esp = esp+8, because return address dword in stack ret Fasm.asm is fasm’s main source file It contains calls to the parser, preprocessor, assembler, formatter, includes for other files, EXE-sections, etc All EXE-sections (imports, fixups) must be removed, as we don’t need ‘em anymore And ‘format PE’, which indicates that the file will be compiled into Portable Executable format (.exe), must be changed to ‘format MS COFF’ FASM 1.39 uses 11 external WinApi functions, which must be declared in MS format: imp functioname@paramlength:returnlength where functionname is the name of Windows API function, paramlength is the byte length of input parameter, and returnlength is the output type Input parameters EAX Pointer to assembly code EDX Length of assembly code Output value EAX Pointer to compiled binary data Declarations of Windows API functions: extrn imp ExitProcess@4:dword ExitProcess equ imp ExitProcess@4 extrn imp CreateFileA@28:dword CreateFile equ imp CreateFileA@28 The rest of this section describes changes I’ve made in FASM(ver 1.39) source-files to recompile it as a COFF file extrn imp ReadFile@20:dword ReadFile equ imp ReadFile@20 system.inc and fasm.asm The system.inc source file consists of an interface to system functions like ReadFile, WriteFile, CreateFile etc Since FASM will be used as a linked COFF-file, all screen-output functions (display_string, display_block, display_character and display_number ) should be removed: extrn imp CloseHandle@4:dword CloseHandle equ imp CloseHandle@4 display_string: ret display_block: ret display_character: ret display_number: ret extrn imp WriteFile@20:dword WriteFile equ imp WriteFile@20 extrn imp SetFilePointer@16:dword SetFilePointer equ imp SetFilePointer@16 extrn imp GetCommandLineA@0:dword GetCommandLine equ imp GetCommandLineA@0 extrn imp GetStdHandle@4:dword GetStdHandle equ imp GetStdHandle@4 extrn imp VirtualAlloc@16:dword VirtualAlloc equ imp VirtualAlloc@16 extrn imp GetTickCount@0:dword GetTickCount equ imp GetTickCount@0 extrn imp GlobalMemoryStatus@4:dword GlobalMemoryStatus equ imp GlobalMemoryStatus@4 So when some part of FASM code calls some of these August 2003 · PHP Architect · www.phparch.com 58 FEATURES Embedding Assembler in PHP I’ve also replaced FASM’s original entry point, ‘start:’, with: public _compile_asm lic ; let compile_asm() be pub- _compile_asm: Here’s a part of FASM’s code where it gets commandline parameters: call cmp je lea mov movzx add cmp je inc mov get_params [params],0 information eax,[params+1] [input_file],eax ecx,byte [eax-1] eax,ecx byte [eax],0 information eax [output_file],eax I’ve replaced this with: mov [str_src], eax ; str_src = pointer to assembly code (eax) mov [str_src_len], edx ; str_src_len = length of [str_src] (edx) The last step is to forbid reading the source from the file and use data passed with input parameters instead of files The source file with the “preprocess_file” function (file: preproce.inc) looks like this: preprocess_file: push push call jc mov xor call push xor xor call pop mov dec mov sub jc mov cmp jbe mov call call [memory_end] edx open no_source_file al,2 edx,edx lseek eax al,al edx,edx lseek ecx edx,[memory_end] edx byte [edx],1Ah edx,ecx out_of_memory esi,edx edx,edi out_of_memory [memory_end],edx read close Which I’ve replaced with: “str_src” and “str_src_len” are variables I‘ve declared in fasm.asm: str_src dd ? str_src_len dd ? , , assemble.inc, preproce.inc, formats.inc The ORG 0xXXXXXXXX - directive tells the assembler to move its location counter to 0xXXXXXXXX memory address Before compilation is started, the source to be compiled must have the directive ORG 0xXXXXXXXX, where 0xXXXXXXXX is the entry point of the compiled binary code Since we can’t know the entry point address before compiling is started, the org directive address (0xXXXXXXXX) needs to be changed during the compilation It just needs to add “mov eax, [code_start]” after “call get_dword_value” within the ‘org_directive’ label (file: assemble.inc) The file ‘formats.inc’ contains code for formatting compiled code into FASM-supported output file formats(e.g MZ, PE, COFF ) Because I only need to get simple binary code, all code after the “formatter:” label (file: formats.inc) may be replaced by: mov eax,[code_start] ;eax = code_start; ret August 2003 · PHP Architect · www.phparch.com preprocess_file: ; read, write, close commands are removed push [memory_end] push edx mov ecx, [str_src_len] mov edx,[memory_end] dec edx mov byte [edx],1Ah sub edx,ecx jc out_of_memory mov esi,edx cmp edx,edi jbe out_of_memory mov [memory_end],edx ; copying assembly source code from extension’s to fasm’s buffer: pushad ;saving registers mov esi, [str_src] mov edi, edx mov ecx, [str_src_len] mov [bytes_count], ecx rep movsb popad ; restoring registers That’s it! FASM is now ready for recompilation! Compiling I’ve compiled these edited FASM sources with the original fasm.exe: 59 FEATURES Embedding Assembler in PHP > fasm.exe fasm.asm fasm.obj fasm.asm – input file fasm.obj – output file access any other functions exported by shared libraries: HINSTANCE LoadLibrary( LPCTSTR lpLibFileName // address of filename of executable module ); and Making the extension This simple extension consists of one source file – php_asm.cpp and provides only one function for PHP developers: int asm(string code) It simply assembles and executes code The return value is the value of the EAX processor’s register after the code has successfully completed The basic extension code (C++) with comments can be seen in Listing (included in this month’s package) After compiling and linking it with fasm.obj, I’ve got php_asm.dll I’ve placed it in my PHP extension directory and I’ve also written a small script to test it (test1.php): ("php_asm.dll"); = asm(" org 0x00000000 use32 mov edx, dword [sux] mov ebx, 0x95511559 xor edx, ebx push edx pop eax ret sux dd 0x87654321 ; setting compilers location ; using 32bit code ; edx = 0x87654321 ; ebx = 0x95511559 ; edx = 0x87654321 xor 0x95511559 = 0x12345678 ; eax = edx ; returning ("%s %x","asmed:", $return ); Execution Output: FARPROC GetProcAddress( HMODULE hModule, // handle to DLL module LPCSTR lpProcName // name of function ); The LoadLibrary() function maps the specified executable module (e.g into the “user32.dll”) address space of the calling process and returns it’s handle If the module is already loaded, the function just increments the reference count for the module and returns the module handle for that library The GetProcAddress function returns the address of the specified exported dynamiclink library (DLL) function.[4] “I've decided to add the ability to call Windows API functions and to work with variables from the PHP namespace.” C++ example: /* getting handle of user32.dll */ h = LoadLibrary(“user32.dll”); /* getting MessageBoxA function’s address*/ f = GetProcAddress(h, “MessageBoxA”); I need to provide to the compiled binary code at least these two functions for accessing any other parts of the API I’ve created an array of DWORDs called “Func_AddressTable” (unsigned long Func_AddressTable[2];) Each element of this array is an address of a function: It’s alive! So the extension works, and now I’ve decided to add important features: the ability to call Windows API functions and the ability to work with variables from the PHP namespace Accessing The Windows API Any Win32 program requires two API functions to August 2003 · PHP Architect · www.phparch.com 60 FEATURES Func_AddressTable will be initialized within the extension’s module startup function ZEND_MINIT_FUNCTION(asm) (this function is called only once, upon module initialization[3]) : ZEND_MINIT_FUNCTION(asm){ HMODULE h; Embedding Assembler in PHP windows message box: err: mov ebp, [esp+8] ; restoring ebp-register mov f_res, eax ; saving eax (f_res = eax) popad ; restoring registers Executing: } Where addr_tbl looks like this: void *addr_tbl; addr_tbl = Func_AddressTable; When the code above executes “call eax” to run compiled code, the stack within the compiled code looks like this: I’ve written a small script to test this feature – test2.php The script gets the address of the WinAPI MessageBoxA function and displays text in a standard August 2003 · PHP Architect · www.phparch.com Note: There’s a way to get addresses of the LoadLibrary and GetProcAddress functions without any APIs But I thought that the way described above was more convenient Moreover, I’ll also need Func_AddressTable to provide access to the script’s variables (see the next section of this article) Accessing a script’s variables Another important feature is the ability of inline assembler to work with variables created within a PHP script I’ve added more functions to the Func_AddressTable (Table on the next page) The set_var() function creates a new variable and assigns it a value If the variable name passed to the 61 FEATURES Embedding Assembler in PHP set_var() function already exists, the function overwrites it PHP variable types are described in the zend.h file from the PHP source package (e.g The type for string variables is 3) Currently, only LONG, BOOL and STRING types are supported unsigned long stdcall set_var(char *name, unsigned long type, unsigned long data){ zval *var1; #ifdef ZTS /* TSRM */ void ***tsrm_ls; tsrm_ls = asm_tsrm_ls; #endif Implementation of these functions: /* making empty zval container */ MAKE_STD_ZVAL(var1); unsigned long stdcall get_var_type(char *name){ zval **var1; #ifdef ZTS /* TSRM */ void ***tsrm_ls; tsrm_ls = asm_tsrm_ls; #endif if(zend_hash_find(EG(active_symbol_table), name, strlen(name)+1, (void **) &var1)==SUCCESS){ /* finds variable in current active symbol table and returns it’s type */ return (*var1)->type; } /* returns 0xffffffff if variable name not found */ return 0xffffffff; } unsigned long stdcall get_var_data(char *name){ zval **var1; #ifdef ZTS /* TSRM */ void ***tsrm_ls; tsrm_ls = asm_tsrm_ls; #endif /* finding variable */ if(zend_hash_find(EG(active_symbol_table), name, strlen(name)+1, (void **) &var1)==SUCCESS){ /*returns variable value depending on it’s type */ switch((*var1)->type){ case IS_NULL: return 0; case IS_LONG || IS_BOOL: return (*var1)->value.lval; case IS_STRING: return (unsigned long)(*var1)->value.str.val; } } return 0; } /* assigning it’s type */ var1->type = type; /* assigning it’s data depending on it’s type */ switch(type){ case IS_LONG || IS_BOOL: var1->value.lval = data; break; case IS_STRING: var1->value.str.len = strlen((char *)data); var1->value.str.val = estrdup((char *)data); break; } /* inserting var1 to current active symbol table */ ZEND_SET_SYMBOL(EG(active_symbol_table), name, var1); return 0; } Changed Func_AddressTable initialization: ZEND_MINIT_FUNCTION(asm){ HMODULE h; h = GetModuleHandle(“kernel32.dll”); Func_AddressTable[0] = GetProcAddress(h,”LoadLibraryA”); Func_AddressTable[1] = GetProcAddress(h,”GetProcAddress”); (void*)Func_AddressTable[2] = get_var_type; (void*)Func_AddressTable[3] = get_var_data; (void*)Func_AddressTable[4] = set_var; return SUCCESS; } I’ve changed test2.php such that the message text and message type are assigned using variables from the PHP namespace Table 1: Addtions to the Func_AddressTable Function Parameters Return Value unsigned long stdcall name - Points to a null-terminated string Returns a number representing variable type get_var_type(char *name) containing the name of a PHP variable (see zend.h from PHP sources) Returns 0xffffffff if variable not found unsigned long stdcall name - Points to a null-terminated string Returns value of a variable if variable type is get_var_data(char *name) containing the name of a PHP variable long or bool Returns pointer to string if variable is string unsigned long stdcall name - Points to a null-terminated string set_var(char *name, unsigned long containing the name of a PHP variable type, unsigned long data) type - variable type (see zend.h) data - new value of the variable name if variable is long or bool Pointer to null-terminated string if variable is string August 2003 · PHP Architect · www.phparch.com Currently always returns zero 62 FEATURES test3.php: Igor is a student of Moscow State Institute of Electronics and Mathematics: Networking faculty You can reach him at zero@zwan.ru Click HERE To Discuss This Article http://www.phparch.com/discuss/viewforum.php?f=42 Related Links http://webster.cs.ucr.edu/Page_asm/ArtofAssembly/0_ArtofAsm.html – The Art of Assembly Language http://fasm.sourceforge.net – FASM homepage http://www.zend.com – Zend homepage http://msdn.microsoft.com – Microsoft Developer Network http://osdev.neopages.net/tutorials/gccasmtut.php – A Brief Tutorial on GCC inline asm http://win32assembly.online.fr – Iczelion’s Win32 Assembly tutorials http://search.cpan.org/perldoc?Inline – Perl’s Inline module Figure 2: example.php output Figure 3: example.php output August 2003 · PHP Architect · www.phparch.com 64 By John W Holmes T I P S & T R I C K S Tips & Tricks Don’t Settle for the Defaults Does your host have a setting in its php.ini file that annoys you? Or maybe it breaks your programs? Well, for most of the settings, you don’t have to settle for what your host has given you PHP happily provides you the ini_set() function so that you can adjust the settings within your scripts Maybe you want your session to last a little longer than the life of the browser, or want to save them in another place, or just really need to have magic_quotes_runtime enabled If so, ini_set() is for you Want to fix that pesky register_globals problem (by turning them OFF, of course) or the magic_quotes_gpc setting? Well, ini_set() is not for you While the function can be used to adjust a lot of the settings for PHP, it can’t change them all Some are restricted so that they can only be changed within the php.ini file, others can be changed with an htaccess file, and a few can be changed in your script How you know the difference? Table shows an excerpt from the ini_set() manual page for some common settings The first column is the name of the setting, the second is the default for the setting, and the third column tells you where the setting can be changed at August 2003 · PHP Architect · www.phparch.com There are four options for this column: PHP_INI_USER Entry can be set in your scripts PHP_INI_PERDIR Entry can be set in php.ini, htaccess, or httpd.conf PHP_INI_SYSTEM Entry can be set in php.ini or httpd.conf PHP_INI_ALL Entry can be set anywhere You won’t actually see any settings that say as if it’s able to be set in your scripts then it can be set in any of the other locations, also So looking at Table 1, we can set magic_quotes_runtime/sybase with ini_set() within our scripts, magic_quotes_gpc in an htaccess or php.ini file, and safe_mode only within php.ini When you’ve made the change you want, whether using ini_set() or an htaccess file, you can view the output of the phpinfo() function to ensure your PHP_INI_USER, 65 TIPS & TRICKS change has taken place The phpinfo() function will show you the Local Value of the setting (which should match what you tried to change it to) and the Master Value from the php.ini file or the PHP defaults An htaccess file is just a plain text file that is named just that, htaccess It’s only available if you’re using Apache as your web server, though If you’re using an htaccess file to change your settings, there are two ways you can it To change the value of a setting that’s boolean or ON/OFF, you would use the format: php_flag ON|OFF To turn register_globals OFF, for example, you’d use: “If the client will not accept a session cookie and you want to use sessions, you're forced to pass the session identifier along with every request.” php_flag register_globals OFF If the setting you’re changing is not boolean, but instead requires a value, then you’d use the format: php_value To change the path that your sessions are saved to, for example, you’d use: php_value session.save_path “/path/to/dir” If you set the value to none, it’ll clear a previously set value Passing the SID So, if you haven’t used the first tip to enable session.user_trans_sid and you’re passing the value by hand, a DevShed.com user named jpenn offered up the solution in Listing If the client will not accept a session cookie and you want to use sessions, you’re forced to pass the session identifier along with every Listing function append_url( $url ) { if ( isset( $_COOKIE[ session_name() ] ) ) { /*—————————————————————— Return Un-Modified —————————————————————— */ return( $url ); } else { if ( strstr( $url, '?' ) ) { $arg_sep = '&'; } else { $arg_sep = '?'; } /*—————————————————————— Return Appended —————————————————————— */ return( $url $arg_sep SID ); } } Table magic_quotes_gpc “1” PHP_INI_PERDIR|PHP_INI_SYSTEM magic_quotes_runtime “0” PHP_INI_ALL magic_quotes_sybase “0” PHP_INI_ALL output_buffering “0” PHP_INI_PERDIR|PHP_INI_SYSTEM NULL PHP_INI_PERDIR|PHP_INI_SYSTEM register_argc_argv “1” PHP_INI_PERDIR|PHP_INI_SYSTEM register_globals “0” PHP_INI_PERDIR|PHP_INI_SYSTEM safe_mode “1” PHP_INI_SYSTEM output_handler August 2003 · PHP Architect · www.phparch.com 66 TIPS & TRICKS request This means every link or form on your page must pass the SID value This function will test to see if a cookie equal to the session name exists If it does, the original URL is returned, as SID does not need to be appended It then checks to see if a query string is already present or not in the URL, then it adds either a “?” or “&” character and the SID The function then returns the complete URL Listing Session Fixation Fix I wrote in the January 2003 issue about PHP having a “permissive” session management system The key to this claim was that PHP will take any value passed as PHPSESSID in the URL and use that as the session ID when you call session_start() in your script A malicious user could get other users to click on a link and set the session ID for them This would make session hijacking quite easy if(!isset($_SESSION['count'])) { $_SESSION['count'] = 0; } “A malicious user could get other users to click on a link and set the session ID for them This would make session hijacking quite easy.” As of PHP 4.3.2, there is now a session_regenerate_id() function that can help protect you against session fixation and session hijacking Calling this function after session_start() will session_start(); if(rand(1,10) == 5) { session_regenerate_id (); } setcookie(session_name(),session_id()); echo "Session ID: " session_id(); $_SESSION['count']++; echo "Count: {$_SESSION['count']}"; echo "Go"; assign a new session ID and still preserve your data This means you can call this at any point in your script Calling it directly after someone verifies their login data will prevent session fixation attacks Calling it periodically throughout your scripts, or as users pass into different areas of your application can help prevent session hijacking There are some problems with this “solution” though Only PHP 4.3.3 will actually reset the value of the session cookie when you call session_regenerate_id() If you’re using cookies and not using PHP 4.3.3, then even though the session ID is changed, it’s reset back to the old value when the next request is made and the old value is given in the session cookie The solution to this is to reset the cookie yourself after you generate a new ID Listing shows an example counter script that’ll randomly change the value of the session ID Using setcookie() after generating a new session ID resets the session cookie to the new ID If you are not using cookies, you can remove the setcookie() function call and notice how SID will be populated and the session data will persist even as the session ID changes You can test this by disabling cookie use with ini_set() Remember my first tip? ini_set(“session.use_cookies” ,0); Dynamic Web Pages www.dynamicwebpages.de sex could not be better | dynamic web pages - german php.node news scripts tutorials downloads books installation hints August 2003 · PHP Architect · www.phparch.com Remember Where Your User Was Maybe it’s happened to you You spend some time browsing through a site looking for something When you happen to find it, you take your time reading it However, when you click on the next link, your session has timed out and you’ve got to log in again The problem with this is that the login process dumps you back out to the main page, though, and you’ve got to find your file again Sure, bookmarking the page would be one option, but as programmers, we should feel for our users and make things easy for them 67 TIPS & TRICKS So what’s the answer? Well, it depends on how you’re controlling your authentication process, but in general terms, you want to save the URL the user requested somewhere When the user properly revalidates their login, then you retrieve that URL and redirect them to there, instead of your main page Each of the parts to make up the URL that was requested can be found in $_SERVER Depending upon your web server, you may need to combine a few variables or you may find one variable that contains the entire URL A simple print_r($_SERVER) will show you all of the contents and you can pick from there This idea could be expanded some As it is right now, it’ll only cover GET requests, or URLs with a query string If the timeout occurs when a form is POSTed, you lost that POST information However, upon realizing the session has timed out, you could check $_POST for values and save that in the session also Then simply restore it on the page the user is redirected back to and their data will be saved This will make the user that takes hours to type up his post to your bulletin board very happy The Difference Between “Works” and “Right” There was a recent, well, "discussion" on the PHP mailing list where people were discussing issues with header() The manual states that HTTP/1.1 requires a August 2003 · PHP Architect · www.phparch.com full URI when sending a Location: header, such as header(‘Location: http://www.domain.com’) At this point, some people piped up and stated that they have been using relative URIs and it’s working just fine Well, that’s the difference between “working” and “right” Yes, relative URIs might work with some clients, but not all of them If it’s done the right way, it’s going to work regardless, which is pretty much what we want in this business The other tip that was offered when redirecting with a Location: header is to always put a exit() after the header() call The PHP code doesn’t stop processing when the Location header is sent Depending upon the code you have after the redirection, it could cause the redirection to fail, even though the code might work in some cases Adding in the exit() makes sure nothing else is executed and the client processes the new Location: header That, again, is the difference between “works” and “right” About The Author ?> John Holmes is a Captain in the U.S Army and a freelance PHP and MySQL programmer He has been programming in PHP for over years and loves every minute of it He is currently serving at Ft Gordon, Georgia as a Company Commander with his wife and two sons php|a 68 Zeev, the Grand Loco Back in June, John Lim (of ADODB fame), speaking about the JSR 223 wrote: “I was hooked the first time i took a drag of PHP All my complicated C shit became clear after one puff of PHP It was so addictive i couldn’t stop I had to prowl the PHP CVS, meet drug dealers like Sterling and Andrei, and even hang out with the grand loco himself, the Zeev.” —http://php.weblogs.com/ Interestingly enough, just a few days earlier, Zeev had uploaded this picture to his personal gallery (http://www.suraski.net/gallery) Looks like he’s ready for the PHP cruise Are you? B I T S cipal applied to programming, i.e the variable does not really take on a value until you look at it” — Jason Sweat, regular php|architect author See the full thread at: http://www.phparch.com/discuss/viewtopic.php?t=163 “A consultant that judges code based on its appearances reminds me of what Brendan Behan once said of literary critics: ‘A critic is like a eunuch at on orgy He knows how it’s done He’s seen it done every day But he’s unable to it himself’.” — Marco Tabini, publisher of php|a See the full blog entry at: http://blogs.phparch.com/mt/archives/000048.html “What’s a polar bear?” “A rectangular bear after a coordinate transform.” — Bill White (appeared in a newsgroup posting by Andrei Zmievski, PHP internals hacker and PHP-GTK developer) & P I E C E S Bits & Pieces Security by Obscurity Recently on comp.lang.php there was a rather heated discussion on security by obscurity Everyone knows (or will learn) that security by obscurity is not really security at all, but Bill S offered an interesting analogy on the subject His original question to the list was about how to prevent the version of PHP from being detected, for which he offered the following reason: Taken by Anya Interesting Quotes “The reasonable man adapt himself to the world; the unreasonable one persists in trying to adapt the world to himself Therefore all progress depends on the unreasonable man.” — George Bernard Shaw “As for why I want to this, it is a paranoid attempt to gain an admittedly small measure of security If all the pages are served with htm/html extensions, one would have to resort to other means to ascertain what back end scripting language, if any, is in use I imagine there could be some future php exploits, so I would prefer to make the task a little more difficult.” “ with straight C (and messy pointer problems) you can add a printf to display the value of a variable, and have the code work, comment out the printf and the code fails I consider this Heisenberg’s uncertainty prin- As you can imagine, this raised some hackles His further explanation offers what I found to be an interesting analogy, although I think it fails to hold a great deal of water in this particular situation August 2003 · PHP Architect · www.phparch.com 69 Bits & Pieces “If I took a lot of time to plug almost all the major holes in the cheese, I would still cover the while thing with a napkin since I can’t be 100% certain that I have not missed a small hole or two, or perhaps a hole could materialize later, and then the napkin will serve a useful purpose in obscuring the remaining holes Now, a lot more effort and highly concentrated pokes are required to find a hole, and hopefully the effort required to find those holes will discourage most, as they move on to easier targets If a hole becomes known, by all means not rely on the napkin—fill it! If you become complacent by depending on the napkin to stop a poke, and you quit checking for new holes, then it is a matter of time before the worst happens As the number of holes inevitably grows, the probability of a breach grows, so the effectiveness of the napkin diminishes over time As the size and number of holes diminishes, but is never zero, the probabilistic effectiveness of the napkin grows against random attackers Of course, if someone happens to know your cheese very well, the napkin will be useless against that person since he knows exactly where to poke, even though it may have served a useful purpose against a number of other assailants that didn’t know where to look The napkin should not be judged as ineffective just because of this breach since it prevented a number of other otherwise successful attacks from people who were merely probing for holes.” “So assuming a sound overall security policy is in place, and we have prevented a number of otherwise successful attacks, if I can furthermore prevent at least one otherwise successful attack by obscuring information about my system in some way (OS, directories, servers) at minimal cost and without breaking normal client interactions, I will it in addition to the obviously needed robust measures.” A later post by Brandon Blackmoor offered the following fatal flaw: “The “napkin” (the illusion of security) is counterproductive because it *delays* the discovery and removal of security holes, and because it creates a false sense of security Eschew ‘napkins’.” An interesting discussion August 2003 · PHP Architect · www.phparch.com Errata: There was a small error in last month’s Geeklog article, found in a comment thread on the Geeklog site (http://www.geeklog.net/article.php?story=2003071 1214739561#comments) Dtrumbower, on July 14 2003, mentioned that the link in installation step should be http://yourgeeklogsite/admin/install/install.php, not http://yourgeeklogsite/admin/install/check.php Monster Quiz This is a skill-testing question taken from a recent job posting (related to PHP) on http://www.monster.ca See if you’d get the job ** How to apply ** • The subject of the email must be the result of the Subject() function as defined below • Attach your résumé • Send the email to job@example.com Note: This is not in any particular language and is meant to be doable with paper & pencil Define Compute_DA(x) { temp = (x + 1) / 4; if (temp >= 1) then return x * Compute_DA(temp+1); else return x; } Define Subject() { LookingFor = “Job”; Job = “Good”; LaserRegistration = “Ultimate”; Programming = Get Pointer(“Job”); Answer = Programming->; Quote = Char(34); Test = “Job=” + Quote + LaserRegistration + “Answer” + Quote; Evaluate(Test); Solution = Job + “=” + Compute_DA(7); return Solution; } • The answer (at least the answer I got) is UltimateAnswer=22 “Frankly, I don’t see the harm in making things less obvious as long as one does not rely primarily on obscurity as a security policy—that would be akin to covering a block of swiss cheese with a napkin and saying it is impenetrable It would not require too many pokes to find a gaping hole in the cheese, since the napkin is clearly not offering strong protection, and no one in their right mind should think so.” php|a 70 Expect More From php|a By Marco Tabini e x i t ( ) ; T raditionally, the summer months are a period of rest and relaxation for the publishing industry, when journalists and editorial staff alike take a break from the hectic schedule that getting a magazine on the newsstands (even the virtual kind) every month dictates In Italy, most specialized magazines don't even publish an issue in August—and skip directly over to September, when they start gearing up for the traditional rush that the holiday season brings For some reason, however, we at php|a have never been as busy as we have over the past few months— and the trend will likely continue for a long time to come Just last month, we announced that in September we'll start publishing the print edition of our magazine—and, believe me, that is no small task Thanks in part to the fact that some of us have had a long experience with the print world, the transition has been going very smoothly, but it remains a long process, and fraught with peril at every corner We take it on gladly, of course, knowing that we'll satisfy the needs of many new readers—and, hopefully, of some existing ones This month, we're finally announcing the winners of our Grant Program It took several weeks to decide which were the best choices from the hundreds of proposals that we received I'm happy to report that both our winners have the great potential of taking PHP into new worlds—the medical management arena, known for its strict requirements for accuracy and reliability, and network management, where interaction with a multitude of different systems is paramount Our new website, which we also launched last month (and was cause of many a discussion on the usefulness of code validation), provides us with a much more stable platform for promoting our products—and, much more importantly, for interacting even better with you We've recently stepped up our news reporting efforts (and, dare I say, Eddie Peloke, our online news editor, is doing an excellent job) We've even started selling PHP-related products through our online store (http://www.phparch.com/shop_phpa.php), with the long-term goal of creating a unique shopping experience designed exclusively for PHP users In the months to come, expect us to add more and more products to our store at the best prices around, and because our store is dedicated only to PHP, you can also expect the lowest noise-to-signal ratio If that wasn't enough, this month we're announcing yet another initiative, one that is, in my opinion, both fun and original PHP conferences have been around for a long time, and some of them have gotten really good However, being that none of us really gets any vacation time, we're trying to take one step further, and hold a PHP conference onboard a beautiful and luxurious cruise ship sailing to the Caribbeans Over the course of five days, we'll have plenty of time to chill out—and, given the amount of time that we spend indoors, get lots of sunburn Just because we're going on a cruise, however, doesn't mean that we're not serious about learning PHP: we've scheduled over 50 hours of talks (in 26 two-hour sessions) from some of the best PHP minds in the world And, with early-bird prices starting at $799 (inclusive of all conference fees, full accommodation and all meals aboard the ship), and two chances to get your pass for free if you sign up before October 31st, we think it's a pretty good deal, too You can find out more about this event by taking your browser to http://www.phparch.com/cruise We'd love to see you there! As you see, we're always at work to bring new and exciting initiatives, and trying to improve the ones we've already started More is coming over the next few months, as our family expands into new territory—but, at the base, there remains our commitment to remain open and accessible about what we We'll always be just one e-mail (at info@phparch.com) or forum post (at http://www.phparch.com/discuss) away Just don't talk to me about W3C coding standards, and we can all be friends! August 2003 · PHP Architect · www.phparch.com 71 ... brian@phparch.com Editorial Team Arbi Arzoumani Brian Jones Eddie Peloke Peter James Marco Tabini Graphics & Layout Arbi Arzoumani, William Martin Managing Editor Emanuela Corso Authors Greame... agree that we will charge your account in Canadian dollars for the “CAD” amounts indicated above Because of fluctuations in the exchange rates, the actual amount charged in your currency on your. .. relationships are doable in two clicks and a drag Many-to-many relationships require a comparable amount of work, but automatically create the association mapping table, which saves a fair bit of

Ngày đăng: 17/01/2014, 18:20

TỪ KHÓA LIÊN QUAN

w