Information transfer between web pages
Focus of this chapter
Why does HTTP continue to spread?
GET parameters
Another URL using GET style
Handling form variables
PHP super array
This chapter briefly explains some content about passing data between Web pages. Such information is not unique to PHP, but is an important part of the PHH/HTML or HTTP protocol itself.
HTTP is stateless
One of the most important things to remember about web services is that the HTTP protocol itself is stateless. If you have a poetic soul, you might say that each HTTP request is alone, without a home, like a complete unknown... you know the stuff. For the less poetic among us, this means that each HTTP request (each request and page transfer) is independent of all other content, has no knowledge of the client's identity, and has no memory. Each request generates an independent process, completes a file service, a seemingly small but important task, and then disappears automatically (this sounds very ruthless, perhaps it can be said to be "returning to a processable state").
Even if the website is designed with very loose one-way navigation (page 1 leads to page 2, page 2 leads to 3, etc.), PTTP assistance never knows or cares whether the page 2 someone browses comes from page 1. Therefore, you cannot set variables on page 1 to be imported into the page through the HTML itself. You can use HTML to display a form and use the form to enter some information, but unless you use some other method to transfer the information to another page or another program, the variables disappear once you move to another page.
This is the reason why form processing technology like PHP is imported. PHP can retrieve variables passed from one page to another and make further use of them. PHP functions happen to be very good at this type of data transfer function, which makes it faster and easier to complete various web website tasks.
HTML forms are the most useful method on a website for passing some data from one web page. There are many more persistent ways to maintain state across many web pages, such as cookies and sessions. We will introduce these in Chapter 27 Function. This chapter will focus on more basic techniques for transferring information between web pages, which is to use HTTP and GET and POST methods to dynamically generate web pages and process data.
ASP programmers may say "PHP sucks!" when they see this, because the session variable they used in ASP is very magical. This is not to burst anyone's bubble, but Microsoft is planning to use cookies to store session variables, but this opens the door to all potential problems.
GET parameters
The GET method treats parameters as part of the URI [Uniform Resource Indicator, consistent resource indicator; some people are more accustomed to using URI (Uniform Resource Indicator, consistent resource locator)] query string, from a page Passed to another page. When used for forms processing, GET appends the variable names and values to the URL specified in the ACTION attribute using question marks (?) as delimiters, and submits all content to the technology providing the processing (in this case Web server).
This is an example of an HTML form using the GET method (save the file in team_select.html):
A GET example, part 1
Root , root, root for the :
When the user makes a selection and clicks the Submit button, the browser puts these elements in the following order Joined, together, without spaces in between:
After the word ACTION, the URL (http://localhost/baseball.php) enclosed in quotes
Question mark (?) indicates that the following characters will form the GET string
NAME variable, equal sign, and matching VALUE (Team = Cubbies)
"&" symbol and the next pair "NAME = VALUE" (Submit = Submit); as long as the length limit of the server query string allows, these use & The separated name-value combination can be repeated many times.
This will form a URL string like this:
(http://locahost/baseball .php ? Team = Cubbies&Submit = Select)
The string becomes a new request and is sent to the browser's address space. After the above form is submitted, the PHP script (baseball.php) that processes the form will obtain the GET variables from the end of the request string and perform corresponding operations on these variables. In the following example, two One of the values is inserted into the literal string.
The following program code is the form processing part used by PHP to process the original HTML form:
A GET example ,part 2
BODY {font-size: 24pt;}
-- >
Go,
!
Finally you should see Go, Cubbies in large letters on the web page.
The GET method in form processing has a much better advantage than the POST method: it creates a truly new and completely different URL query string. This way users can bookmark this page (seeing this can be a morale booster when the development team is feeling down). Results obtained from a form using the POST method cannot be bookmarked.
However, just because you can use GET parameters to accomplish what you want doesn't mean you should. For most form handlers, the shortcomings of the GET method are so severe that the original HTML 4.0 official specification deprecated its use. These disadvantages include:
GET is not suitable for login, because the user name and password are hidden and stored in the memory of the client browser as accessed pages, and they are fully visible on the screen. .
Every GET submission is recorded in the web server log, and the data set is also included.
Because GET will allocate data to server environment variables, the length of the URL is limited. You can imagine what a very long URL looks like when using GET, but in reality no one wants to try to deliver a three hundred word HTML article using this method.
The original HTML official specification limited the query string length to 255 characters. Although the 255-character limit was later relaxed, using very long strings is really asking for trouble.
After much debate, W3 still reverted to using the GET method in form processing, mainly due to the bookmark feature. Although the GET method is still the default choice for form processing, we recommend that you only use it where there are no side effects. Putting the two advantages and two disadvantages together, the most suitable use for using GET to process forms should actually be the "search box". Unless you have absolutely no reason to use the GET method in a non-search form handler, use the POST method instead.
A better usage of GET style URL
Although the GET method has been recommended not to be used for form processing. However, the URL style related to it is still very useful for website navigation, especially for websites with dynamic advertisements, such as those websites that are often built with PHP. Because the variable format URL is appended, it is very suitable for templates as the basis. Content development system.
As shown in the following example, assume that you are running a web site with rich information about solar cars, and you have stored the lengthy and consistent format of information-rich and attractive pages as follows:
suspension_design.html
windtunnel_testing .html
friction_braking.html
But when the size of the website increases, such a simple archive website structure will take a lot of time to manage, because some trivial changes must be repeated on each page. If the structure of these pages is very simple, you can use PHP to convert the site to a template-based system.
You may decide to use a single template to separate text files for each topic (including information, photos, opinions, etc.):
topic.php
suspension_design.inc
windtunnel_testing .inc
friction_braking . inc
Or you may decide on a larger, more specifically chosen template file:
vehicle_structure . php
tubular_frames . inc
mechanical_systems . php
friction_braking . inc
electrical_systems . php
solar_array . inc
racing .php
race _strategy . inc
A simple template might look like this (since we didn’t include the required .inc text file, this file won’t actually work):
Solar – car topics
BODY{font:verdana;font - size:12pt}
-- >
Friction braking
Steering
Suspenion
Tires and wheels
Please note that when clicked the link on the navigation bar is processed by the browser as if it were submitted to a GET handler.
But for this solution, you still have to manually change part of the program code: to ensure that each included file is in the correct HTML format, and to add new links to the navigation bar every time a new page is added to the website. and other similar content. Separate form and content as much as possible as a general rule, and you may choose to use a database. If using a database, the URL would look like this:
(http://localhost/topic .php ?topicID = 2)
It would point to a PHP template that handles database calls (using numeric variables instead of using Single words can query the database faster). When a new topic is added to the database, the system will add links to the navigation bar, so all Web pages can be generated without manual work (the word "all" here is a bit exaggerated, but it does save people and excess labor of time).
POST parameters
POST is currently a relatively good form processing method, especially suitable for situations that need not be used all at once (specifying some data or functions for long-term processing), such as adding information to a database. When the form data is passed to the handler (in this case PHP), it is included in the form body. When the submitted information is different, no changes will be seen in the URL.
The POST method has the following advantages:
◎ It is more secure than GET because in the URL query string, server log, or on the screen (if precautions are taken, such as always using the HTML password input format Express password field) cannot see the information entered by the user.
◎ The limit on the amount of data that can be passed is looser (up to 2,000 tuples, not just over 200 characters).
However, POST also has some disadvantages:
◎ The results cannot be marked as bookmarks.
◎ This method is incompatible with some firewall settings. For security reasons, the firewall will remove certain form data.
In this book we consistently use the POST method to process forms, especially when using the SQL syntax of writing to files or INSERT to fill in data into the system. We only use the GET method in the browsing and search boxes of the website. In other words, the timing of use is to write data to the data storage location and display the web page. The rest of the forms in this chapter will use the POST method.
Use both GET and POST methods
Did you know? PHP allows using both GET and POST variables on the same page, so feel free to write dynamic forms!
But this immediately raises a question: What if the same variable name is used in the GET and POST arrays (intentionally or for other reasons)? If you set the register_globals directive in your php .ini file to on, PHP stores variables such as ENVIRONMENT, GET, POST, COOLIE and SERVER in the $GLOBAL array. If a conflict occurs, it will be based on what you set. This is solved by re-adjusting the variable contents in a certain order, by setting the variable_order option in your php.ini. The latter will replace the former, so if you use the default "EGPCS" value, POST will replace GET, and COOKIE will replace POST. You can control the order of substitution by appropriately adjusting the order of letters in this file, or It's even better to turn register_globals off and use PHP's new super-global arrays, which we'll cover in the following section.
Variable handling in PHP
PHP is very efficient for passing data because the developers decided to use a very convenient but (in theory) somewhat complicated design. When submitting a data set using the GET or POST method, PHP automatically and invisibly specifies the variables on the new page. Most other programming languages let the programmer perform explicitly specified processing on the page; if the specification is forgotten or written incorrectly, the information will not be passed to the processing agent. In comparison, PHP is faster, simpler, and more foolproof.
But due to such automatic variable specification, you must always get a good NAME attribute for each INPUT control item. In fact, the NAME attribute is not mandatory for HTML. Your form can still function normally without it, but the data will have no effect because the NAME form field properties of these HTML will be the variable names of the form handler.
In other words, the following form:
" METHOD = "POST" >
< ; INPUT TYPE=“submit” NAME=“Submit” VALUE=“Send” >
email text field will cause PHP to generate a variable $_OPET[ 'email' when the form is sent ] (or $HTTP_POST_VARS[ 'email'] if you use old-style array variables, or even $email if you enable register_globals). Likewise, the submit button will cause the next page to generate $_POST ['submit' ] variable, the name you use in the HTML form will become the variable form field processed by your PHP form.
Another thing you must remember when generating and generating HTML forms is that if you want the form to display initial text before filling it out, you must set the VALUE attribute. This is especially useful on two types of forms: used to enter data library forms, and forms that are used to deliver more than once, the latter often occurring when the form needs to be redisplayed in the event of an input error. For example, a form used to log in will not enter a valid email address until it is used. Or other relevant information can be sent.
For example, the following form (used as a pension spreadsheet) is designed to be sent multiple times as the user fills in the information. Whenever you send the form, the information you filled in previously will be automatically Fill in, please pay attention to the VALUE attribute of the form field in the following program example.
A POST example:retirement savings worksheet
< ; !- -
BODY {font-size:14pt}
.heading {font-size:18pt; color:red}
-->
//This test,along with the Submit button value in the form below,
//will check to see if the form is being rendered for the first time
//(in which case it will display with only the default annual gain
//filled in )
If (!IsSet($_POST[′Submit?])||$_POST[′Submit?]!=′Calculate?){
$_POST['CurrentAge'] = "";
$_POST['RetieAge'] = "";
$_POST['Contrib'] = "";
$Total = 7;
}else{
$AnnGain = $_POST['AnnGain'];
$Years = $_POST['RetireAge'] - $_POST['CurrentAge'];
$YearCount = 0;
$Total = $_POST['Countrib '];
While($YearCount
$Total = round($Total *(1.0 + $AnnGain/100)+$_POST['Contrib']);
$YearCount = $YearCount +1;
}
}
? >
A retirement – savings calculator
Fill in all the values(except “Nest Egg”)and see how much money you′ll have for your retirement under different scenarios.You can change the values and resubmit the form as many times as you like.You must fill in the two “Age” variables.The “Annual return” variable has a default inflation-adjusted value (7% = 8% growth minus 1% inflation)which you can change to reflect your greater optimism or pessimism.
Your age now:
The age at which you plan to retire:
NAME = "RetireAge" VALUE = "" >
Annual contribution: 〈 INPUT TYPE="text" SIZE=15 NAME="Contrib" VALUE=" “ >
Annual return: %
NEST EGG:
Figure 9-1 shows the results of the above program.
Figure 9-1: Form using methods and VALUE attributes
Enhancing forms and form processing
As you can see in the above program, it is usually simple to put the HTML form and the form handler in the same program, like this There are many advantages to this approach. For example, your login page will display an error message if the login fails. If you separate the form handler, you may need to additionally redirect via GET variables. If you enhance the form operation If so, you can more easily control the display without using such a mechanism.
When you enhance the form, the form handler should appear before the form is displayed. Some people may think that the order should be reversed because the form is designed first and then the handler, but if you follow the method here, you will understand The logic here, you must enable you to name the variables first and make selections before displaying the form. This is useful if you must direct the user to a different web page in some cases, by using the header () function, more Important because this decision must be made before any HTML output is displayed in the browser.
The above is the content of Chapter 9 of the PHP Learning Guide. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!