PHP and MySQL Web Development - P11 doc

5 397 0
PHP and MySQL Web Development - P11 doc

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

Thông tin tài liệu

17 Embedding PHP in HTML n ASP style <% echo '<p>Order processed.</p>'; %> This style of tag is the same as used in Active Server Pages (ASP). It can be used if you have enabled the asp_tags configuration setting.You might want to use this style of tag if you are using an editor that is geared toward ASP or if you already program in ASP. PHP Statements We tell the PHP interpreter what to do by having PHP statements between our opening and closing tags. In this example, we used only one type of statement: echo '<p>Order processed.</p>'; As you have probably guessed, using the echo construct has a very simple result; it prints (or echoes) the string passed to it to the browser. In Figure 1.2, you can see the result is that the text "Order processed." appears in the browser window. You will notice that a semicolon appears at the end of the echo statement.This is used to separate statements in PHP much like a period is used to separate sentences in English. If you have programmed in C or Java before, you will be familiar with using the semicolon in this way. Leaving the semicolon off is a common syntax error that is easily made. However, it’s equally easy to find and to correct. Whitespace Spacing characters such as new lines (carriage returns), spaces, and tabs are known as whitespace. As you probably already know, browsers ignore whitespace in HTML. So does the PHP engine. Consider these two HTML fragments: <h1>Welcome to Bob's Auto Parts!</h1><p>What would you like to order today?</p> and <h1>Welcome to Bob's Auto Parts!</h1> <p>What would you like to order today?</p> These two snippets of HTML code produce identical output because they appear the same to the browser. However, you can and are encouraged to use whitespace in your HTML as an aid to humans—to enhance the readability of your HTML code.The same is true for PHP.There is no need to have any whitespace between PHP statements, but it makes the code easier to read if we put each statement on a separate line. For example, echo 'hello '; echo 'world'; 03 525x ch01 1/24/03 3:40 PM Page 17 18 Chapter 1 PHP Crash Course and echo 'hello ';echo 'world'; are equivalent, but the first version is easier to read. Comments Comments are exactly that: Comments in code act as notes to people reading the code. Comments can be used to explain the purpose of the script, who wrote it, why they wrote it the way they did, when it was last modified, and so on.You will generally find comments in all but the simplest PHP scripts. The PHP interpreter will ignore any text in a comment. Essentially the PHP parser skips over the comments that are equivalent to whitespace. PHP supports C, C++, and shell script style comments. This is a C-style, multiline comment that might appear at the start of our PHP script: /* Author: Bob Smith Last modified: April 10 This script processes the customer orders. */ Multiline comments should begin with a /* and end with */. As in C, multiline com- ments cannot be nested. You can also use single line comments, either in the C++ style: echo '<p>Order processed.</p>'; // Start printing order or in the shell script style: echo '<p>Order processed.</p>'; # Start printing order With both of these styles, everything after the comment symbol (# or //) is a comment until we reach the end of the line or the ending PHP tag, whichever comes first. Adding Dynamic Content So far, we haven’t used PHP to do anything we couldn’t have done with plain HTML. The main reason for using a server-side scripting language is to be able to provide dynamic content to a site’s users.This is an important application because content that changes according to a user’s needs or over time will keep visitors coming back to a site. PHP allows us to do this easily. Let’s start with a simple example. Replace the PHP in processorder.php with the following code: <?php echo '<p>Order processed at '; echo date('H:i, jS F'); echo '</p>'; ?> 03 525x ch01 1/24/03 3:40 PM Page 18 19 Adding Dynamic Content In this code, we are using PHP’s built-in date() function to tell the customer the date and time when his order was processed.This will be different each time the script is run. The output of running the script on one occasion is shown in Figure 1.3. Figure 1.3 PHP’s date() function returns a formatted date string. Calling Functions Look at the call to date().This is the general form that function calls take. PHP has an extensive library of functions you can use when developing Web applications. Most of these functions need to have some data passed to them and return some data. Look at the function call: date('H:i, jS F') Notice that we are passing a string (text data) to the function inside a pair of parenthe- ses.This is called the function’s argument or parameter.These arguments are the input used by the function to output some specific results. The date() Function The date() function expects the argument you pass it to be a format string, represent- ing the style of output you would like. Each of the letters in the string represents one part of the date and time. H is the hour in a 24-hour format, i is the minutes with a leading zero where required, j is the day of the month without a leading zero, S repre- sents the ordinal suffix (in this case "th"), and F is the full name of the month. (For a full list of formats supported by date(), see Chapter 18,“Managing the Date and Time.”) 03 525x ch01 1/24/03 3:40 PM Page 19 20 Chapter 1 PHP Crash Course Accessing Form Variables The whole point of using the order form is to collect the customer order. Getting the details of what the customer typed in is very easy in PHP, but the exact method depends on the version of PHP you are using and a setting in your php.ini file. Form Variables Within your PHP script, you can access each of the form fields as a PHP variable whose name relates to the name of the form field.You can recognize variable names in PHP because they all start with a dollar sign ($). (Forgetting the dollar sign is a common pro- gramming error.) Depending on your PHP version and setup, there are three ways of accessing the form data via variables.These methods do not have official names, so we have nick- named them short, medium, and long style. In any case, each form field on a page that is submitted to a PHP script is available in the script. You can access the contents of the field tireqty in the following ways: $tireqty // short style $_POST['tireqty'] // medium style $HTTP_POST_VARS['tireqty'] // long style In this example, and throughout this book, we have used the long style for referencing form variables, but we create short versions of the variables for ease of use.This is a con- venient, secure way of handling data that will work on all systems regardless of version or settings. For your own code, you might decide to use a different approach, but you should make an informed choice, so we will cover the different methods now. In brief: n Short style is convenient, but requires the register_globals configuration setting to be on. (By default, whether it is on or off depends on the version of PHP.) This style also allows you to make errors that could make your code insecure. n Medium style is fairly convenient, but only came into existence with PHP 4.1.0, so it will not work on older installations. n Long style is the most verbose, but is the only style that is guaranteed at present to work on every server, regardless of the configuration. Note, however, that it is dep- recated and is therefore likely to be removed in the long term. We want the sample code in the book to work without alteration on as many readers’ systems as possible, which is why we have chosen the long style, but your decision will probably be different. When using short style, the names of the variables in the script are the same as the names of the form fields in the HTML form.You don’t need to declare the variables or take any action to create these variables in your script.They are passed into your script, essentially as arguments are passed to a function. If you are using this style, you can just 03 525x ch01 1/24/03 3:40 PM Page 20 21 Accessing Form Variables use a variable like $tireqty.The field tireqty in the form creates the variable $tireqty in the processing script. Using short style requires that a setting called register_globals is turned on in your php.ini configuration file. In PHP from version 4.2.0 onward it is off by default. In older versions it is on by default. Such convenient access to variables is appealing, but before simply turning register_globals on, it is worth considering why the PHP development team sets it to off. Having direct access to variables like this is very convenient, but it does allow you to make programming mistakes that could compromise the security of your scripts.With form variables automatically turned into global variables like this, there is no obvious separation between variables that you have created, and untrusted variables that have come directly from the user. If you are not careful to give all your own variables a starting value, then users of your scripts can pass variables and values as form variables that will be mixed with your own. If you choose to use the convenient short style of accessing variables, you need to be careful to give all your own variables a starting value. Medium style involves retrieving form variables from one of the arrays $_POST, $_GET, and $_REQUEST. One of $_GET or $_POST arrays will hold the details of all the form variables.Which array is used depends on whether the method used to submit the form was POST or GET, respectively. In addition, all data submitted via POST or GET will be available through $_REQUEST. If the form was submitted via the POST method, then the data entered in the tireqty box will be stored in $_POST['tireqty']. If the form was submitted via GET, then the data will be in $_GET['tireqty']. In either case, the data will be available in $_REQUEST['tireqty']. These arrays are some of the new so-called superglobals.We will revisit the super- globals when we talk about variable scope. If you are using an older version of PHP, you might not have access to $_POST or $_GET.Prior to version 4.1.0, this information was stored in arrays named $HTTP_POST_VARS and $HTTP_GET_VARS.We are calling this long style.This style can be used with new or old versions of PHP, but has been deprecated so may not work with all future versions.There is no equivalent of $_REQUEST in this style. If you are using long style, you can access the user’s response through $HTTP_POST_VARS['tireqty'] or $HTTP_GET_VARS['tireqty']. Throughout the book, we have tried to remember to point out where examples might not work with older versions, but the examples in the book were tested with PHP version 4.3 and will sometimes be incompatible with versions of PHP prior to ver- sion 4.1.0.We recommend that, where possible, you use the current version. You might have noticed that we don’t, at this stage, check the variable contents to make sure that sensible data has been entered in each of the form fields.Try entering deliberately wrong data and observing what happens. After you have read the rest of the chapter, you might want to try adding some data validation to this script. 03 525x ch01 1/24/03 3:40 PM Page 21 . method depends on the version of PHP you are using and a setting in your php. ini file. Form Variables Within your PHP script, you can access each of the form fields as a PHP variable whose name relates. it was last modified, and so on.You will generally find comments in all but the simplest PHP scripts. The PHP interpreter will ignore any text in a comment. Essentially the PHP parser skips over. that are equivalent to whitespace. PHP supports C, C++, and shell script style comments. This is a C-style, multiline comment that might appear at the start of our PHP script: /* Author: Bob Smith Last

Ngày đăng: 07/07/2014, 03:20

Từ khóa liên quan

Mục lục

  • PHP and MySQL Web Development

  • Copyright

  • Table of Contents

  • Introduction

  • Part I: Using PHP

    • Chapter 1: PHP Crash Course

    • Chapter 2: Storing and Retrieving Data

    • Chapter 3: Using Arrays

    • Chapter 4: String Manipulation and Regular Expressions

    • Chapter 5: Reusing Code and Writing Functions

    • Chapter 6: Object-Oriented PHP

    • Part II: Using MySQL

      • Chapter 7: Designing Your Web Database

      • Chapter 8: Creating Your Web Database

      • Chapter 9: Working with Your MySQL Database

      • Chapter 10: Accessing Your MySQL Database from the Web with PHP

      • Chapter 11: Advanced MySQL

      • Part III: E-commerce and Security

        • Chapter 12: Running an E-commerce Site

        • Chapter 13: E-commerce Security Issues

        • Chapter 14: Implementing Authentication with PHP and MySQL

        • Chapter 15: Implementing Secure Transactions with PHP and MySQL

        • Part IV: Advanced PHP Techniques

          • Chapter 16: Interacting with the File System and the Server

Tài liệu cùng người dùng

Tài liệu liên quan