When submitting a form to the server, we usually use PHP's $_POST method to obtain the parameter values passed by the front end. But sometimes, we encounter the problem of garbled parameters, which not only causes the backend to be unable to correctly parse parameter values, but also causes the front end to obtain incorrect data results. So how to deal with this situation?
When transmitting data, the client and server need to agree on an encoding method, generally using UTF-8 encoding. But sometimes we may encounter inconsistencies in the front-end and back-end encoding methods. At this time, we need to uniformly convert the encoding methods.
In PHP, you can use urlencode(), rawurlencode(), http_build_query() and other methods to encode the submitted data to ensure consistent encoding. For example:
urlencode($_POST['name']); rawurlencode($_POST['name']); http_build_query($_POST);
The Content-Type header information in the HTTP protocol describes the MIME type of the request and response. When the encoding method of data transferred between the client and the server is inconsistent, the encoding method needs to be set in the HTTP header information.
In PHP, you can use the header() method to set the Content-Type header information. For example:
header('Content-Type: text/html; charset=utf-8');
In HTML, you can set the form encoding method to ensure that the transmitted data encoding method is consistent. You can use the accept-charset attribute in the form element to specify the encoding method. For example:
<form action="http://example.com" accept-charset="utf-8"> <input type="text" name="name"> </form>
mb_convert_encoding(string $str, string $to_enc [, mixed $from_enc = mb_internal_encoding()]) The function can Convert a string from one character encoding to another. For example:
$str = $_POST['name']; $str = mb_convert_encoding($str, 'UTF-8', 'GBK');
iconv(string $in_charset, string $out_charset, string $str) function can convert a string from one Convert a character encoding to another character encoding. For example:
$str = $_POST['name']; $str = iconv('GBK', 'UTF-8', $str);
Summary:
When the form submission parameters are garbled, you need to pay attention to check whether the encoding method during data transmission is consistent, and whether the HTTP header information, form encoding, etc. are correct. settings, and be sure to use the transcoding function provided in PHP for encoding conversion. These methods can effectively prevent garbled characters and ensure the correct parsing of back-end data and the correct display of front-end data.
The above is the detailed content of Parameters passed in php post in form are garbled. For more information, please follow other related articles on the PHP Chinese website!