search
HomeBackend DevelopmentPHP TutorialPHP can also do great things - detailed explanation of encoding and decoding in PHP, detailed explanation of php encoding and decoding_PHP tutorial

PHP can also do great things. Detailed explanation of encoding and decoding in PHP. Detailed explanation of php encoding and decoding

is written in front

PHP can also do great things. This is the classic usage of PHP syntax features and related function libraries that I have summarized. It may not really be able to achieve the effect of making a big difference, but mastering these methods can be of some help in your work and study. , I hope everyone can brainstorm and make "PHP Can Do Great Things" more exciting! Please indicate the source when reprinting (jb51.net)

2. Foreword

PHP is a common scripting language, mainly because it is easy to learn and quick to use. Almost 50% of web programs include PHP (incomplete statistics). PHP provides a wealth of functions and API interfaces for development, which allows us to use its powerful built-in functions and extensions very conveniently. This article is the first article in the series "PHP Can Do Big Things", which mainly summarizes the advantages of PHP in encoding, decoding, Knowledge of base conversion.

3. PHP encoding and decoding

1. ASCII encoding and decoding

ASCII (pronunciation: English pronunciation: /ˈæski/ ASS-kee, American Standard Code for Information Interchange, American Standard Code for Information Interchange) is a computer coding system based on the Latin alphabet. It is mainly used to display modern English, while its extended version EASCII can partially support other Western European languages ​​and is equivalent to the international standard ISO/IEC 646. As the World Wide Web made ASCII widely used, it was gradually replaced by Unicode until December 2007. https://zh.wikipedia.org/zh/ASCII

PHP basic functions have built-in ASCII encoding and decoding functions, which allows us to easily perform ASCII encoding and decoding.

int ord ( string $string ) //Returns the ASCII code value of the first character of string string.
string chr ( int $ascii ) //Returns a single character corresponding to ascii specified.
Copy code The code is as follows:
$str = 'Welcome to China';
function getNum($string){
$needle = 0;
$num = '';
While (isset($string[$needle])) {
            $num .= $num==0?'':' ';
           $num .= ord($string[$needle]);
         $needle ;
}
Return $num;
}
function getChar($num){
$num_arr = explode(' ', $num);
$string = '';
foreach ($num_arr as $value) {
           $string .= chr($value);
}
Return $string;
}
echo "Character to ASCII code n";
echo getNum($str);
echo "n";
echo "ASCII character n";
echo getChar(getNum($str));
/* @OUTPUT
Convert characters to ASCII code
87 101 108 99 111 109 101 32 116 111 32 67 104 105 110 97
ASCII character
Welcome to China
*/

?>

2. URL encoding and decoding

URL encoding is a format used by browsers to package form inputs. The browser retrieves all names and values ​​from the form and sends them to the server as part of the URL or separately as name/value parameter encoding. For example, when we visit a web page, there will be many strings with %, which is URL encoding.

URL encoding generally uses UTF-8 encoding format, so it is recommended to use UTF-8 format to transfer data. The URL encoding in the normal sense can be understood as the hexadecimal number of the ASCII code plus % before it, and there is no case distinction.
Copy code The code is as follows:
string urlencode(string $str) //This function facilitates encoding a string and using it in the request part of the URL, and it also facilitates passing variables to the next page. Spaces are encoded as .
string urldecode(string $str) //Decode any %XX in the given encoded string, the plus sign (' ') is decoded into a space character.
string rawurlencode (string $str) //Encode the specified characters according to RFC 3986, and convert spaces into .
string rawurldecode (string $str) //Returns a string. The sequence of percent signs (%) followed by two hexadecimal digits in this string will be replaced with literal characters. Not converted to spaces.

The two sets of functions have the same usage, except for the conversion processing of and spaces: rawurlencode converts spaces into and does not convert into spaces; urlencode is different.

Copy code The code is as follows:
$str_arr = array(
'www.jb51.net',
'http://www.bkjia.com/',
‘PHP can also do great things’,
'!@#$%^&*()_ =-~`[]{}|\;:'",./?'
);
foreach ($str_arr as $key => $value) {
echo $value,"t->t",urlencode($value),"n";
}
/* @OUTPUT
www.jb51.net -> www.jb51.net
http://www.bkjia.com/ -> http://www.jb51.net/
PHP can also do big things -> PHP can also do big things
!@#$%^&*()_ =-~`[]{}|;:'",./? -> !@#$%^&*()_+=-~ `[]{}|;:'",./?
*/
?>

3. Base64 encoding and decoding

