Cheap Web Hosting for Developers

PHP, MySQL, Java, Unix Cheap Web Hosting

Polymorphism and Self-Modifying Code 81 Indeed, the regular

Filed under: Web Applications Development With PHP4.0 — webmaster @ 21:39

Polymorphism and Self-Modifying Code 83 // see if we ve been invoked with a function string set if(!isset($function_string)) { // no, there s no function string present, // generate an input form print( ); print(

); print( Function definition:
); print( Required PHP code:
); print( ); print(

); print( ); } else { // translate input function to PHP code $parsed_function = parse_function($function_string); // *** NOTE: security holes! (see book contents) *** eval($parsed_function); // create image $image = create_image(); // plot the function for($x = PLOT_MIN; $x < PLOT_MAX; $x += PLOT_STEP) { $y = calculate($req_code, $x); plot($image, $x, $y); } // set content type // header( Content-type: image/gif ); header( Content-type: image/png ); // send image // imagegif($image); imagepng($image); } The script is executable; you can use it directly in your browser. On first invocation, it will notice that you haven t supplied a function to plot yet and display a little input form, as shown in Figure 2.13.

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost PHP Web Hosting services

PHP, MySQL, Java, Unix Cheap Web Hosting

Polymorphism and Self-Modifying Code 81 Indeed, the regular

Filed under: Web Applications Development With PHP4.0 — webmaster @ 21:39

Polymorphism and Self-Modifying Code 81 Indeed, the regular expressions required to transform a simple math function into PHP code are extremely easy.Assuming that all variables consist of a single character and that only legal PHP math operators are used (+, -, *, etc.), the following line can do the job: $php_code = ereg_replace( ([a-zA-Z]) , $\1 , $input_function); This line transforms m * x + b into $m * $x + $b. Building a little bit of code around this regular expression and making a few simplifying assumptions, we can construct a dynamic function plotter very quickly, as shown in Listing 2.6. Listing 2.6 Dynamic function parser and plotter. // // define global constants // define( PLOT_MIN , 0.1); define( PLOT_MAX , 100); define( PLOT_STEP , 0.5); define( DIAGRAM_HEIGHT , 300); define( DIAGRAM_HORIZON , 150); function parse_function($in_string) { // define a custom function header $header = ; $header = $header. function calculate($req_code, $x)n ; $header = $header. {n ; $header = $header. eval($req_code);n ; // define a custom function footer $footer = n}n ; // convert all characters to PHP variables $out_string = ereg_replace( ([a-zA-Z]) , $\1 , $in_string); // prepend header, create equation, and append footer $out_string = $header. return( .$out_string. );n .$footer; // return result return($out_string); } function create_image() { // export this variable global $color_plot; // we calculate the X scale based on the plot parameters continues

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost PHP Web Hosting services

PHP, MySQL, Java, Unix Cheap Web Hosting

78 Chapter 2 Advanced Syntax $mail_text = fetch_mail();

Filed under: PHP Web Hosting — webmaster @ 16:24

80 Chapter 2 Advanced Syntax How does this relate to PHP? Of course, you can t create polymorphic programs like this PHP s architecture prevents runtime modifications of code that has already been parsed but nevertheless there s useful stuff in it. One possibility: dynamic function parsers, as described in the next section. Dynamic Function Generator While we were writing this book, someone in the German PHP mailing list was asking for a way to handle the processing of mathematical functions that were entered by a user. He wanted to know how he could display a function graphically that was entered by a user using a Web formula with PHP, but he didn t know how to deal with the textual input: How could you turn something looking like f(x) = m * x + b into a graph? The discussion quickly moved into one of the traditional paths; everyone started thinking big, really big, instead of seeing the simple, obvious things. Uni sono (Latin, with one voice ), the common method to approach the problem seemed to be the following: 1. Analyze input data. 2. Create a parsed representation (something related to compiler techniques). 3. Let a processor run over the parsed representation and generate step-by-step numerical output data. Our concrete example, f(x) = m * x + b, would look like this: 1. See that this is a function depending on x, where m and b are variables. 2. Create a structure to internally represent the function text for easier handling; for example, make a tree of variable bindings to the multiplication sign (*) and plus sign (+). 3. Let a function vary x (which we found to be the variable this function depends on) and store output data for y, then interpolate. This is the de facto approach taught in universities, seen in complex example sources, and so on. Nobody seemed to be able to make himself free of this pre-thought solution and create a more innovative solution. Ever thought about what PHP does when it interprets your scripts? 1. Analyze input source. 2. Generate a parsed representation. 3. Let a processor run over the parsed representation. Alright, this is very simplified, but basically what we need. So why not transform the input function into valid PHP code and let PHP do the work for us? PHP supports dynamic coding, as you ve seen elsewhere in this chapter, so the whole task could turn into something very trivial.

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Inexpensive Web Hosting services

PHP, MySQL, Java, Unix Cheap Web Hosting

78 Chapter 2 Advanced Syntax $mail_text = fetch_mail();

Filed under: Web Applications Development With PHP4.0 — webmaster @ 16:24

Polymorphism and Self-Modifying Code 79 calls the function whose name has been constructed).This implies that for every possible constructed name, you have to create a function beforehand in order to let the program operate correctly kind of restricting. This can be overcome by completely dynamic programs programs that generate themselves on the fly. Originally, this was an idea from the early days of programming, partially invented by game programmers and virus writers. It all started with self-modifying code. In the inner loops of games for example, the procedures that were responsible for drawing a buffer to the screen speed was (still is) very crucial. However, as processing time was not an infinite resource, people had to think of new ways of getting the most out of their equipment. Often it was the case that, in this innermost loop, quite a few decisions had to take place. For example, if a buffer copy routine only had to copy every second line to the screen on some occasions, you would have a few if()/then constructs embedded into the part of the code that needed them the least.These constructs took away precious processing time, and since this innermost routine was taking something like 80% of the total processing time of the overall program, speeding it up by 50% by removing these constructs would result in 40% additional available computing power. Creating a set of routines to handle each case wouldn t have helped much, however; you would have wasted code space and just moved the decisions elsewhere. Of course, eventually you could have gotten a better overall performance, but not the optimal performance. Thus, the technique of self-modifying code was invented.Whenever a part of the program would modify one of the conditions of the innermost if()/then constructs, instead of adjusting the responsible flags accordingly, it just reprogrammed the inner loop in such a way that it would act as desired; that is, exactly as it would if it would evaluate the flags.The necessary modifications were often only a matter of changing one or two bytes, and no more expensive than setting a set of flags. This would only work on the machine code level, of course, and was extremely system-dependent but it was also extremely powerful. Virus programmers finally took this technique to the extreme by creating polymorphic programs. Polymorphic programs are called polymorphic because they change their own code while still performing the same task.The simplest method to create polymorphic code was to compress the viruses and choose a different compression algorithm or different compression parameters every time.This resulted in different bytecode after every compression, but after decompression the original program was restored. (Try looking at ZIP archives containing the same data with different compression levels they look substantially different, but always expand back to the same data.) The more complicated method was to dynamically regroup instruction blocks while keeping the algorithmic structure intact a method that sometimes required extremely sophisticated code,but that was also very effective.As every method resulted in a change of the bytecode, different signatures for each infection of the virus were created, making it almost impossible for antivirus software to detect them while the viruses were able to happily infect every program they found.

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Inexpensive Web Hosting services

