Hướng dẫn php external function

HTML Forms [GET and POST]

When a form is submitted to a PHP script, the information from that form is automatically made available to the script. There are few ways to access this information, for example:

Example #1 A simple HTML form

    Name:  
Email:

There are only two ways to access data from your HTML forms. Currently available methods are listed below:

Example #2 Accessing data from a simple POST HTML form

Using a GET form is similar except you'll use the appropriate GET predefined variable instead. GET also applies to the QUERY_STRING [the information after the '?' in a URL]. So, for example, //www.example.com/test.php?id=3 contains GET data which is accessible with $_GET['id']. See also $_REQUEST.

Note:

Dots and spaces in variable names are converted to underscores. For example becomes $_REQUEST["a_b"].

PHP also understands arrays in the context of form variables [see the related faq]. You may, for example, group related variables together, or use this feature to retrieve values from a multiple select input. For example, let's post a form to itself and upon submission display the data:

Example #3 More complex form variables



    Name:  
    Email: 
    Beer: 
    
        Warthog
        Guinness
        Stuttgarter Schwabenbräu
    
    

Note: If an external variable name begins with a valid array syntax, trailing characters are silently ignored. For example, becomes $_REQUEST['foo']['bar'].

IMAGE SUBMIT variable names

When submitting a form, it is possible to use an image instead of the standard submit button with a tag like:

When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables, sub_x and sub_y. These contain the coordinates of the user click within the image. The experienced may note that the actual variable names sent by the browser contains a period rather than an underscore, but PHP converts the period to an underscore automatically.

HTTP Cookies

PHP transparently supports HTTP cookies as defined by » RFC 6265. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the setcookie[] function. Cookies are part of the HTTP header, so the SetCookie function must be called before any output is sent to the browser. This is the same restriction as for the header[] function. Cookie data is then available in the appropriate cookie data arrays, such as $_COOKIE as well as in $_REQUEST. See the setcookie[] manual page for more details and examples.

Note: As of PHP 7.2.34, 7.3.23 and 7.4.11, respectively, the names of incoming cookies are no longer url-decoded for security reasons.

If you wish to assign multiple values to a single cookie variable, you may assign it as an array. For example:

That will create two separate cookies although MyCookie will now be a single array in your script. If you want to set just one cookie with multiple values, consider using serialize[] or explode[] on the value first.

Note that a cookie will replace a previous cookie by the same name in your browser unless the path or domain is different. So, for a shopping cart application you may want to keep a counter and pass this along. i.e.

Example #4 A setcookie[] example

Dots in incoming variable names

Typically, PHP does not alter the names of variables when they are passed into a script. However, it should be noted that the dot [period, full stop] is not a valid character in a PHP variable name. For the reason, look at it:

