Home > Article > Backend Development > How to convert php string to hexadecimal
How to convert php string to hexadecimal: first find and open common.php; then add the strToHex function; finally use the strToHex function to convert the string to hexadecimal.
Recommended: "PHP Video Tutorial"
PHP string and hexadecimal conversion
I was working on a project today because I needed to call the interface of someone else’s website. As a result, I needed to perform hexadecimal encryption on the request and return time, so I checked the information on the Internet and made a conversion. Demo makes a record.
If used under TP, you can put the following functions in common.php
1. Encryption function
<?php /** *字符串转十六进制函数 *@pream string $str='abc'; */ function strToHex($str){ $hex=""; for($i=0;$i<strlen($str);$i++) $hex.=dechex(ord($str[$i])); $hex=strtoupper($hex); return $hex; } ?>
2. Decryption function
<?php /** *十六进制转字符串函数 *@pream string $hex='616263'; */ function hexToStr($hex){ $str=""; for($i=0;$i<strlen($hex)-1;$i+=2) $str.=chr(hexdec($hex[$i].$hex[$i+1])); return $str; } ?>
The encryption and decryption conversion function uses the Demo example, which is written in a class for convenience.
<?php class Test{ /** *字符串转十六进制函数 *@pream string $str='abc'; */ public function strToHex($str){ $hex=""; for($i=0;$i<strlen($str);$i++) $hex.=dechex(ord($str[$i])); $hex=strtoupper($hex); return $hex; } /** *十六进制转字符串函数 *@pream string $hex='616263'; */ public function hexToStr($hex){ $str=""; for($i=0;$i<strlen($hex)-1;$i+=2) $str.=chr(hexdec($hex[$i].$hex[$i+1])); return $str; } } <span style="white-space:pre"> </span>//测试Demo效果 $test = new Test(); $str = '要加密的内容sxfenglei'; $data = $test->strToHex($str); echo '加密内容:要加密的内容sxfenglei <br>'.$data.'<hr>'; $output = $test->hexToStr($data); echo '解密内容:E8A681E58AA0E5AF86E79A84E58685E5AEB9737866656E676C6569 <br>'.$output; ?>
Run result:
加密内容:要加密的内容sxfenglei E8A681E58AA0E5AF86E79A84E58685E5AEB9737866656E676C6569 解密内容:E8A681E58AA0E5AF86E79A84E58685E5AEB9737866656E676C6569 要加密的内容sxfenglei
The above is the detailed content of How to convert php string to hexadecimal. For more information, please follow other related articles on the PHP Chinese website!