Base64 is a representation method for binary data based on 64 printable characters. Since 2 to the 6th power is equal to 64, every 6 bits is a unit, corresponding to a printable character. Three bytes have 24 bits, corresponding to 4 Base64 units, that is, 3 bytes need to be represented by 4 printable characters. It can be used as a transfer encoding for email. The characters used include 26 uppercase and lowercase letters, plus 10 numbers, plus sign " ", slash "/", a total of 64 characters, and the equal sign "=" is used as a suffix. The complete base64 definition can be found in RFC 1421 and RFC 2045. The encoded data is slightly longer than the original data, 4/3 of the original length. In emails, according to RFC 822, a carriage return and line feed must be added for every 76 characters. It can be estimated that the encoded data length is approximately 135.1% of the original length. https://zh.wikipedia.org/zh/Base64

string base64_encode(string $data) //Use base64 to encode data.
string base64_decode (string $data [, bool $strict = false ]) //Decode base64 encoded data.

Case: The img tag in the HTML page can use base64 encoding in the src attribute to output images, which can reduce the number of HTTP requests.
Copy code The code is as follows:
$string = file_get_content('3mc2.png');
echo 'PHP can also do great things - detailed explanation of encoding and decoding in PHP, detailed explanation of php encoding and decoding_PHP tutorial';
/* @OUTPUT
UEhQ5Lmf6IO95Yqe5aSn5LqL
*/
?>

4. HTML entity encoding and decoding

Some characters are reserved in HTML and have special meanings. For example, the less than sign "

string htmlspecialchars ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = “UTF-8″ [, bool $double_encode = true ]]] ) //Convert HTML to the following HTML special characters Entity encoding
1.'&' (ampersand) becomes ‘&'
2.'"' (double quote) becomes ‘"' when ENT_NOQUOTES is not set.
3."'" (single quote) becomes ‘'' (or ') only when ENT_QUOTES is set.
4.' 5.'>' (greater than) becomes ‘>'

string htmlspecialchars_decode (string $string [, int $flags = ENT_COMPAT | ENT_HTML401 ]) //The function of this function is exactly the opposite of htmlspecialchars(). It converts special HTML entities back to normal characters.
There is also the function htmlentities/html_entity_decode with the same function. This pair of functions even encodes Chinese characters into HTML entities, and will produce garbled characters, so it is recommended to use htmlspecialchars for encoding and decoding.

Case: Preventing XSS cross-site scripting attacks requires HTML entity conversion of user-submitted data:

Copy code The code is as follows:
$_POST['message'] = 'Test message character'">

5. Conversion between binary, octal, decimal and hexadecimal

There is nothing to say about the conversion between base systems. In short, they are almost the same. Just remember that the base system is based on the number of digits. For example, the next digit of 9 in base 10 is 10, binary, octal, and hexadecimal. The base system can be deduced in this way.

string bin2hex (string $str) //Returns the ASCII string, which is the hexadecimal representation of the parameter str. Conversion uses byte mode, with the high nibble taking precedence.
string hex2bin (string $data) //Convert hexadecimal string to binary string.
number bindec (string $binary_string) //Returns the decimal equivalent of the binary number represented by the binary_string parameter.
string decbin (int $number) //Returns a string containing the binary representation of the given number parameter. The maximum value that can be converted is 4294967295 in decimal, which results in a string of 32 ones.
number octdec (string $octal_string) //Returns the decimal equivalent of the octal number represented by the octal_string parameter.
string decoct (int $number) //Returns a string containing the octal representation of the given number parameter. The maximum value that can be converted is 4294967295 in decimal, which results in "37777777777".
string base_convert (string $number, int $frombase, int $tobase) //Convert to any base and return a string containing the representation of number in tobase base. The base of number itself is specified by frombase. Both frombase and tobase can only be between 2 and 36 (inclusive). Numbers above decimal are represented by the letters a-z, such as a for 10, b for 11, and z for 35.

6, GBK, UTF-8 character encoding conversion

In the process of writing code, we often encounter garbled characters caused by coding problems. In fact, solving the encoding problem is very simple. Just use one encoding. Generally speaking, using Universal Code-UTF-8 is the best choice.

The encoding mentioned here is the encoding of text encoding and file storage. Of course, we have to mention the difference in system encoding:

System Encoding Character Ending
Windows GBK rn
*nix UTF-8 n

So pay special attention when dealing with special characters.

Common encodings include GBK, UTF-8, etc. There are generally two types of functions used:

string mb_convert_encoding (string $str , string $to_encoding [, mixed $from_encoding = mb_internal_encoding() ]) //Convert the character encoding of string type str from optional from_encoding to to_encoding.
string iconv (string $in_charset, string $out_charset, string $str) //Convert the string str from in_charset to out_charset.

Case: Windows system, set up a WAMP server, save the following script as a UTF-8 encoded php file, you can view the files in the php directory without garbled characters through the browser; if you do not use mb_convert_encoding to transcode, This will directly result in garbled output (Windows as a server).

Copy code The code is as follows:
Function getDir($dir){
          static $string = '';
           if(is_file($dir)){
                 $string.= $dir;
         }else{
               $oDir = @opendir($dir);
​​​​​​while($fileName = readdir($oDir)){
If($fileName!='.' && $fileName!='..'){
If(is_file($dir.'/'.$fileName)){
$string.=$fileName."n";
                           }elseif(is_dir($dir.'/'.$fileName)){
$string.= $dir.'/'.$fileName.'/'."n";
                                          getDir($dir.'/'.$fileName);
                 }
                }
            }
}
          return $string;
}
echo mb_convert_encoding( getDir('php'),'utf8', 'gbk' );

?>

4. Summary

Coding is the basis of data processing, so it is very important in the PHP programming development process. As for PHP's processing method, its application in programming still requires quantitative control, especially how to distinguish some similar functions. Please indicate the source when reprinting (jb51.net)

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/987246.htmlTechArticlePHP can also do big things. Detailed explanation of encoding and decoding in PHP. Detailed explanation of php encoding and decoding is written in front. PHP can also do big things. The classic usage of PHP syntax features and related function libraries that I summarized are not the same...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Dependency Injection in PHP: Avoiding Common PitfallsDependency Injection in PHP: Avoiding Common PitfallsMay 16, 2025 am 12:17 AM

DependencyInjection(DI)inPHPenhancescodeflexibilityandtestabilitybydecouplingdependencycreationfromusage.ToimplementDIeffectively:1)UseDIcontainersjudiciouslytoavoidover-engineering.2)Avoidconstructoroverloadbylimitingdependenciestothreeorfour.3)Adhe