Now, what the parser sees is a variable named $varname, followed by the string concatenation operator, followed by the barestring [i.e. unquoted string which doesn't match any known key or reserved words] 'ext'. Obviously, this doesn't have the intended result.

For this reason, it is important to note that PHP will automatically replace any dots in incoming variable names with underscores.

Determining variable types

Because PHP determines the types of variables and converts them [generally] as needed, it is not always obvious what type a given variable is at any one time. PHP includes several functions which find out what type a variable is, such as: gettype[], is_array[], is_float[], is_int[], is_object[], and is_string[]. See also the chapter on Types.

HTTP being a text protocol, most, if not all, content that comes in Superglobal arrays, like $_POST and $_GET will remain as strings. PHP will not try to convert values to a specific type. In the example below, $_GET["var1"] will contain the string "null" and $_GET["var2"], the string "123".

/index.php?var1=null&var2=123

Changelog

VersionDescription
7.2.34, 7.3.23, 7.4.11 The names of incoming cookies are no longer url-decoded for security reasons.

Anonymous

14 years ago

The full list of field-name characters that PHP converts to _ [underscore] is the following [not just dot]:
chr[32] [ ] [space]
chr[46] [.] [dot]
chr[91] [[] [open square bracket]
chr[128] - chr[159] [various]

PHP irreversibly modifies field names containing these characters in an attempt to maintain compatibility with the deprecated register_globals feature.

krydprz at iit dot edu

17 years ago

This post is with regards to handling forms that have more than one submit button.

Suppose we have an HTML form with a submit button specified like this:

Normally the 'value' attribute of the HTML 'input' tag [in this case "Delete"] that creates the submit button can be accessed in PHP after post like this:



We of course use the 'name' of the button as an index into the $_POST array.

This works fine, except when we want to pass more information with the click of this particular button.

Imagine a scenario where you're dealing with user management in some administrative interface.  You are presented with a list of user names queried from a database and wish to add a "Delete" and "Modify" button next to each of the names in the list.  Naturally the 'value' of our buttons in the HTML form that we want to display will be "Delete" and "Modify" since that's what we want to appear on the buttons' faceplates.

Both buttons [Modify and Delete] will be named "action_button" since that's what we want to index the $_POST array with.  In other words, the 'name' of the buttons along cannot carry any uniquely identifying information if we want to process them systematically after submit. Since these buttons will exist for every user in the list, we need some further way to distinguish them, so that we know for which user one of the buttons has been pressed.

Using arrays is the way to go.  Assuming that we know the unique numerical identifier of each user, such as their primary key from the database, and we DON'T wish to protect that number from the public, we can make the 'action_button' into an array and use the user's unique numerical identifier as a key in this array.

Our HTML code to display the buttons will become:


The 0000000002 is of course the unique numerical identifier for this particular user.

Then when we handle this form in PHP we need to do the following to extract both the 'value' of the button ["Delete" or "Modify"] and the unique numerical identifier of the user we wish to affect [0000000002 in this case]. The following will print either "Modify" or "Delete", as well as the unique number of the user:



$submitted_array[0] carries the 0000000002.
When we index that into the $_POST['action_button'], like we did above, we will extract the string that was used as 'value' in the HTML code 'input' tag that created this button.

If we wish to protect the unique numerical identifier, we must use some other uniquely identifying attribute of each user. Possibly that attribute should be encrypted when output into the form for greater security.

Enjoy!

tmk-php at infeline dot org

17 years ago

To handle forms with or without [] you can do something like this:



The function will check every field in the $_POST with the raw post data and rebuild the arrays that got lost.

Anonymous

19 years ago

"...the dot [period, full stop] is not a valid character in a PHP variable name."

That's not completely correct, consider this example:
$GLOBALS['foo.bar'] = 'baz';
echo ${'foo.bar'};
This will output baz as expected.

lennynyktyk at yahoo dot com

18 years ago

When dealing with multiple select boxes and the name=some_name[] so that PHP will understand that is needs to interpet the input as an array an not as a single value. If you want to access this in Javascript you should assign an id attribute to the select box as well as the name attribute. Then proceed to use the id attribute in Javascript to reference the select box and the name attribute to reference the select box in PHP.
Example


....




  document.forms[0].select_id.options[0].selected = true;

I hope you get the idea

a at b dot c dot de

20 years ago

As far as whether or not "[]" in name attributes goes, The HTML4.01 specification only requires that it be a case-insensitive CDATA token, which can quite happily include "[]". Leading and trailing whitespace may be trimmed and shouldn't be used.

It is the id= attribute which is restricted, to a case-sensitive NAME token [not to be confused with a name= attribute].

anisgazis at gmail dot com

3 years ago

Dots , spaces and [  in variable names are converted to underscores. For example 
becomes $_REQUEST["a_b"].
becomes $_REQUEST["a_b"].
becomes $_REQUEST["a_b"].
becomes $_REQUEST["a]b"].
becomes $_REQUEST["a-b"].
becomes $_REQUEST["a/b"].
becomes $_REQUEST["a\b"].
becomes $_REQUEST["a,b"].

vb at bertola dot eu dot org

19 years ago

For what I understand, since PHP 4.3 it is possible to access the content of a POST request [or other methods as well] as an input stream named php://input, example:

readfile["php://input"];  
[to display it]

or

$fp = fopen["php://input", "r"];   
[to open it and then do whatever you want]

This is very useful to access the content of POST requests which actually have a content [and not just variable-value couples, which appear in $_POST].

This substitutes the old $HTTP_RAW_POST_DATA variable available in some of the previous 4.x versions. It is available for other upload methods different from POST too, but it is not available for POSTs with multipart/form-data content type, since the file upload handler has already taken care of the content in that case.

vierubino dot r3m0oFdisB1T at gmail dot com

15 years ago

When you are using checkboxes to submit multiple choices, there is no need to use the complex method further down the page where you assign a unique name to each checkbox.

Instead, just name each checkbox as the same array, e.g.:



This way your $_POST["items"] variable will return as an array containing all and only the checkboxes that were clicked on.

fabian dot picone at gmail dot com

4 years ago

"That will create two separate cookies although MyCookie will now be a single array in your script. If you want to set just one cookie with multiple values, consider using serialize[] or explode[] on the value first."

explode should be implode in this sentence.

kevinrlat nospam dot ccs dot neu dot edu

19 years ago

if you use an array of checkboxes to submit info to a database or what have you, be careful of the case when no boxes are checked.  for example:




. . .

if these are submitted and none are checked, the $_POST['checkstuff'] variable will not contain an empty array, but a NULL value.  this bothered me when trying to implode[] the values of my checkboxes to insert into a database, i got a warning saying the 2nd argument was the wrong type.

hope this helps!
-kevin

jlratwil at yahoo dot com

17 years ago

To get multiple selected [with "multiple" ] lists in tag, make sure that the "name" attribute is added to braces, like this:


     Foo
     Bar

When submitted to PHP file [assume that you have a complete form] it will return an array of strings. Otherwise, it will just return the last element of the tag you selected.

walf

11 years ago

WARNING! replacement of spaces and dots does not occur in array keys.

E.g. If you have

var_dump[$_POST];
gives
array[1] {
  ["a__b"]=>
  array[1] {
    ["x. y"]=>
    string[3] "foo"
  }
}

un shift at yahoo dot com

19 years ago

This function takes a recurring form item from php://input and loads it into an array - useful for javascript/dom incompatibility with form_input_item[] names for checkboxes, multiple selects, etc.  The fread maxes out at 100k on this one.  I guess a more portable option would be pulling in ini_get['post_max_size'] and converting it to an integer.

t.montg AT gmail DOT com

15 years ago

For anyone else having trouble figuring out how to access values in a SELECT element from a POST or GET form, you can't set the "id" attribute to the same thing as your "name" attribute.  i.e. don't do this:



If you do the above, the variable $_POST['selectElem'] will not be set.  Instead, either change the id or name attribute so that they are dissimilar.  i.e. do this:



Then you can access the value[s] of the SELECT element through the array $_POST['selectElem'][] or $_GET['selectElem'][].  It took me quite some time to figure out the problem.

POSTer

12 years ago

Here's a simple function to give you an uncorrupted version of $_POST:

Chủ Đề