PHP data compression, encryption and decryption (pack, unpack)

Source: Internet
Author: User
Tags flock
Data is frequently exchanged in network communication and file storage. To reduce network communication traffic, file storage size, and encrypted communication rules, two-way encryption and decryption of data is often required to ensure data security. The main functions required to implement this function in PHP are pack and unpack functions.
Pack

The compressed data is in the string.

Syntax: String pack (string format, mixed [ARGs]...);

Return Value: String. This function is used to compress and package data into strings.
A-NUL-string fills up [padded string] to fill the blank string with null characters a-space-string fills up [padded string] H-hexadecimal string, low "four bits" [Low nibble first] (low front) H-hexadecimal string, high "four bits" [High nibble first] (High Front) c-Signed characters C-Unsigned characters s-Signed short mode [Short] (usually 16 bits, in machine byte order) s-Unsigned short mode [Short] (usually 16 bits, sorted by machine bytes) N-Unsigned short mode [Short] (usually 16 bits, sort by large endian bytes) V-short mode without symbols [Short] (usually 16 bits, sorted by small endian bytes) i-signed integers (determined by the size and byte order) I-unsigned integers (determined by the size and byte order) l-signed long mode [long] (usually 32-bit, in the machine byte order) L-long mode without symbols [long] (usually 32-bit, in the order of machine bytes) N-long mode without symbols [long] (usually 32-bit, in the order of large edian bytes) v-long mode without symbols [long] (usually 32-bit, in the small edian byte order) F-floating point (determined by the size and byte order) d-Double Precision (determined by the size and byte order) x-Null Byte [NUL byte] X-Next byte [back up one byte] (reverse back one bit)

Unpack

Extract the bit string.

Syntax: String pack (string format, mixed [ARGs]...);

