Home > Articles

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

What If Your Device Uses POST as the Form Method?

There are two methods for passing form data to web servers: GET and POST. Thus far, we’ve been using GET in our examples, since that’s what most devices use in their forms. However, an occasional device will use POST instead, recognized by a <form> tag similar to this:

<form method="POST" action="setup.cgi">

A GET request encapsulates the form data in the URL, as seen in the examples throughout this article. By contrast, a POST request embeds the form data in the headers of the request. To support POST, you have to make some basic changes to how you create the header block to send to your device. The following list outlines those changes:

  • Use the POST method in the request, instead of using GET.
  • Request only the document in the requesting line (POST); don’t add the data.
  • Include a Content-Type: application/x-www-form-urlencoded header.
  • Include a Content-Length: header with an appropriate value stating the length of the form data being passed.
  • Include the form data, URL-encoded in name=value syntax, after the headers.

Using the earlier example for my router and its Save+and+Restart=Save+and+Restart data, the request would be built in PHP similarly to the code snippet shown in Listing 5.

Listing 5 Building a POST request in PHP.

// URL to request
$url = "/basic_setup_finish.html";

// Form data to pass
$formdata = "Save+and+Restart=Save+and+Restart";
$datalength = strlen($formdata);


// Build the request
$postrequest = <<<HTTP
POST $url HTTP/1.1
Accept: text/plain,text/html
Host: localhost
User-Agent: PHP
Connection: Close
$auth
Content-Type: application/x-www-form-urlencoded
Content-Length: $datalength

$formdata


HTTP;
// Note the two blank lines above; due to PHP heredoc idiosyncrasies,
// this creates one blank line in the data to be sent

Notice that the headers and the data are separated by the mandatory "end of headers" blank line and that another blank line is used to signal the end of the data. Also note that the Content-Length header is mandatory and must accurately reflect the length of the encoded data.

  • + Share This
  • 🔖 Save To Your Account