PHP, MySQL, Java, Unix Cheap Web Hosting

78 Chapter 2 Advanced Syntax $mail_text = fetch_mail();

Filed under: PHP Web Hosting — webmaster @ 16:24

78 Chapter 2 Advanced Syntax $mail_text = fetch_mail(); $encoder_type = determine_encoding($mail_text); // returns: base64 for Base64 // returns: uuencoded for .UUEncoded $decoder = decode_ .$encoder_type; $decoded_data = $decoder($mail_text); This code automatically determines the correct handler for the input data. determine_encoding() returns a string indicating the type of data to be decoded, for each of which a corresponding function must exist.The name of the function to be called is then written into $decoder and called right away. The drawback of this method is that it s dirty.You can hardly see a default behavior in it the decoding mechanism is completely dynamic and might crash if determine_encoding() produces a meaningless result. However, it s a very comfortable way to deal with the input data.As soon as new encoding types appear,you only have to create an appropriately named function and adjust determine_encoding() to return the corresponding string. As long as you make determine_encoding() bulletproof, meaning that it will always return a meaningful string (even if it s only a dummy), we would say that this technique is totally legal to use.As long as you can make sure that your script will remain in a defined state throughout runtime, this way of dynamic data handling is fit for production environments. A real-life example of a script that makes extensive use of variable function names is phpIRC (discussed in the following chapter). phpIRC is an IRC layer for PHP, providing access to IRC (Internet Relay Chat) networks through a comfortable API. As the handling of input data is nonlinear and completely user-dependable, phpIRC knows a set of events classifying each incoming packet.The user can install handlers into phpIRC for each event, to be able to react on each type of incoming traffic. phpIRC stores the names of the callback functions in an internal array; as soon as data arrives, it scans its callback array for functions matching the detected type of data, calling all matching functions in a row.This allows for dynamic data processing similar to the email example described earlier, and is very handy when you can (or want to) decide how to deal with upcoming events only at runtime. Taking this further, you can use variable function names to change the behavior of your scripts at runtime and also install user-defined plug-ins that attach themselves to the code at runtime, making additional functionality available to the script without having to change a single line of code. Polymorphism and Self-Modifying Code The drawbacks of variable function names (and partially variable variable names) is that you always have to have a fixed part of the program (in the case of variable function names, a list of previously declared functions that you can use) and then a variable part (the part that constructs the function names into a variable and then

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Inexpensive Web Hosting services

