PHP - base64_decode() 函式



PHP URL base64_decode() 函式用於解碼使用 base64 演算法編碼的資料。此函式接受兩個引數並返回解碼後的資料作為字串。

語法

以下是 PHP URL base64_decode() 函式的語法:

string base64_decode( string $data [, bool $strict = false ] )

引數

以下是 base64_decode() 函式的引數:

  • $data - 要解碼的 Base64 編碼字串。

  • $strict - 如果設定為 true,並且輸入包含不屬於 base64 字母表的一部分的字元,則函式將返回 false。預設值為 false。

返回值

base64_decode() 函式返回解碼後的資料作為字串,如果輸入無效且 $strict 設定為 true,則返回 false。

PHP 版本

base64_decode() 函式最初在 PHP 4 的核心版本中引入,並且在 PHP 5、PHP 7 和 PHP 8 中繼續輕鬆執行。

示例 1

以下是 PHP URL base64_decode() 函式解碼給定編碼字串的基本示例。

<?php
   // Define encoded string here
   $str = "SGVsbG8gVHV0b3JpYWxzcG9pbnQh";

   // Decode the string using base64_decode() function
   $decodedString = base64_decode($str);

   // Print the decoded message
   echo $decodedString;
?>

輸出

以上程式碼將產生類似以下的結果:

Hello Tutorialspoint!

示例 2

在下面的 PHP 程式碼中,我們將嘗試使用 base64_decode() 函式,並在此處提供嚴格引數。

<?php
   // Define encoded string here
   $str = "SGVsbG8gV29ybGQh";
   $decodedString = base64_decode($str, true);
   if ($decodedString === false) {
       echo "Invalid Base64 string.";
   } else {
       echo $decodedString; 
   }
?> 

輸出

這將生成以下輸出:

Hello World!

示例 3

現在,在下面的程式碼中,我們將使用 base64_decode() 函式解碼 Base64 編碼的 JSON 字串。

<?php
   // Define the encoded json here
   $str = "eyJrZXkiOiAidmFsdWUifQ==";
   $decodedJson = base64_decode($str);
   $jsonArray = json_decode($decodedJson, true);
   print_r($jsonArray); 
?> 

輸出

這將建立以下輸出:

Array ( [key] => value )

示例 4

現在,使用 base64_decode() 函式,我們將解碼影像檔案並將其儲存在給定路徑中,並使用提供的名稱。

<?php
   // Define encoded string of an image
   $imgstr = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4
   //8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
   
   // Use base64_decode() function here
   $decodedImg = base64_decode($imgstr);

   // Save the image file
   file_put_contents("/PhpProjects/decoded_image.png", $decodedImg); 

   echo "The decoded image has been saved in the directory!";
?> 

輸出

以下是以上程式碼的輸出:

The decoded image has been saved in the directory!
php_function_reference.htm
廣告