search for in the  
<base64_decodeget_headers>
Last updated: Thu, 19 May 2005

base64_encode

(PHP 3, PHP 4, PHP 5)

base64_encode -- Encodes data with MIME base64

Description

string base64_encode ( string data )

base64_encode() returns data encoded with base64. This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean, such as mail bodies.

Base64-encoded data takes about 33% more space than the original data.

Example 1. base64_encode() example

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

This example will produce:

VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==

See also base64_decode(), chunk_split(), convert_uuencode() and RFC 2045 section 6.8.



User Contributed Notes
base64_encode
RRWH.com
24-Apr-2005 12: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
01-Dec-2004 02: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 agradeço Sr. Hugo, pela informação do erro!!

Thanks Mr. Hugo,
Obrigado Sr. Hugo,

David Monroe
diexmax@rediffmail.com
David Monroe diexmax at rediffmail dot com
11-Nov-2004 07:47
Use this code to send attachments in email body.
Ps. Jackie, I love you, did you love me too

Start here:

   $arquivo = "spider.jpg";
   $tipo = "image/jpg";

   //$arquivo is  file and $tipo is type

       $abreArquivo = fopen ($arquivo, "r");

   //$abreArquivo is openFile

   $dados = fread ($abreArquivo, filesize($arquivo));
   fclose ($abreArquivo);
   $encode_anexo = chunk_split (base64_encode($dados));

       $cabeca = "--Message-Boundary\n";
   $cabeca .= "Content-type: text/plain; charset=US-ASCII\n";
   $cabeca .= "Content-transfer-encoding: 7BIT\n";
   $cabeca .= "Content-description: Mail message body\n\n";
 
       $corpo = $cabeca  . $corpo;

       //$corpo is BODY

$corpo .= "Your text here HERE\n";
   $corpo .= "\n\n--Message-Boundary\n";
   $corpo .= "Content-type: $attach_type; name=\"$arquivo\"\n";
   $corpo .= "Content-Transfer-Encoding: BASE64\n";
   $corpo .= "Content-disposition: attachment; filename=\"$arquivo\"\n\n";
   $corpo .= "$encode_anexo\n";
   $corpo .= "--Message-Boundary--\n";

       mail("diexmax@rediffmail.com< please remove my e-mail it´s only one example>", "Your subject", $corpo, $headers);

 the end
 very easy

To Brazilians friends begin here

Usem o codigo acima para enviarem anexos no corpo do e-mail.
mightymrj at hotmail dot com
28-Oct-2004 12: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
21-Jun-2004 10: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 01: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
29-Aug-2003 05: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
28-May-2003 11: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 06: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
13-May-2003 04: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 07: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
01-Oct-2002 07: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

<base64_decodeget_headers>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 17:35:34 2005 CDT