PHP, MySQL, Java, Unix Cheap Web Hosting

Associative Arrays 75 The fact that PHP can t

Filed under: Web Applications Development With PHP4.0 — webmaster @ 11:04

Associative Arrays 77 Variable Function Names Of course, what we said about variable variable names in the preceding section is also valid for function names. Function names can be constructed using variables, providing a dynamic way of processing data, installing modifiable callbacks, and the like. Instead of hardcoding function names, you can use string variables to specify the functions you want to call: function my_func($a, $b) { print( $a, $b ); } $function = my_func ; $function(1, 2); After the declaration of my_func(), the variable $function is assigned a string my_func . Since this string is the same as the name of the function you want to call, you can use it when calling my_func(). Of course,this is a very simple example of variable function names.They re very useful when you have to switch between a set of different functions, depending on a number of variable flags. Suppose you want to decode email attachments.These can have different formats to name just two, base64 and uuencoded. Creating a closed parser that only understands one or two encoding formats and can hardly be extended is not a good idea; as soon as new formats are demanded,you ll be stuck.This case is almost ideal for variable function names: function decode_base64($encoded_data) { // do something with the encoded data return($decoded_data); } function decode_uuencoded($encoded_data) { // do something with the encoded data return($decoded_data); } continues

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost PHP Web Hosting services

PHP, MySQL, Java, Unix Cheap Web Hosting

Associative Arrays 75 The fact that PHP can t

Filed under: Web Applications Development With PHP4.0 — webmaster @ 11:04

76 Chapter 2 Advanced Syntax $$my_var = 1; ?> In the second line, $my_var is prefixed with $$. Basically, this is how variable variable names work. Of course, you could nest variable variable names to get variable variable variable names (and so on), but with variable variable names you can already do pretty neat tricks. A real-life example: phpPolls, the voting booth software described in Chapter 1, Development Concepts, makes use of variable variable names.To protect itself from users voting twice in the same poll, one of the protection mechanisms is based on cookies.Whenever a user votes,a cookie is set,named with a configurable prefix and a unique ID identifying the poll.As cookies are reintroduced into the global namespace, whenever a user tries to submit a vote, phpPolls checks for the existence of a global variable named like the cookie name it constructed before. If a variable with this name exists, phpPolls rejects the vote. To perform this task, variable variable names are extremely handy. Following is an excerpt from the phpPolls source code: $poll_object = mysql_fetch_object($poll_result); $poll_timeStamp = $poll_object->timeStamp; $poll_cookieName = $poll_cookiePrefix.$poll_timeStamp; // check if cookie exists if(isset($$poll_cookieName)) { // cookie exists, invalidate this vote $poll_voteValid = 0; } else { // cookie does not exist yet, set one now setCookie( $poll_cookieName , 1 , $poll_cookieExpiration); } The code first retrieves the unique ID for the cookie, which consists of the poll s timestamp, and then assembles this with the cookie prefix $poll_cookiePrefix to form the name of the wanted variable, $poll_cookieName. Using isset(), the existence of the variable (and thus the cookie) is determined and acted on accordingly.

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost PHP Web Hosting services

PHP, MySQL, Java, Unix Cheap Web Hosting

Associative Arrays 75 The fact that PHP can t

Filed under: Web Applications Development With PHP4.0 — webmaster @ 11:04

Associative Arrays 75 The fact that PHP can t guess which value belongs to which parameter requires you to put all optional parameters at the end of the argument lists. If you d put $hostname as the only required parameter at the end of the list (and $port and $timeout in front of it), the first call that only specified $hostname would make PHP think that the string for the hostname would actually be the value for $port, and thus create a lot of confusion. Also, you can t just pick a random set of optional parameters for which you d like to supply values if you have a function that accepts three optional parameters and you only want to change the last one in the argument list, you still have to supply the default values for the other two parameters. (Shown in the second call above as well, where only $timeout is changed.) In PHP 4.0,real variable arguments are possible.A function can take more arguments than the function definition lists, and you can access any number of arguments with the functions func_get_args(), func_num_args(), and func_get_arg(). The return value of func_get_args() is an indexed array that s filled with all argument values passed to the function, from left to right: function show_arguments() { $argument_array = func_get_args(); for($i=0; $i $argument_array[$i]
); } } show_arguments( Leftmost , Middle , Rightmost ); The func_num_args() function returns the number of passed arguments; func_get_arg() returns a specific argument. For example, func_get_arg(0) would return the first argument. Variable Variable Names Variable variable names. For those who don t know about it (and for us, when we heard it the first time) weird! Variable variable names are about accessing variables whose names you don t know beforehand and construct during runtime.This feature is possible in PHP because of its interpreted nature. PHP just walks through the code and translates whatever it finds to something useful.The following code constitutes the simplest example for variable variable names:

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost PHP Web Hosting services

