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

Source: Internet
Author: User
Tags flock fread unpack
network communication, file storage often need to exchange data, in order to reduce network traffic, file storage size and encryption of communication rules, often need to two-way encryption and decryption to ensure data security.
The main functions to implement this function in PHP are the pack and unpack functions.

Pack
Compress the data into the string in place.
Syntax: string Pack (string format, mixed [args] ...);
return value: String
This function is used to compress the data into a string that is packed into place.
a-nul-string fills [padded string] fills the string blank with a NULL character
a-space-string fills [padded string]
H – Hex string, low "four-bit" [Lower nibble first] (low in front)
H-16 binary string, high "four-bit" [Hi Nibble First] (high in front)
C – Characters with symbols
C – characters with no symbols
S-Short (usually 16-bit, machine-byte order) with a symbol
S-Short mode with no symbols (usually 16 bits, sorted by machine byte)
N-Short pattern without symbols [shorter] (usually 16 bits, sorted by large endian bytes)
V-Short pattern without symbols [shorter] (usually 16 bits, sorted by small endian bytes)
I – a signed integer (determined by size and byte order)
I – Integers without symbols (determined by size and byte order)
L – Long mode with symbol [long] (usually 32 bits, in machine byte order)
L – Long mode without symbols [long] (usually 32 bits, in machine byte order)
n – Long mode without symbols [long] (usually 32 bits, in large Edian byte order)
V– long mode without symbols [long] (usually 32 bits, in small Edian byte order)
F – floating point (determined by size and byte order)
D – Double precision (determined by size and byte order)
x – Null byte [NUL byte]
x back a byte [back up one byte] (rewind a bit)

Unpack
Unzip the bit string data.
Syntax: string Pack (string format, mixed [args] ...);
return value: Array
This function is used to decompress the data of a bit string. This function is identical to Perl's function function with the same name.

case one, pack implementation reduced file data storage size

<?php//Storage integer 1234567890 file_put_contents ("Test.txt", 1234567890);

At this point the file size of Test.txt is 10byte. Note that at this point the file size is 10 bytes, and the actual footprint size is 1KB.
The integers stored above are actually stored as strings in the file Test.txt.
However, if the JY is stored as a binary string of integers, it will be reduced to 4byte.

<?php Print_r (Unpack ("I", file_get_contents ("test.txt"));


Case two, data encryption
Stores a meaningful piece of data as a string, 7-110-abcdefg-117.
After the character "-" is split, the first bit represents the string length, the second bit represents the storage location, the third bit represents the actual stored string, and the fourth bit represents the end position.

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

Disadvantages of the above method:
One, the data storage size
Second, the data is stored in plaintext, and if it is any sensitive information, it may cause unsafe access.
Third, the file storage size, in an irregular manner increment.
Encryption:

<?php file_put_contents ("Test.txt", Pack ("I2a7i1", 7, +, "ABCDEFG", 117));

The

Stores a piece of data in the form of an integer 2-bit length string 10-bit length integer 1-bit length.
Advantages:
One, the data size optimization
Second, do not know "i2a7i1" such a compression format, even if you get the file, you can not read the binary file into clear text correctly.
Three, when the data increases, the file storage size is an equal increment. Each time it is incremented by 19byte.

Case Three, Key-value type file Store
Storage generates two files: index file, data file
file format for data storage such as:


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 struct private $_inx_node_siz      E = 36;//index node size public function __construct ($file _index= "Filecache_index.dat", $file _data= "Filecache_data.dat") { $this->_node_struct = Array (' Next ' =>array (1, ' V '), ' prev ' =>array (1, ' V '), ' Data_offset ' =& Gt;array (1, ' V '),//data store start position ' data_size ' =>array (1, ' V '),//Data length ' Ref_count ' =>array (1, ' V '),//reference here, mimic PHP reference meter       Number destruction mode ' key ' =>array (+, ' h* '),//store 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 index file PRI vate 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 ("Could ' t Open index File:". $this->_file_index_name); $this->_index_puts (0, ' < '? PHP exit ()? '. '    > ')///Locate file stream to start position 0, place php tag to prevent download $this->_index_puts ($this->_file_header_size, Pack ("V1", 0)); }//Create storage file Private Function _create_data () {$this->_file_data = fopen ($this->_file_data_name, "wb+");// Binary storage requires the use of the B if (! $this->_file_index) throw new Filecacheexception ("Could ' t Open index File:". $this->_fil       E_data_name); $this->_data_puts (0, ' < '? PHP exit ()? '. ' > ');//Locate file stream to start position 0, place php tag to prevent download} 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 is exclusive, 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 ($this->_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_si    Ze * ($index _count-1);      The 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-&G           T;_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)); }}//use method $cache = new Filecache (); $cache->add (' ABCDEFG ', ' testabc '); $data = $cache->get_node (' ABCDEFG '); Print_r ($data); echo $cache->get_data ($data [' Data_offset '], $data [' data_size ']);

Case four, Socket communication encryption
Both sides of the communication are well-defined encryption formats:
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 ()));

Server side and client based on the parse command format, find the corresponding data decoding method, get the correct

The above is a detailed explanation of PHP data compression, encryption and decryption (pack, unpack) content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.