- http_request_body_encode
- Parameters
- Return Values
- User Contributed Notes
- HTTP Input and Output
- User Contributed Notes
- How to do URL encoding and decoding in PHP
- Example
- 1. Using urlencode() and urldecode() functions
- Example: URL encoding
- Example: URL decoding
- 2. Using rawurlencode() and rawurldecode() functions
- Example: URL encoding
- Example: URL decoding
- Related Articles
- Compressed HTTP Requests with Curl and PHP
- Recent Articles on PHP.Watch
- How to extend lifetime of legacy PHP applications
- PHP 8.2 Highlights: What’s New and Changed
- How to install/upgrade PHP 8.2 on Debian and Ubuntu systems
http_request_body_encode
Generate x-www-form-urlencoded resp. form-data encoded request body.
Parameters
Return Values
Returns encoded string on success or FALSE on failure.
User Contributed Notes
- HTTP Functions
- http_cache_etag
- http_cache_last_modified
- http_chunked_decode
- http_deflate
- http_inflate
- http_build_cookie
- http_date
- http_get_request_body_stream
- http_get_request_body
- http_get_request_headers
- http_match_etag
- http_match_modified
- http_match_request_header
- http_support
- http_negotiate_charset
- http_negotiate_content_type
- http_negotiate_language
- ob_deflatehandler
- ob_etaghandler
- ob_inflatehandler
- http_parse_cookie
- http_parse_headers
- http_parse_message
- http_parse_params
- http_persistent_handles_clean
- http_persistent_handles_count
- http_persistent_handles_ident
- http_get
- http_head
- http_post_data
- http_post_fields
- http_put_data
- http_put_file
- http_put_stream
- http_request_body_encode
- http_request_method_exists
- http_request_method_name
- http_request_method_register
- http_request_method_unregister
- http_request
- http_redirect
- http_send_content_disposition
- http_send_content_type
- http_send_data
- http_send_file
- http_send_last_modified
- http_send_status
- http_send_stream
- http_throttle
- http_build_str
- http_build_url
HTTP Input and Output
HTTP input/output character encoding conversion may convert binary data also. Users are supposed to control character encoding conversion if binary data is used for HTTP input/output.
Note:
If enctype for HTML form is set to multipart/form-data and mbstring.encoding_translation is set to On in php.ini the POST’ed variables and the names of uploaded files will be converted to the internal character encoding as well. However, the conversion isn’t applied to the query keys.
- HTTP Input There is no way to control HTTP input character conversion from a PHP script. To disable HTTP input character conversion, it has to be done in php.ini .
;; Disable HTTP Input conversion mbstring.http_input = pass ;; Disable HTTP Input conversion mbstring.encoding_translation = Off
Example #2 php.ini setting example
;; Enable output character encoding conversion for all PHP pages ;; Enable Output Buffering output_buffering = On ;; Set mb_output_handler to enable output conversion output_handler = mb_output_handler
Example #3 Script example
// Enable output character encoding conversion only for this page
// Set HTTP output character encoding to SJIS
mb_http_output ( ‘SJIS’ );// Start buffering and specify «mb_output_handler» as
// callback function
ob_start ( ‘mb_output_handler’ );User Contributed Notes
- Multibyte String
- Introduction
- Installing/Configuring
- Predefined Constants
- Summaries of supported encodings
- Basics of Japanese multi-byte encodings
- HTTP Input and Output
- Supported Character Encodings
- Function Overloading Feature
- PHP Character Encoding Requirements
- Multibyte String Functions
How to do URL encoding and decoding in PHP
In this article, we will cover what URL encoding and decoding are, where they are applicable and why, and how to do it using PHP language.
ASCII (American Standard Code for Information Interchange) was the first character encoding standard used between computers and other electronic devices on the Internet.
It was designed in the 1960s, containing 128 characters. These characters include the numbers from 0 to 9, the upper and lower case alphabets from A to Z, and some special characters.
The character sets (encoding) used in modern computers, in HTML, and on the Internet, are all based on ASCII character set. For example, the default character set for HTML 4.01 is ISO-8859-1 while the default in HTML5 is UTF-8, which are both built on ASCII.
URLs can only be sent over the Internet using the ASCII character-set. Since oftentimes URLs contain non-ASCII characters (eg. semicolon, equal sign, space, etc), the URL has to be converted into a valid ASCII format.
URL encoding is a mechanism for translating/converting non-ASCII (unprintable or special) characters to a universally accepted format by web servers and browsers, and that can be transmitted over the Internet.
URL encoding replaces the non-ASCII characters with a percent character «%» followed by two hexadecimal digits. These hexadecimal digits represent the numerical value of the characters being replaced.
URLs cannot contain spaces. Therefore, URL encoding replaces spaces with a plus «+» sign or with «%20» depending on the encoding method.
For instance, if you type any URL with some spaces in the browser address bar and hit enter, immediately that URL will be automatically converted to replace the space with «%20«.
Example
https://www.example.com/product?=black leather shoe
Will automatically be converted to:
URL encoding is mostly used in HTML form data submission via HTTP GET requests.
URL encoding is also known as percent-encoding.
As a developer, there will always be scenarios where you will be required to do URL encoding. There are two different ways to do encoding and decoding in PHP which includes:
- Using urlencode() and urldecode() functions
- Using rawurlencode() and rawurldecode() functions
1. Using urlencode() and urldecode() functions
Also referred to as «application/x-www-form-urlencoded» type, this method is preferable when sending the data submitted from the form to the URL query string.
It uses the PHP built-in functions urlencode() and urldecode() to encode and decode respectively.
This method replaces space with the plus «+» character.
It replaces the special characters with the «%hexcode» except for hyphen (—), underscore (_), and dot (.).
Example: URL encoding
Example: URL decoding
URL decoding simply means reverting an encoded URL back to its original form. To do this, we used the urldecode() function.
https://www.example.com/product?=HP Elitebook Folio 9470m
2. Using rawurlencode() and rawurldecode() functions
This encoding method replaces the spaces within the URL with «%20» as opposed to the above method which uses the plus «+» character.
This encoding method is most preferable when creating URLs dynamically.
This method uses the RFC 3986 standard. Prior to PHP version 5.3.0, it used the RFC 1738 standard.
It uses the PHP built-in functions rawurlencode() and rawurldecode() to encode and decode respectively.
Example: URL encoding
Example: URL decoding
https://www.example.com/product?=HP Elitebook Folio 9470m
Related Articles
Compressed HTTP Requests with Curl and PHP
Compression is a vital and effective way to increase the performance of web pages and web apps. For text-based resources such as HTML files, CSS/JS files, SVG files, etc., compressing the resource at the server prior to the transmission, and decompressing it at the browser can greatly reduce the bandwidth and transfer times.
For the server and web browser, this compression step is quite opaque, in that the server compresses the resources prior to sending it to the browser, and the browser decompresses them before rendering them. The server-side software and the front-end developers do not need to handle the compression/decompression steps.
There are few compression algorithms developed through the years, and browsers and servers can negotiate the correct compression algorithm using HTTP headers.
When making an HTTP request, the browser indicates the encoding algorithms it supports in an Accept-Encoding HTTP header. If the server supports any of the specified encoding algorithms, it may decide to compress the response, and indicate that with an Content-Encoding HTTP header. IANA maintains a list of registered encoding algorithms.
The Wikipedia page for PHP is around 549 KB in size, and when it compressed with Brotli ( br ), it is only 92 KB. HTML pages, JSON responses, SVG files, CSS/JS files, and other text-based files compress well, and the computational cost it takes to compress/decompress resources is small compared to the network transfer times the compression saves.
Although browsers default to use compression when fetching resources, PHP’s HTTP clients do not. Curl, the popular HTTP Client supports encoding negotiation and opaque compressed requests, but it needs to be enabled.
$ch = curl_init('https://en.wikipedia.org/wiki/PHP'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_exec($ch);
Above is simplified example of making an HTTP request to the PHP page on Wikipedia. Curl does not use HTTP compression by default, and results in larger transfer size and request time:
curl_getinfo($ch, CURLINFO_TOTAL_TIME); // 0.81 sec curl_getinfo($ch, CURLINFO_SIZE_DOWNLOAD_T); // 548 KB
CURLINFO_SIZE_DOWNLOAD_T value reveals that Curl download 548 KB of data from the remote server. Because there is no compression support indicated by Curl (via the Accept-Encoding header), the server did not compress the response.
Using the CURLOPT_ENCODING option, it is possible to explicitly specify the values for the Accept-Encoding header. It is not necessary manually decode the response, because Curl does it automatically. Note that setting the CURLOPT_ENCODING option is different from setting Accept-Encoding header manually. If set manually, Curl does not automatically decode the response.
CURLOPT_ENCODING value accepts a few types of values which are not known to be intuitive.
- CURLOPT_ENCODING = null : Resets the value, disables header and automatic decoding.
- CURLOPT_ENCODING = «» : Curl automatically sends the appropriate header based on the supported algorithms, and automatically decodes the response.
- CURLOPT_ENCODING = «identity» : Client expects the server to not encode the response in any way.
- CURLOPT_ENCODING = «gzip» : Client is capable of gzip algorithm.
- CURLOPT_ENCODING = «br» : Client is capable of Brotli br algorithm.
CURLOPT_ENCODING option in fact accepts any string value, and Curl will attempt to decode it if the responding Content-Encoding header contains a known encoding algorithm.
The most useful and appropriate value for CURLOPT_ENCODING is an empty string ( «» ). It enables encoding, but does not explicitly state the algorithms. This effectively enables all algorithms supported and selected by Curl.
$ch = curl_init('https://en.wikipedia.org/wiki/PHP'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_ENCODING, ''); curl_exec($ch);
With the CURLOPT_ENCODING=»» option, Curl now makes HTTP requests with an appropriate Accept-Encoding header, listing all algorithms it supports.
The headers sent-out can be later retrieved using curl_getinfo function:
$ch = curl_init('https://en.wikipedia.org/wiki/PHP'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_ENCODING, ''); curl_setopt($ch, CURLINFO_HEADER_OUT, true); curl_exec($ch); $headers = curl_getinfo($ch, CURLINFO_HEADER_OUT); var_dump($headers);
string(103) "GET /wiki/PHP HTTP/2 Host: en.wikipedia.org accept: */* + accept-encoding: deflate, gzip, br, zstd
The server can opt to compress the response in one of the compression algorithms it supports. This greatly reduces the transfer time and size:
curl_getinfo($ch, CURLINFO_TOTAL_TIME); // 0.31 sec curl_getinfo($ch, CURLINFO_SIZE_DOWNLOAD_T); // 90 KB
Curl picks the compression algorithms it supports based on the options it was set at the compilation step.
In most distributions, PHP Curl is compiled with gzip , deflat , and br (Brotli). However, it is also possible to add support for zstd by compiling libcurl with zstd support, and recompiling PHP with the new libcurl header files.
Recent Articles on PHP.Watch
How to extend lifetime of legacy PHP applications
As PHP continue to evolve with new breaking changes, and while that is great for most PHP applications, there are legacy applications that can’t justify the human and financial cost of keeping up. Here is a guide on how to extend the lifetime of legacy PHP applications with security updates and maintenance.
PHP 8.2 Highlights: What’s New and Changed
How to install/upgrade PHP 8.2 on Debian and Ubuntu systems
You will receive an email on last Wednesday of every month and on major PHP releases with new articles related to PHP, upcoming changes, new features and what’s changing in the language. No marketing emails, no selling of your contacts, no click-tracking, and one-click instant unsubscribe from any email you receive.
© 2018-2023 PHP.Watch, with ❤ from Ayesh • About PHP.Watch