Php input and output streams are learning the http protocol recently! To better understand the http protocol, I checked the http module of nodejs! I think there are still a lot of gains. For example, I use an http request to send a request:
var options = { host: 'localhost', port: 80, path: '/backbone/data.php', method: 'POST'};var req = http.request(options, function(res) { console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); res.setEncoding('utf8'); res.on('data', function (chunk) { console.log('BODY: ' + chunk); });});// write data to request bodyreq.end('name=liuzhang&age=28');
The above code indicates sending data 'name = liuzhang & age = 28'. the callback is the response object and prints the server response data!
Data. php code is
print_r($_POST);
Print the passed data!
The result of running on the command line is
We can see that the Array is empty, that is, $ _ POST has no data. At first I thought it was not passed in! But I changed the backend data. php
echo file_get_contents("php://input");
Received data!
Php: // input is a read-only stream that can access the requested raw data. In the case of POST requests, it is best to use php: // input instead of $ HTTP_RAW_POST_DATA, because it does not rely on specific php. ini commands. In this case, $ HTTP_RAW_POST_DATA is not filled by default, which requires less memory than activating always_populate_raw_post_data. When enctype = "multipart/form-data", php: // input is invalid.
$ _ POST can only be obtained when data is submitted by application/x-www-form-urlencoded type. the enctype attribute of form is encoded in two ways: application/x-www-form-urlencoded and multipart/form-data. the default value is application/x-www-form-urlencoded. When the action is get, the browser uses the x-www-form-urlencoded encoding method to convert form data into a string (name1 = value1 & name2 = value2 ...), then append the string to the end of the url, using? Load the new url. When the action is post, the browser encapsulates form data into the http body and sends it to the server.
When we change "send options" to "send options ",
var options = { host: 'localhost', port: 80, path: '/backbone/data.php', method: 'POST', headers : {'Content-Type': 'application/x-www-form-urlencoded'}};
With a headers content-type, you can use $ _ POST to receive data! If this is not the form type, you can use the original input to receive data!