Php reads memcache binary data

Source: Internet
Author: User

As a data middle layer, memcache is often used for data exchange.


For example, in a system, we define the following user status information. Each user only needs to exist in 52 bytes.
Key state # ID, for example, "state #10888"
Value: (binary data)
User ID Uint32
Type User Type Uint8:
State user status Uint8:
Server IP Uint32
Last online time Uint64
Session ID length Uint16

Session ID char [32]

A total of 52 bytes


So how can we get the above data through memcache in php?


The stored data contains binary 0. Will the string be truncated?


Actually, no!


Perform the following tests:


$ Mem = new Memcache ();

$ Mem-> connect ('192. 168.0.69 ', 192 );

$ Memstr = $ mem-> get ('State #105709 ');

Var_dump ($ memstr );
The following output is displayed. We can see that memstr is exactly 53 bytes. SessionId has an Terminator.
String (53) "contains F> * R! 8w.fmsik41kbdkmlqc7m7qowicq8nzz7"


Furthermore, we output the data to a file and use winhex to view the data status.


File_put_contents ('./dd.txt', $ memstr );


Use winhex dd.txt to view hexadecimal data.


Bytes

 


Next I can retrieve data by byte, mainly using the ord function to obtain the byte ASCII code.


$ Type = ord ($ memstr {4 });

$ State = ord ($ memstr {5 });

$ Ip = ord ($ memstr {6 }). '. '. ord ($ memstr {7 }). '. '. ord ($ memstr {8 }). '. '. ord ($ memstr {9 });

$ Ses_long = ord ($ memstr {19}) * 16 + ord ($ memstr {18 });

// The timestamp only needs 4 bytes and is allocated with 8 bytes.
$ Lastactive = ord ($ memstr {13}) * 16777216 + ord ($ memstr {12}) * 65536 + ord ($ memstr {11 }) * 256 + ord ($ memstr {10 });

$ Sessionid = substr ($ memstr, 20, $ ses_long );

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.