Returned value: array this function is used to extract the data of a bit string. The functions of this function and Perl functions with the same name have the same usage.
Case 1: Pack to reduce the file data storage size
<? PHP // store the integer 1234567890file_put_contents ("test.txt", 1234567890 );
The file size of ipvtest.txt is 10 bytes. Note that the file size is 10 bytes and the actual occupied space is 1 kb. The entire number of bytes stored is stored in the test.txt file in serial form. However, if you store the JY string as an integer, it will be reduced to 4 bytes.
<?phpprint_r(unpack("i", file_get_contents("test.txt")));
Case 2: Data Encryption stores a piece of meaningful data in the form of strings, 7-110-abcdefg-117. After the character "-" is separated, the first character indicates the string length, the second character indicates the storage position, the third character indicates the actually stored string, and the fourth character indicates the end position.
<?phpfile_put_contents("test.txt", "7-110-abcdefg-117");
Disadvantages of the preceding method: 1. Data Storage is stored by a large organization (Alibaba Cloud) and data is stored in plain text. any sensitive information may cause insecure access. Iii. File storage size, increasing in irregular mode. Encryption:
<?phpfile_put_contents("test.txt", pack("i2a7i1", 7, 110, "abcdefg", 117));
Store a piece of data. The encryption format is: integer 2-bit length string 10-Bit Length Integer 1-bit length. Advantages: 1. Data Size Optimization 2. When you do not know the compression format such as "i2a7i1", even if you get the file, you cannot correctly read the binary file and convert it to plain text. 3. When data is increased, the file storage size increases proportionally. Each time it is increased by a 19byte. Case 3: the key-value file storage generates two files: The index file. The format of data storage in the data file is as follows: code implementation:
<? Phperror_reporting (e_all); Class filecacheexception extends exception {}// key-value type file storage class filecache {private $ _ file_header_size = 14; private $ _ file_index_name; private $ _ file_data_name; private $ _ file_index; // index file handle private $ _ file_data; // data file handle private $ _ node_struct; // index node Structure private $ _ inx_node_size = 36; // index node size public function _ construct ($ file_index = "filecache_index.dat", $ file_data = "filecach E_data.dat ") {$ this-> _ node_struct = array ('Next' => array (1, 'V'), 'prev' => array (1, 'V'), 'Data _ offset '=> array (1, 'V'), // Data Storage Start position 'data _ size' => array (1, 'V'), // Data Length 'ref _ count' => array (1, 'V'), // reference here, simulate the PHP reference counting destruction mode 'key' => array (16, 'H * '), // store the key); $ this-> _ file_index_name = $ file_index; $ this-> _ file_data_name = $ file_data; If (! File_exists ($ this-> _ file_index_name) {$ this-> _ create_index ();} else {$ this-> _ file_index = fopen ($ this-> _ file_index_name, "RB +");} If (! File_exists ($ this-> _ file_data_name) {$ this-> _ create_data ();} else {$ this-> _ file_data = fopen ($ this-> _ file_data_name, "RB +"); // binary storage needs to use B} // create the index file private function _ create_index () {$ this-> _ file_index = fopen ($ this-> _ file_index_name, "WB +"); // binary storage requires the use of B if (! $ This-> _ file_index) throw new filecacheexception ("cocould't open index file :". $ this-> _ file_index_name); $ this-> _ index_puts (0, '<'. '? PHP exit ()? '. '>'); // Locate the file stream to the starting position 0, place the PHP mark to prevent downloading $ this-> _ index_puts ($ this-> _ file_header_size, pack ("V1 ", 0);} // create the storage file private function _ create_data () {$ this-> _ file_data = fopen ($ this-> _ file_data_name, "WB + "); // binary storage requires the use of B if (! $ This-> _ file_index) throw new filecacheexception ("cocould't open index file :". $ this-> _ file_data_name); $ this-> _ data_puts (0, '<'. '? PHP exit ()? '. '>'); // Locate the file stream to the starting position 0, place the PHP mark to prevent downloading} private function _ index_puts ($ offset, $ data, $ length = false) {fseek ($ this-> _ file_index, $ offset); if ($ length) fputs ($ this-> _ file_index, $ data, $ length ); else fputs ($ this-> _ file_index, $ data);} private function _ data_puts ($ offset, $ data, $ length = false) {fseek ($ this-> _ file_data, $ offset); if ($ length) fputs ($ this-> _ file_data, $ data, $ length ); else fputs ($ this-> _ file _ Data, $ data);}/*** file lock * @ Param $ is_block: exclusive or blocking lock */private function _ Lock ($ file_res, $ is_block = true) {flock ($ file_res, $ is_block? Lock_ex: lock_ex | lock_nb);} private function _ unlock ($ file_res) {flock ($ file_res, lock_un);} public function add ($ key, $ value) {$ key = MD5 ($ key); $ value = serialize ($ value); $ this-> _ Lock ($ this-> _ file_index, true ); $ this-> _ Lock ($ this-> _ file_data, true); fseek ($ this-> _ file_index, $ this-> _ file_header_size); List (, $ index_count) = unpack ('v1 ', fread ($ this-> _ file_index, 4); $ data_size = filesize ($ t His-> _ file_data_name); fseek ($ this-> _ file_data, $ data_size); $ value_size = strlen ($ value ); $ this-> _ data_puts (filesize ($ this-> _ file_data_name), $ value); $ node_data = pack ("v1v1v1v1v1h32", ($ index_count = 0 )? 0: $ index_count * $ this-> _ inx_node_size, 0, filesize ($ this-> _ file_data_name), strlen ($ value), 0, $ key ); $ index_count ++; $ this-> _ index_puts ($ this-> _ file_header_size, $ index_count, 4 ); $ this-> _ index_puts ($ this-> get_new_node_pos ($ index_count), $ node_data); $ this-> _ unlock ($ this-> _ file_data ); $ this-> _ unlock ($ this-> _ file_index);} public function get_new_node_pos ($ index_count) {return $ this-> _ file_header_size + 4 + $ this-> _ inx_node_size * ($ index_count-1);} public function get_node ($ key) {$ key = MD5 ($ key); fseek ($ this-> _ file_index, $ this-> _ file_header_size); $ index_count = fread ($ this-> _ file_index, 4); if ($ index_count> 0) {for ($ I = 0; $ I <$ index_count; $ I ++) {fseek ($ this-> _ file_index, $ this-> _ file_header_size + 4 + $ this-> _ inx_node_size * $ I); $ DATA = fread ($ this-> _ file_index, $ this-> _ inx_node_size ); $ node = unpack ("v1next/v1prev/v1data_offset/v1data_size/v1ref_count/h32key", $ data); if ($ key = $ node ['key']) {return $ node ;}} else {return NULL ;}} public function get_data ($ offset, $ length) {fseek ($ this-> _ file_data, $ offset ); return unserialize (fread ($ this-> _ file_data, $ length) ;}// usage $ cache = new filecache (); $ cache-> Add ('abcdef', 'testabc'); $ DATA = $ cache-> get_node ('abcdefg'); print_r ($ data ); echo $ cache-> get_data ($ data ['data _ offset '], $ data ['data _ size']);
Case 4: both parties define the encryption format for socket communication encryption: for example:
$LOGIN = array(     'COMMAND'=>array('a30', 'LOGIN'),     'DATA'=>array('a30', 'HELLO'));$LOGOUT = array(     'COMMAND'=>array('a30', 'LOGOUT'),     'DATA'=>array('a30', 'GOOD BYE'));$LOGIN_SUCCESS = array(     'COMMAND'=>array('a30', 'LOGIN_SUCCESS'),     'DATA'=>array('V1', 1));$LOGOUT_SUCCESS = array(     'COMMAND'=>array('a30', 'LOGIN_SUCCESS'),     'DATA'=>array('V1', time()));
The server and client locate the corresponding data decoding method based on the parsing command format to obtain the correct data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.