PHP, MySQL, Java, Unix Cheap Web Hosting

72 Chapter 2 Advanced Syntax Listing 2.5 Usage

Filed under: Web Applications Development With PHP4.0 — webmaster @ 06:39

Associative Arrays 73 $file_handle = fopen($original_file, r ); if(!$file_handle) die( Error opening file. ); // encode it $output = encode_data(); // close input file fclose($file_handle); // open output file $file_handle = fopen($compressed_file, w ); if(!$file_handle) die( Error creating file. ); // write decoded data for($i = 0; $i < count($output); $i++) fputs($file_handle, $output[$i]); // close output file fclose($file_handle); // open input file $file_handle = fopen($compressed_file, r ); if(!$file_handle) die( Error opening file. ); // decode it $output = decode_data(); // close input file fclose($file_handle); // open output file $file_handle = fopen($decompressed_file, w ); if(!$file_handle) die( Error creating file. ); // write decoded data for($i = 0; $i < count($output); $i++) fputs($file_handle, $output[$i]); // close file fclose($file_handle); This example shows very nicely how the decoder and reader logic can be split into smaller,separate functions.The actual decoder is now only a few lines long.The function that supplies input data can be detached from the rest of the code and the decision maker that differentiates between literal and compressed data is again in a separate, small, easy-to-understand function.

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost PHP Web Hosting services

PHP, MySQL, Java, Unix Cheap Web Hosting

72 Chapter 2 Advanced Syntax Listing 2.5 Usage

Filed under: PHP Web Hosting — webmaster @ 06:39

74 Chapter 2 Advanced Syntax A clever trick is to return literal data with a count of 1, so that the decompression loop doesn t have to worry about this again it can simply write the data it s being supplied with to the output array. The error checking could be improved some, but we re leaving this up to the reader. It s not hard to do. Variable Argument Lists Variable argument lists, also often called optional parameters, allow you to pre-assign function parameters with a default value. If the caller doesn t specify a value for the argument,the default value is assumed.This makes it possible to supply the caller with a list of optional parameters that can be used but don t have to be used. Optional parameters are defined as follows: function open_http_connection($hostname, $port = 80, $timeout = 10) { $socket = fsockopen($hostname, $port, $timeout); /* rest of the code goes here */ return($socket); } $regular_socket = open_http_connection( www.myhost.com ); $slow_socket = open_http_connection( www.myhost.com , 80, 20); $test_socket = open_http_connection( testserver.myhost.com , 8080); $slow_test_socket = open_http_connection( testserver.myhost.com , 8080, 20); The function open_http_connection() accepts one regular argument named $hostname that specifies the name of the host to which the function is supposed to connect.Additionally,it has two optional arguments, $port and $timeout, containing the port number to connect to and the connection timeout in seconds, respectively. These two have pre-assigned, default values, indicated by the equal sign (=) followed by the wanted default value.Thus,whenever these arguments are not given by the caller, PHP just replaces the missing fields with their default values. As you can see in the call examples, the very first call only uses $hostname. $port and $timeout are missing, so PHP just fills in the default values, which makes the call equal to this: $regular_socket = open_http_connection( www.myhost.com , 80, 10); In turn, you can still specify the optional parameters and overwrite their defaults, as seen in the second call.The value for $port is still 80, but $timeout is now set at 20 seconds. You need to supply the default arguments whose value you d like to change, as demonstrated by the third example. Here, only $port is given as 8080. $timeout is not given and thus remains at its default value of 10 seconds.

Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost PHP Web Hosting services

« Previous PageNext Page »

Powered by Cheap Web Hosting