


Use HTML forms with PHP to access single and multiple form values_PHP tutorial
The ability to more easily operate on information submitted by users through HTML forms has always been one of PHP's strengths. In fact, PHP version 4.1 adds several new methods for accessing this information and effectively removes one of the most commonly used methods from previous versions. This article examines different ways of working with information submitted on an HTML form, using both older and newer versions of PHP. This article starts by studying a single value and then builds a page that can generally access any available form value. Note: This article assumes you have access to a web server running PHP version 3.0 or higher. You need a basic understanding of PHP itself and creating HTML forms. HTML Forms As you read this article, you'll see how different types of HTML form elements provide information that PHP can access. For this example, I used a simple information form consisting of two text fields, two checkboxes, and a select box that allows multiple items: Listing 1. HTML form
Mission Information
In the absence of a specified method, the form uses the default method GET, which is used by the browser to append the form value to the URL. As shown below: http://www.vanguardreport.com/formaction.php?ship=Midnight+Runner&tripdate=12-15-2433&exploration=yes&crew=snertal&crew=gosny Figure 1 shows the form itself. Figure 1. HTML forms the old way: accessing global variables The code shown in Listing 2 handles form values as global variables: Listing 2. Form values as global variables "; echo "Tripdate = ".$tripdate; echo ""; echo "Exploration = ".$exploration; echo "
"; echo "Contact = ".$contact; ?> The generated Web page displays the submitted value: Ship = Midnight Runner Tripdate = 12-15 -2433 Exploration = yes Contact = (As you will see later, Contact has no value because the box is not checked) The notation in Listing 2 is certainly convenient, but it is only set if the PHP directive register_globals. Available only when on. Before version 4.2, this was the default setting, and many PHP developers were not even aware of this problem. However, starting with version 4.2, the default setting for register_globals is off, in which case. This notation does not work properly because the variables are no longer created and initialized with the appropriate values. However, you can initialize these variables in other ways. The first method is to change the value of register_globals. Many developers using shared servers do not have the permission. Change this value for the entire server, but can change the behavior for a specific site. If you have access to the .htaccess file, you can enable register_globals by adding the following directive: php_flag register_globals on Given the uncertainty about whether this feature is available. , developers are advised not to use or rely on this method of obtaining variables. So what are your options? If your system is running version 4.1 or higher, your other option is to use import_request_variables(). Optionally register a collection of global variables. You can use this function to import get, post, and cookie values, and prefix each item if you wish. For example: "; echo "Tripdate = ".$formval_tripdate; echo "
"; echo "Exploration = ".$formval_exploration; echo "
"; echo "Contact = ".$formval_contact; ?> Here, the get and post values are imported - using c to import the cookie value - and since p follows g, the post value will overwrite the get value of the same name. But what if you, like many developers, are not running version 4.1 or higher? Accessing a Collection of Form Values For those running older versions or who prefer not to use global variables, there is an option to use the $HTTP_GET_VARS and $HTTP_POST_VARS arrays. Although these collections are deprecated, they are still available and are still widely used. When they are no longer used, they will be replaced by the $_GET and $_POST arrays added in version 4.1. The types of these two types of arrays are hash tables. A hash table is an array indexed by string values rather than integers. When working with forms, you can access values by their names, as shown in Listing 3: Listing 3. Accessing form values via hash table $ship_value = $HTTP_GET_VARS[ship]; echo $ship_value; echo " $ship_value = $HTTP_GET_VARS[ship]; echo $ship_value; echo "
"; $tripdate_value = $HTTP_GET_VARS[tripdate]; echo $tripdate_value; echo "
"; $exploration_value= $HTTP_GET_VARS[exploration]; echo $exploration_value; echo "
"; $contact_value = $HTTP_GET_VARS[contact]; echo $contact_value; ?> Using this method you can retrieve the value of each field by name. Single name, multiple values Until now, each name corresponded to only one value. What happens if there are multiple values? For example, the crew species listbox allows multiple values to be submitted with the name crew. Ideally, you want to use the values as an array so you can retrieve them explicitly. You must modify the HTML page slightly. Fields to be submitted as arrays should be named with square brackets, as in crew[]: Listing 4. Modify the HTML page... ... Once you make the change, retrieving the form values actually results in an array: Listing 5. Accessing variables as an array... $crew_values = $HTTP_GET_VARS[crew]; echo "0) ".$crew_values[0]; echo "
"; echo "1) ".$crew_values[1]; echo "
"; echo "2) ".$crew_values[2]; . .. Now, after submitting the page, multiple values will be displayed: 0) snertal 1) gosny 2) First notice that this is an array with indexes starting from 0. The first encountered value is in position 0, and the following ones. The value is at position 1, and so on. In this case, I only submitted two values, so the third item is empty. Usually, you don't know how many items will be submitted, so you can take advantage of the fact that it is an array. sizeof() function to determine how many values were submitted without having to call each item directly: Listing 6. Determining the size of the array... for ($i = 0; $i "; } ... However, sometimes the problem isn't too many values, but rather no values at all. The surprisingly disappearing checkbox only appears when it's actually selected. It's important to realize that otherwise, its disappearance tells you all you need to know: the user didn't click the checkbox. When using a checkbox, you can check it explicitly using the isset() function. Whether the value was set: Listing 7. Check if the checkbox was submitted... $contact_value = $HTTP_GET_VARS[contact]; echo $contact_value; if (isset($contact_value)) { //The checkbox was clicked } else { / /The checkbox wasn't clicked } ... Getting all form values The checkbox field is just one example of a situation where you might not be completely sure about the expected form value names. Often, you will find it useful to have a routine that accesses all form values in a common way. Fortunately, because $HTTP_GET_VARS and its ilk are just hash tables, you can manipulate them with some properties of arrays. For example, you can use the array_keys() function to get a list of all potential value names: Listing 8. Get a list of form value names... $form_fields = array_keys($HTTP_GET_VARS); for ($i = 0; $i "; } .. . In this example, you're actually combining several techniques. First, retrieve an array of form field names and name it $form_fields. The $form_fields array is just a typical array, so you can use the sizeof() function to determine the number of potential keys and loop over each item. For each item, retrieve the name of the field and then use that name to get the actual value. The resulting Web page looks like this: ship = Midnight Runner tripdate = 12-15-2433 exploration = yes crew = Array There are two important things here. First, the contact field returns no value at all, as expected. Second, the crew value (which, by the way, you probably know: its name is crew, not crew[]) is an array, not a value. In order to actually retrieve all values, you need to detect all arrays using the is_array() function and process them accordingly: Listing 9. Processing arrays... for ($i = 0; $i "; } } else { echo $thisField ." = ". $thisValue; } echo "
"; } ... The result is all Actual data submitted: ship = Midnight Runner tripdate = 12-15-2433 exploration = yes crew = snertal crew = gosny One final note: Now that you have a form action page that can accommodate any form value you submit, you need Take a moment to consider a situation that often surprises PHP programmers. In some cases, designers choose to use a graphical button instead of a submit button, as shown in Figure 2 and the code is shown in Listing 10. Listing 10. Adding a graphic button ... Crew sp

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6
Visual web development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!
