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.tw/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
廣告