Combining HTML and PHP Code on a Single Page In some circumstances, you may want to include form-parsing code on the same page as a hard-coded HTML form. Such a combination can be useful if you need to present the same form to the user more than once. You would have more flexibility if you were to write the entire page dynamically, of course, but you would miss out on one of the great strengths of PHP. The more standard HTML you can leave in your pages, the easier they will be for designers and page builders to amend without reference to you. You should avoid scattering substantial chunks of PHP code throughout your documents, however. This will make them hard to read and maintain. Where possible you should create functions that can be called from within your HTML code, and can be reused in other projects. For the following examples, imagine that we are creating a site that teaches basic math to preschool children and have been asked to create a script that takes a number from form input and tells the user whether it is larger or smaller than a predefined integer. A PHP Guessing Script <?php $num_to_guess = 42; $message = ""; if ( ! isset( $guess ) ) { $message = "Welcome to the guessing machine!"; } elseif ( $guess > $num_to_guess ) { $message = "$guess is too big! Try a smaller number"; } elseif ( $guess < $num_to_guess ) { $message = "$guess is too small! Try a larger number"; } else // must be equivalent { $message = "Well done!"; } ?> <html> <head> <title>A PHP number guessing script</title> </head> <body> <h1> <?php print $message ?> </h1> <form action="<?php print $PHP_SELF?>" method="POST"> Type your guess here: <input type="text" name="guess"> </form> </body> </html> Whatever we name the page that contains this form, the form always calls it because we have assigned the value of $PHP_SELF to the FORM element's ACTION argument. Note that we have not created a submit button. Most recent browsers will submit a form consisting of a single text field when the user hits the return key, but you should be aware that some older browsers cannot do this. The bulk of this script consists of an if statement that determines which string to assign to the variable $message. If the $guess variable has not been defined, we assume that the user has arrived for the first time and assign a welcome string the variable. Otherwise, we test the $guess variable against the number we have stored in $num_to_guess, and assign advice to $message accordingly. If $guess is neither larger nor smaller than $num_to_guess, we can assume that it is equivalent and assign a congratulations message to the variable. Now all we need to do is print the $message variable within the body of the HTML. There are a few more additions yet, but you can probably see how easy it would be to hand this page over to a designer. He can make it beautiful without having to disturb the programming in any way. Using Hidden Fields to Save State The last code has no way of knowing how many guesses a user has made. We can use a hidden field to keep track of this. A hidden field behaves exactly the same as a text field, except that the user cannot see it, unless he views the HTML source of the document that contains it. This code adds a hidden field to the number guessing script and some PHP to work with it. Saving State with a Hidden Field <?php $num_to_guess = 42; $message = ""; $num_tries = ( isset( $num_tries ) ) ? ++$num_tries : 0; if ( ! isset( $guess ) ) { $message = "Welcome to the guessing machine!"; } elseif ( $guess > $num_to_guess ) { $message = "$guess is too big! Try a smaller number"; } elseif ( $guess < $num_to_guess ) { $message = "$guess is too small! Try a larger number"; } else // must be equivalent { $message = "Well done!"; } $guess = (int) $guess; ?> <html> <head> <title>Saving state with a hidden field</title> </head> <body> <h1> <?php print $message ?> </h1> Guess number: <?php print $num_tries?> <form action="<?php print $PHP_SELF?>" method="POST"> Type your guess here: <input type="text" name="guess" value="<?php print $guess?>"> <input type="hidden" name="num_tries" value="<?php print $num_tries?>"> </form> </body> </html> The hidden field is given the name "num_tries". We also use PHP to write its value. While we're at it, we do the same for the "guess" field, so that the user can always see his last guess. This technique is useful for scripts that parse user input. If we were to reject a form submission for some reason we can at least allow our user to edit his previous query. File Upload Forms and Scripts So far we've looked at simple form input. Browsers Netscape 2 or better and Internet Explorer 4 or better all support file uploads, and so, of course, does PHP4. In this section, you will examine the features that PHP makes available to deal with this kind of input. First, we need to create the HTML. HTML forms that include file upload fields must include an ENCTYPE argument: ENCTYPE="multipart/form-data" PHP also requires that a hidden field be included before the file upload field. This should be called MAX_FILE_SIZE and should have a value representing the maximum size in bytes of the file that you are willing to accept. This size cannot override the maximum size set in the upload_max_filesize field in your php.ini file that defaults to 2 megabytes. After the MAX_FILE_SIZE field has been entered, you are ready to add the upload field itself. This is simply an INPUT element with a TYPE argument of "file". You can give it any name you want. A Simple File Upload Form <html> <head> <title>A simple file upload form</title> </head> <body> <form enctype="multipart/form-data" action="<?print $PHP_SELF?>"method="POST"> <input type="hidden" name="MAX_FILE_SIZE" value="51200"> <input type="file" name="fupload"><br> <input type="submit" value="upload!"> </form> </body> </html> Notice that once again this form calls the page that contains it. This is because we are going to add some PHP code to handle the uploaded file. We limited file uploads to 50KB and named our upload field "fupload". As you might expect, this name will soon become important. When a file is successfully uploaded, it is given a unique name and stored in a temporary directory (/tmp on UNIX systems). The full path to this file becomes available to you in a global variable with the same name as the file upload form field ($fupload in this case). PHP stores more information about the file for you in a series of global variables. These consist of the variable name (as derived from the form file upload field) followed by an underscore character and "name", "size", and "type".
If a file has been uploaded, the path to the uploaded file on the server is contained in the variable $fupload, and we print this to the browser. We also print the filename, which is stored in $fupload_name, the file's size, which is stored in $fupload_size, If we are dealing with a GIF image, we use the copy() function to copy the uploaded file from its default location to a directory in our server space. The copy() function requires two string arguments; the original and new paths to a file. It returns true if the copy is successful. The original path to our file is stored in $fupload. We have created a variable $file_dir that contains the full path to the directory we want to use to store uploaded images. This, combined with the file's name as stored in $fupload_name, forms the second argument passed to copy(). As a result of this function call, the uploaded file should be copied to our upload directory with its original name restored. Note that on UNIX systems server scripts run as a special user, often 'nobody'. Before you copy a file to a directory you should make sure that your process is allowed to do so. We are using the or operator and the die() function to abort the script if copying fails. and the file's MIME type, which is stored in $fupload_type. |