PHP - base64_encode() 函数



PHP URL base64_encode() 函数用于使用 MIME base64 编码数据。它基本上使用 base64 算法来编码给定的数据。这种编码旨在使二进制数据能够在非 8 位干净的传输层(例如邮件正文)上进行传输。Base64 编码的数据比原始数据大约多占用 33% 的空间。

语法

以下是 PHP URL base64_encode() 函数的语法:

string base64_encode( string $data )

参数

此函数接受 $data 参数,它是需要编码的数据。

返回值

base64_encode() 函数返回编码后的字符串数据,或者在失败时返回 FALSE。

PHP 版本

base64_encode() 函数首次引入于 PHP 4的核心版本中,并在 PHP 5、PHP 7 和 PHP 8 中继续轻松运行。

示例 1

在这里,我们将向您展示 PHP URL base64_encode() 函数编码给定简单字符串的基本示例。

<?php
   // Define the string to be encoded
   $str = "This is an simple string";
   echo "Encoded string is as follows: ";
   echo base64_encode($str);
?>

输出

以上代码将产生类似于以下的结果:

Encoded string is as follows: 
VGhpcyBpcyBhbiBzaW1wbGUgc3RyaW5n

示例 2

在下面的 PHP 代码中,我们将尝试使用 base64_encode() 函数来编码 URL 以使其安全。

<?php
   // Define a URL here
   $url = "https://tutorialspoint.com/search?q=php&lang=en";
   
   // Use base64_encode() function
   $encodedUrl = base64_encode($url);

   echo "Here is the encoded URL: ";
   echo $encodedUrl; 
?> 

输出

这将生成以下输出:

Here is the encoded URL: 
aHR0cHM6Ly93d3cudHV0b3JpYWxzcG9pbnQuY29tL3NlYXJjaD9xPXBocCZsYW5nPWVu

示例 3

现在,我们将使用数组作为数据,该数据将使用 base64_encode() 函数进行编码。因此,我们将首先序列化给定的数组,然后对其进行编码。

<?php
   // Define an array here
   $array = array("name" => "Amit", "age" => 30);

   $serializedArray = serialize($array);
   $encodedArray = base64_encode($serializedArray);
   
   echo "Encoded array is here: ";
   echo $encodedArray; 
?> 

输出

这将创建以下输出:

Encoded array is here: 
YToyOntzOjQ6Im5hbWUiO3M6NDoiQW1pdCI7czozOiJhZ2UiO2k6MzA7fQ==

示例 4

在下面的示例中,我们使用 base64_encode() 函数来编码给定的 JSON 数据。

<?php
   // Define a JSON data here
   $data = array("name" => "Amit", "city" => "Mumbai");

   $jsonData = json_encode($data);
   $encodedJson = base64_encode($jsonData);

   // Print the message
   echo "The encoded JSON data is here: ";
   echo $encodedJson; 
?> 

输出

以下是上述代码的输出:

The encoded JSON data is here:
eyJuYW1lIjoiQW1pdCIsImNpdHkiOiJNdW1iYWkifQ==
php_function_reference.htm
广告
© . All rights reserved.