base64_encode

(PHP 3, PHP 4, PHP 5)

base64_encode -- 使用 MIME base64 对数据进行编码

描述

string base64_encode ( string data )

base64_encode() returns 使用 base64 对 data 进行编码。设计此种编码是为了使二进制数据可以通过非纯 8-bit 的传输层传输,例如电子邮件的主体。

Base64-encoded 数据要比原始数据多占用 33% 左右的空间。

例子 1. base64_encode() 示例

<?php
  $str
= 'This is an encoded string';
  echo
base64_encode($str);
?>

此示例将显示:

VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==

参见 base64_decode()chunk_split()RFC 2045 6.8 章节。


add a note add a note User Contributed Notes
dlyaza aT yahoo DOT com
22-Oct-2006 08:57
Using Function:
Output for HTML Put:
<img src="$self?image=file" border="0" alt="file">
<img src="$self?image=folder" border="0" alt="folder">

function getimage ($image) {
   switch ($image) {
   case 'file':
       return base64_decode('R0lGODlhEQANAJEDAJmZmf///wAAAP///yH5BAHoAwMALAAAA
AARAA0AAAItnIGJxg0B42rsiSvCA/REmXQWhmnih3LUSGaqg35vF
bSXucbSabunjnMohq8CADsA');
   case 'folder':
       return base64_decode('R0lGODlhEQANAJEDAJmZmf///8zMzP///yH5BAHoAwMALAAAAA
ARAA0AAAIqnI+ZwKwbYgTPtIudlbwLOgCBQJYmCYrn+m3smY5v
Gc+0a7dhjh7ZbygAADsA');
   case 'hidden_file':
       return base64_decode('R0lGODlhEQANAJEDAMwAAP///5mZmf///yH5BAHoAwMALAAAA
AARAA0AAAItnIGJxg0B42rsiSvCA/REmXQWhmnih3LUSGaqg35vF
bSXucbSabunjnMohq8CADsA');
   case 'link':
       return base64_decode('R0lGODlhEQANAKIEAJmZmf///wAAAMwAAP///wAAAAAAAAAAA
CH5BAHoAwQALAAAAAARAA0AAAM5SArcrDCCQOuLcIotwgTYUll
NOA0DxXkmhY4shM5zsMUKTY8gNgUvW6cnAaZgxMyIM2zBLCaHlJgAADsA');
   case 'smiley':
       return base64_decode('R0lGODlhEQANAJECAAAAAP//AP///wAAACH5BAHoAwIALAAAA
AARAA0AAAIslI+pAu2wDAiz0jWD3hqmBzZf1VCleJQch0rkdnppB3
dKZuIygrMRE/oJDwUAOwA=');
   case 'arrow':
       return base64_decode('R0lGODlhEQANAIABAAAAAP///yH5BAEKAAEALAAAAAARAA0AA
AIdjA9wy6gNQ4pwUmav0yvn+hhJiI3mCJ6otrIkxxQAOw==');
   }
}
php at ianco dot co dot uk
22-Sep-2006 11:25
I am finding a length restriction with base64_encode (or possibly with echo) in PHP 4.3.9.
This works ok for me:
<?php
echo strlen(str_repeat('-', 3273)); // 3273
echo strlen(base64_encode(str_repeat('-', 3273))); // 4364
echo base64_encode(str_repeat('-', 3273)); // LS0t repeated
?>
But change the length to 3274 and the third echo prints nothing.
<?php
echo strlen(str_repeat('-', 3274)); // 3274
echo strlen(base64_encode(str_repeat('-', 3274))); // 4368
echo base64_encode(str_repeat('-', 3274)); // Nothing at all printed
?>
This has obvious implications if you're wanting to encode a fairly large serialized array and echo it to a form field.
peter at mailinator dot com
24-Jul-2006 05:06
If you want to decode base64 encoded data in Javascript, you can use the tool (Webtoolkit.base64) on this website: http://www.webtoolkit.info/
greenthumb at 4point-webdesign dot de
26-Apr-2006 05:57
I had massive problems storing a serialized Object which contained UTF-8 parts and some ascii parts (from the serialization i think) into mysql.

So i used base64_encode to get a clean string which could be safely decoded and unserialized.

this is bulletproof - if you ever have trouble use this.
the runtime is imho no problem.
dawgeatschikin at hotmail dot com
28-Mar-2006 12:06
Just a minor tweak of massimo's functions.

<?
$data
= str_replace(array('+','/','='),array('-','_','.'),$data);
//replace '=' with '.' instead of with nothing, that way the process is reversible.  '.' is uri-safe according to http://www.w3.org/Addressing/URL/5_URI_BNF.html
?>
massimo dot scamarcia at gmail dot com
23-Mar-2006 11:23
$data = str_replace(array('+','/','='),array('-','_',),$data); // MIME::Base64::URLSafe implementation
      
$data = str_replace(array('+','/'),array('-','_'),$data); // Python raise "TypeError: Incorrect padding" if you remove "=" chars when decoding
massimo dot scamarcia at gmail dot com
23-Mar-2006 07:02
function urlsafe_b64encode($string) {
   $data = base64_encode($string);
   $data = str_replace(array('+','/','='),array('-','_',''),$data);
   return $data;
}

function urlsafe_b64decode($string) {
   $data = str_replace(array('-','_'),array('+','/'),$string);
   $mod4 = strlen($data) % 4;
   if ($mod4) {
       $data .= substr('====', $mod4);
   }
   return base64_decode($data);
}

Php version of perl's MIME::Base64::URLSafe, that provides an url-safe base64 string encoding/decoding (compatible with python base64's urlsafe methods)
Gabriel Malca
18-Mar-2006 05:45
If the function doesn't exist, this is a messy but effective way of doing it:

<?

echo bencode("Gabriel Malca");
// R2FicmllbCBNYWxjYQ==

function bencode($string='') {
  
$binval = convert_binary_str($string);
  
$final = "";
  
$start = 0;
   while (
$start < strlen($binval)) {
       if (
strlen(substr($binval,$start)) < 6)
          
$binval .= str_repeat("0",6-strlen(substr($binval,$start)));
      
$tmp = bindec(substr($binval,$start,6));
       if (
$tmp < 26)
          
$final .= chr($tmp+65);
       elseif (
$tmp > 25 && $tmp < 52)
          
$final .= chr($tmp+71);
       elseif (
$tmp == 62)
          
$final .= "+";
       elseif (
$tmp == 63)
          
$final .= "/";
       elseif (!
$tmp)
          
$final .= "A";
       else
          
$final .= chr($tmp-4);
      
$start += 6;
   }
   if (
strlen($final)%4>0)
      
$final .= str_repeat("=",4-strlen($final)%4);
   return
$final;
}

function
convert_binary_str($string) {
   if (
strlen($string)<=0) return;
  
$tmp = decbin(ord($string[0]));
  
$tmp = str_repeat("0",8-strlen($tmp)).$tmp;
   return
$tmp.convert_binary_str(substr($string,1));
}

?>
conradopinto at yahoo dot com dot br
09-Feb-2006 11:04
There is an error on the example of passing an array through an HTML Form.

In the line:
$array = unserialize(base64_decode($coded_array);

There is a ')' missing. it should be:
$array = unserialize(base64_decode($coded_array));
php at mmx dot e4ward dot com
19-Dec-2005 03:19
I dont understand why so many programmers use base64_encode to obfuscate their scripts. It can be completely reversible in a matter of seconds.

Instead of using base64_encode to obfuscate, go out and buy Zend Encoder. If you are just cheap, there are other free options like http://pobs.mywalhalla.net/ and http://www.phpcipher.com/

However, if you really want to use base64_encode to obfuscate your source code, you can try running it multiple times. It wont be more secure but it will be more irritating.

<?
function base64_hide ($sourceCode) {
   for (
$k=0; $k <10; $k++) {
      
$sourceCode = "eval(base64_decode("    + base64_encode($sourceCode) + "));";
   }
   return
$sourceCode;
}
?>
virtuall at virtuall dot info
07-Dec-2005 05:53
If you encode text that contains symbols like < > and want to send it in GET query, be sure to urlencode the result of base64_encode, as it sometimes adds a  + (and it's a special symbol) at the end:

<?php
  
echo base64_encode('<html>');
?>

returns:

PGh0bWw+

A function like this could also be useful:

<?php
  
function base64_urlencode($str) {
       return
urlencode(base64_encode($str));
   };
?>
andi151278
15-Nov-2005 01:58
Using base64_encode to produce clean filenames from usernames (e.g. for image upload) is a bad idea if Umlaute (,,) are allowed. Then there is a slash (/) added in the filename, that will lead to a nonexisting directory beeing looked for and your script crashing!
Cristiano Calligaro
25-Aug-2005 06:05
I've used base64_encode and base64_decode for file attachment both in MySQL (using a BLOB field) and MSSQL (using a TEXT field). For MSSQL remember to set in PHP.INI file both mssql.textsize and mssql.textlimit to 2147483647.

Here's the code:

######### MSSQL(mssql_)/MySQL(mysql_) file attach
$val=$HTTP_POST_FILES['lob_upload']['tmp_name'];
$valn=$HTTP_POST_FILES['lob_upload']['name'];
$valt=$HTTP_POST_FILES['lob_upload']['type'];

$data=base64_encode(addslashes(fread(fopen($val, "r"), filesize($val))));

mssql_connect("srv","usr","pass") or die ("");
mssql_select_db("db") or die ("");
$query = "UPDATE $table SET $field='$data', $fieldname='$valn', $fieldtype='$valt' WHERE DocID='$DocID'";
$result = mssql_query($query) or die(mssql_error());
mssql_close();

######### MSSQL(mssql_)/MySQL(mysql_) open file attached
mssql_connect("srv","usr","pass") or die ("");
mssql_select_db("db") or die ("");
$query = "SELECT $field,$fieldtype FROM $table WHERE DocID='$DocID'";
$result = mssql_query($query) or die(mssql_error());
$row = mssql_fetch_array($result);

header("Content-type: $row[1]");
echo stripslashes(base64_decode($row[0]));

This strategy is good for Microsoft Word, Acrobat PDF, JPG image and so on (even zipped files!!!)
RRWH.com
25-Apr-2005 01:40
I had the need to send a Multi-part mime message. I spent a lot of time trying to correctly receive it.  I finally worked out what I needed to do, and rather than keep it to myself - thought I would share it.

I needed to send a text message and an attached file via email rather than providing a direct download link to a file and this is my solution.

The main parts I had problem with was to correctly format the boundary in the header - then also in the body of the message.

<?php
      
$tempfile
= '/full/path/to/file.zip';
$thisfile = 'file.zip';

// Encode the file ready to send it off
$handle = fopen($tempfile,'rb');
$file_content = fread($handle,filesize($tempfile));
fclose($handle);
$encoded = chunk_split(base64_encode($file_content));

// create the email and send it off

$subject = "File you requested from RRWH.com";
$from = "scripts@rrwh.com";
$headers = 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-Type: multipart/mixed;
   boundary="----=_NextPart_001_0011_1234ABCD.4321FDAC"'
. "\n";

$message = '

This is a multi-part message in MIME format.

------=_NextPart_001_0011_1234ABCD.4321FDAC
Content-Type: text/plain;
       charset="us-ascii"
Content-Transfer-Encoding: 7bit

Hello

We have attached for you the PHP script that you requested from http://rrwh.com/scripts.php
as a zip file.

Regards

------=_NextPart_001_0011_1234ABCD.4321FDAC
Content-Type: application/octet-stream;  name="'
;

$message .= "$thisfile";
$message .= '"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="'
;
$message .= "$thisfile";
$message .= '"

'
;
$message .= "$encoded";
$message .= '

------=_NextPart_001_0011_1234ABCD.4321FDAC--

'
;

// now send the email
mail($email, $subject, $message, $headers, "-f$from");

?>
diexmax at rediffmail dot com
02-Dec-2004 04:18
This is $headers of codigo below,  I thank to  Mr. Hugo, for informing to me of the imperfection!

$headers .= "From: example@example\n";
$headers .= "MIME-version: 1.0\n";
$headers .= "Content-type: multipart/mixed; ";
$headers .= "boundary=\"Message-Boundary\"\n";
$headers .= "Content-transfer-encoding: 7BIT\n";
$headers .= "X-attachments: $arquivo";

To Brazilians:

Este  o $headers do codigo abaixo, eu agradeo Sr. Hugo, pela informao do erro!!

Thanks Mr. Hugo,
Obrigado Sr. Hugo,

David Monroe
diexmax@rediffmail.com
mightymrj at hotmail dot com
29-Oct-2004 01:35
Problem: mime attachments sending as blank or almost completely blank documents (all data is lost)

Explanation: After a couple days of trying to mime pdf attachments without losing all data, I finally came across this function in some obsolete obscure post:

set_magic_quotes_runtime()

This is set to on by default in the machine, and it causes fread() and/or base64_encode() (both used in most mime examples I've seen) to read or encrypt binary without slashes for special characters.  This causes sent files to process incorrectly, breaking, thus truncating most of the data in the file. 

Fix: pass 0 to this function and it will do a one time turn off while your code executes.

example:
<?php
   set_magic_quotes_runtime
(0);
?>

This can also been turned off in the php.ini file, but I'm not sure what uses that setting or what the consequences might be.

info:
   http://us2.php.net/manual/en/function.set-magic-quotes-runtime.php
juha at kuhazor dot idlegames dot com
22-Jun-2004 11:29
If you use base64encoded strings as cookie names, make sure you remove '=' characters. At least Internet Explorer refuses cookie names containing '=' characters or urlencoded cookie names containing %xx character replacements. Use the function below to turn base64 encoded strings to bare alphabets (get rid of / and + characters as well)

<?php
function base64clean($base64string)
{
    
$base64string = str_replace(array('=','+','/'),'',$base64string);

     return
$base64string;
}
?>
Siu from Hong Kong
20-Nov-2003 03:17
As someone suggested above:

using base64_encode() to encode image data and finally output to browser using "data" scheme of IMG src:

<?
// ...
echo '<img src="data:image/png;base64,'.$encoded.' ">';
?>

Netscape browser supports this... However, Windows' Internet Explorer does not.

To embed binary contents in ascii text based html file for IE, you need use MIME multipart.
sb
30-Aug-2003 06:33
Re the message on 10-May-2003 04:02

You'll want to call urlencode on the base_64 encoded data before putting it into a GET.  IIUC, base 64 output includes the plus and the slash, both of which will be mungered by browsers.
teddy at mycyberclassroom dot com
29-May-2003 12:21
if you want to insert the base64 encoded image in your html <img src> you need to write 'data:datatype;base64,encodeddata' . For example here's a way to embed an PNG image data:

<?
//get the base64 encoded image
$handle = fopen($tempfile,'rb');
$file_content = fread($handle,filesize($tempfile));
fclose($handle);
$encoded = chunk_split(base64_encode($file_content));

//then echo to browser as:

echo '<img src="data:image/png;base64,'.$encoded.' ">';
?>
Richard Fairthorne netwiz101 at hotmail dot com
23-May-2003 07:47
I have come up with an interesting use for the base64 features. Code obfuscation! Here's a working example you can use if you want to protect your source code from greedy clients who will rip out your copyright notices or modify the code for their own use without paying you:

http://richard.fairthorne.is-a-geek.com/utils_obfuscate.php

This page uses a combination of Zlib and base64_encode/decode features to obfuscate and compress web pages which can be displayed on any php enabled webserver with Zlib.

It does not use any variables or disk storage, and doesn't affect the "state" of your php program, so you can also use it to compress function libraries, configuration files, or whatever you wish.

Enjoy!
Calvin[at] polbox [at] com
14-May-2003 05:34
If you want attach a binary file into mail, pay attention to use mode with "B" flag into fopen function (This is useful only on systems which differentiate between binary and text files, i.e. Windows) Include the 'b' flag in order to make your scripts more portable.

<?php
$handle
= fopen($source_file,'rb');
$file_content = fread($handle,filesize($source_file));
fclose($handle);
$encoded = chunk_split(base64_encode($file_content));
?>
koos_nt_hulskamp at hotmail dot com
10-May-2003 08:02
I had to send a php array trough a FORM in HTML, and came up with this solution:

<?
$array
[] = array("foo", "bar");
$coded_array = base64_encode(serialize($array));
?>

now u can put the $coded_array into an input field or even a GET link ex:

<a href="some_script.php?coded_array=<?=$coded_array;?>">script link</a>

after receiving it in the script you send it to, do the following:

<?
$coded_array
= $_GET["coded_array"]    // or $_POST off course
$array = unserialize(base64_decode($coded_array);
?>
guy at bhaktiandvedanta dot com
02-Oct-2002 08:00
You can use base64_encode to transfer image file into string text and then display them. I used this to store my images in a database and display them form there. First I open the files using fread, encoded the result, and stored that result in the database. Useful for creating random images.

image.php:

<?

header
(" Content-Type: image/jpeg");
header(" Content-Disposition: inline");
$sql = "SELECT data FROM image where name='".$img."'";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$image = $row[0];
echo
base64_decode($image);

?>

And in the html file you put:

<img src="image.php?img=test3"  border="0" alt="">

Guy Laor