How to Convert Strings to Binary in PHP: A Comprehensive Guide

Susan Sarandon
Release: 2024-11-06 04:31:02
Original
852 people have browsed it

How to Convert Strings to Binary in PHP: A Comprehensive Guide

Binary Conversion of Strings in PHP: A Comprehensive Guide

In PHP, there are effective methods for converting strings to binary formats and back. This is a crucial aspect when dealing with password storage or other sensitive data. One approach is to leverage the hash-hmac() function.

Using the hash-hmac() Function

The hash-hmac() function combines the capabilities of hashing and binary output. It takes a string as input, hashes it using the specified algorithm (e.g., SHA256), and returns the result in binary format.

<code class="php">$password = 'MySecret';
$hashedPassword = hash_hmac('sha256', $password, 'Key');

// Store the binary hashed password in a database</code>
Copy after login

Alternative Approach: pack() and base_convert()

Another method involves using the pack() and base_convert() functions. pack() converts a string into binary by interpreting it as a series of hexadecimal values. base_convert() converts the binary representation back to a string.

Example

<code class="php">// Convert string to binary
$binary = pack('H*', 'Stack');
echo base_convert($binary, 16, 2); // 0101001101110100011000010110001101101011

// Convert binary to string
$string = pack('H*', base_convert('0101001101110100011000010110001101101011', 2, 16));
echo $string; // Stack</code>
Copy after login

The above is the detailed content of How to Convert Strings to Binary in PHP: A Comprehensive Guide. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!