📜  php base64 - PHP (1)

📅  最后修改于: 2023-12-03 15:03:34.511000             🧑  作者: Mango

PHP Base64

Base64 is a binary-to-text encoding scheme that represents binary data in an ASCII string format by translating it into a radix-64 representation. This encoding is often used in email and other internet protocols to transfer large or binary data as plain text.

PHP offers built-in functions to encode and decode base64 data. In this article, we will explore the various ways to use base64 functions in PHP.

Encoding Data

To encode data in base64, we use the base64_encode() function. This function takes a string as an argument and returns the base64-encoded version of the string.

<?php
$data = "Hello World!";
$encoded_data = base64_encode($data);
echo $encoded_data;
?>

Output:

SGVsbG8gV29ybGQh
Decoding Data

To decode a base64-encoded string, we use the base64_decode() function. This function takes a base64-encoded string as input and returns the original data as a string.

<?php
$encoded_data = "SGVsbG8gV29ybGQh";
$data = base64_decode($encoded_data);
echo $data;
?>

Output:

Hello World!
Encoding and Decoding Data with MIME Content-Types

We can also use PHP's chunk_split() function to encode and decode data in base64 with MIME content-types. MIME content-types are used in email to specify the format of the data being sent. The chunk_split() function is used to break the encoded data into smaller chunks, which is necessary for MIME content-types.

To encode data in base64 with MIME content-types, we use the following code:

<?php
$data = "Hello World!";
$encoded_data = chunk_split(base64_encode($data));
echo $encoded_data;
?>

Output:

SGVsbG8gV29ybGQh

To decode base64-encoded data with MIME content-types, we use the following code:

<?php
$encoded_data = "SGVsbG8gV29ybGQh\n";
$data = base64_decode($encoded_data);
echo $data;
?>

Output:

Hello World!
Conclusion

Base64 is a simple and widely-used encoding scheme used to transfer binary data over text-based protocols. In PHP, we can easily encode and decode data in base64 using built-in functions like base64_encode() and base64_decode(). Additionally, we can also use chunk_split() to work with base64-encoded data with MIME content-types.