Home Backend Development PHP Tutorial PHP Learning Guide-Chapter 9

PHP Learning Guide-Chapter 9

Dec 23, 2016 am 09:54 AM
php learning

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.

PHP Learning Guide-Chapter 9

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)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
How to learn PHP development? How to learn PHP development? Jun 12, 2023 am 08:09 AM

With the development of the Internet, the demand for dynamic web pages is increasing. As a mainstream programming language, PHP is widely used in web development. So, for beginners, how to learn PHP development? 1. Understand the basic knowledge of PHP. PHP is a scripting language that can be directly embedded in HTML code and parsed and run through a web server. Therefore, before learning PHP, you can first understand the basics of front-end technologies such as HTML, CSS, and JavaScript to better understand the operation of PHP.

PHP study notes: modular development and code reuse PHP study notes: modular development and code reuse Oct 10, 2023 pm 12:58 PM

PHP study notes: Modular development and code reuse Introduction: In software development, modular development and code reuse are very important concepts. Modular development can decompose complex systems into manageable small modules, improving development efficiency and code maintainability; while code reuse can reduce redundant code and improve code reusability. In PHP development, we can achieve modular development and code reuse through some technical means. This article will introduce some commonly used technologies and specific code examples to help readers better understand and apply these concepts.

PHP study notes: web crawlers and data collection PHP study notes: web crawlers and data collection Oct 08, 2023 pm 12:04 PM

PHP study notes: Web crawler and data collection Introduction: A web crawler is a tool that automatically crawls data from the Internet. It can simulate human behavior, browse web pages and collect the required data. As a popular server-side scripting language, PHP also plays an important role in the field of web crawlers and data collection. This article will explain how to write a web crawler using PHP and provide practical code examples. 1. Basic principles of web crawlers The basic principles of web crawlers are to send HTTP requests, receive and parse the H response of the server.

PHP study notes: performance analysis and tuning PHP study notes: performance analysis and tuning Oct 08, 2023 pm 03:21 PM

PHP study notes: Performance analysis and tuning Introduction: In web development, performance is a very critical factor. A high-performance website can provide a better user experience, improve user retention, and increase business revenue. In PHP development, performance optimization is a common and important issue. This article will introduce performance analysis and tuning methods in PHP, and provide specific code examples to help readers better understand and apply these techniques. 1. Performance analysis tool Xdebug extension Xdebug is a powerful P

What is the best way to learn PHP in 2023? What is the best way to learn PHP in 2023? Sep 10, 2023 pm 09:16 PM

What is the best way to learn PHP in 2023? With the rapid development of the Internet, computer programming has become a skill with extremely high employment prospects. Among many programming languages, PHP is a language that is widely used in network development. If you want to learn PHP, it's important to know the best way to learn it. PHP is an open source, server-side scripting language used to develop dynamic websites and applications. Compared to other languages, PHP has a lower learning curve and a wide range of applications, making it an ideal choice for beginners.

Learn video special effects and filter processing functions in PHP Learn video special effects and filter processing functions in PHP Aug 07, 2023 pm 11:53 PM

Learn video special effects and filter processing function methods in PHP. PHP is a powerful programming language that is widely used in the field of web development. With the development of website design, video special effects and filter processing are becoming more and more popular. This article will introduce how to use PHP to implement video special effects and filter processing, as well as some commonly used function methods. 1. Install the ffmpeg extension. To process videos, we need to install the ffmpeg extension. Through this extension, we can directly call the ffmpeg command in PHP for video processing. Installation process

PHP study notes: form processing and data validation PHP study notes: form processing and data validation Oct 09, 2023 am 08:52 AM

PHP study notes: Form processing and data validation In web development, forms are one of the important components for users to interact with the website. When users fill out forms and submit data on the website, the website needs to process and verify the submitted data to ensure the accuracy and security of the data. This article will introduce how to use PHP to process forms and perform data validation, and provide specific code examples. Form submission and data preprocessing In HTML, we need to use the &lt;form&gt; tag to create a form and specify the form

PHP study notes: front-end and back-end separation and API design PHP study notes: front-end and back-end separation and API design Oct 08, 2023 am 09:42 AM

PHP study notes: Overview of front-end and back-end separation and API design: With the continuous development of the Internet and the increasing user needs, the development model of front-end and back-end separation has attracted more and more attention from developers. Front-end and back-end separation refers to separating the development of the front-end and the back-end, and conducting data interaction through APIs to achieve development efficiency and flexibility. This article will introduce the concept of front-end and back-end separation, and how to design an API. The concept of front-end and back-end separation: The traditional Web development model is front-end and back-end coupling, that is, the development of front-end and back-end is carried out in the same project.

See all articles