How to Speed Up Your PHP Website: Performance TuningHow to Speed Up Your PHP Website: Performance TuningMay 16, 2025 am 12:12 AM

ToimproveyourPHPwebsite'sperformance,usethesestrategies:1)ImplementopcodecachingwithOPcachetospeedupscriptinterpretation.2)Optimizedatabasequeriesbyselectingonlynecessaryfields.3)UsecachingsystemslikeRedisorMemcachedtoreducedatabaseload.4)Applyasynch

Sending Mass Emails with PHP: Is it Possible?Sending Mass Emails with PHP: Is it Possible?May 16, 2025 am 12:10 AM

Yes,itispossibletosendmassemailswithPHP.1)UselibrarieslikePHPMailerorSwiftMailerforefficientemailsending.2)Implementdelaysbetweenemailstoavoidspamflags.3)Personalizeemailsusingdynamiccontenttoimproveengagement.4)UsequeuesystemslikeRabbitMQorRedisforb

What is the purpose of Dependency Injection in PHP?What is the purpose of Dependency Injection in PHP?May 16, 2025 am 12:10 AM

DependencyInjection(DI)inPHPisadesignpatternthatachievesInversionofControl(IoC)byallowingdependenciestobeinjectedintoclasses,enhancingmodularity,testability,andflexibility.DIdecouplesclassesfromspecificimplementations,makingcodemoremanageableandadapt

How to send an email using PHP?How to send an email using PHP?May 16, 2025 am 12:03 AM

The best ways to send emails using PHP include: 1. Use PHP's mail() function to basic sending; 2. Use PHPMailer library to send more complex HTML mail; 3. Use transactional mail services such as SendGrid to improve reliability and analysis capabilities. With these methods, you can ensure that emails not only reach the inbox, but also attract recipients.

How to calculate the total number of elements in a PHP multidimensional array?How to calculate the total number of elements in a PHP multidimensional array?May 15, 2025 pm 09:00 PM

Calculating the total number of elements in a PHP multidimensional array can be done using recursive or iterative methods. 1. The recursive method counts by traversing the array and recursively processing nested arrays. 2. The iterative method uses the stack to simulate recursion to avoid depth problems. 3. The array_walk_recursive function can also be implemented, but it requires manual counting.

What are the characteristics of do-while loops in PHP?What are the characteristics of do-while loops in PHP?May 15, 2025 pm 08:57 PM

In PHP, the characteristic of a do-while loop is to ensure that the loop body is executed at least once, and then decide whether to continue the loop based on the conditions. 1) It executes the loop body before conditional checking, suitable for scenarios where operations need to be performed at least once, such as user input verification and menu systems. 2) However, the syntax of the do-while loop can cause confusion among newbies and may add unnecessary performance overhead.

How to hash strings in PHP?How to hash strings in PHP?May 15, 2025 pm 08:54 PM

Efficient hashing strings in PHP can use the following methods: 1. Use the md5 function for fast hashing, but is not suitable for password storage. 2. Use the sha256 function to improve security. 3. Use the password_hash function to process passwords to provide the highest security and convenience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools