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

Source: Internet
Author: User
Tags flock unpack

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

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 filling [padded string]

H-hexadecimal string, with a low "four-digit" [low nibble first] (before low position)

H-hexadecimal string, high "four-digit" [high nibble first] (high Front)

C-Signed characters

C-non-symbolic 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, sorted by large endian bytes)

V-short mode without symbols [short] (usually 16 bits, sorted by small endian bytes)

I-signed integer (determined by the size and byte order)

I-unsigned integer (determined by the size and byte order)

L-signed long mode [long] (usually 32-bit, In the byte order of the machine)

L-long mode without symbols [long] (usually 32-bit, In the byte order of the machine)

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 sequence)

D-Double Precision (determined by the size and byte order)

X-Null byte [NUL byte]

X-the next byte [Back up one byte] (returns one byte)

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 1234567890 file_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.

<?php print_r(unpack("i", file_get_contents("test.txt"))); 

Case 2: Data Encryption

Store a piece of meaningful data as a string, 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.

<?php file_put_contents("test.txt", "7-110-abcdefg-117"); 

Disadvantages of the above method:

I. Data storage size

2. data is stored in plain text. any sensitive information may cause insecure access.

Iii. File storage size, increasing in irregular mode.

Encryption:

<?php file_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:

I. Data Size Optimization

2. If you do not know the compression format like "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: key-value type file storage

Two files are generated: index files and data files.

The format of data storage in the file is as follows:

Code implementation:

<? Php error_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 = "fil Ecache_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: socket communication encryption

Both parties define the encryption format:

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

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.