百科狗-知识改变命运!
--

base64_encode() - php 网址URL函数

梵高1年前 (2023-11-21)阅读数 23#技术干货
文章标签数据

base64_encode()

(PHP 4, PHP 5, PHP 7)

使用 MIME base64 对数据进行编码

说明

base64_encode(string $data): string

使用 base64 对$data进行编码。

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

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

参数

$data

base64_encode() - php 网址URL函数

要编码的数据。

返回值

编码后的字符串数据,或者在失败时返回FALSE

范例

Example #1base64_encode()示例

以上例程会输出:

VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==

参见

  • base64_decode() 对使用 MIME base64 编码的数据进行解码
  • chunk_split() 将字符串分割成小块
  • convert_uuencode() 使用 uuencode 编码一个字符串
  • » RFC 20456.8 章节
For anyone interested in the 'base64url' variant encoding, you can use this pair of functions: 
In PHP 7, the padding issue with base64_decode() is no more - the following is totally fine:
function base64_encode_url($string) {
  return str_replace(['+','/','='], ['-','_',''], base64_encode($string));
}
function base64_decode_url($string) {
  return base64_decode(str_replace(['-','_'], ['+','/'], $string));
}
Checked here with random_bytes() and random lengths:
https://3v4l.org/aEs4o
gutzmer at usa dot net's ( http://php.net/manual/en/function.base64-encode.php#103849 ) base64url_decode() function doesn't pad longer strings with '='s. Here is a corrected version: 
Base64 encoding of large files.
Base64 encoding converts triples of eight-bit symbols into quadruples of six-bit symbols. Reading the input file in chunks that are a multiple of three bytes in length results in a chunk that can be encoded independently of the rest of the input file. MIME additionally enforces a line length of 76 characters plus the CRLF. 76 characters is enough for 19 quadruples of six-bit symbols thus representing 19 triples of eight-bit symbols. Reading 57 eight-bit symbols provides exactly enough data for a complete MIME-formatted line. Finally, PHP's default buffer size is 8192 bytes - enough for 143 MIME lines' worth of input.
So if you read from the input file in chunks of 8151 (=57*143) bytes you will get (up to) 8151 eight-bit symbols, which encode as exactly 10868 six-bit symbols, which then wrap to exactly 143 MIME-formatted lines. There is no need to retain left-over symbols (either six- or eight-bit) from one chunk to the next. Just read a chunk, encode it, write it out, and go on to the next chunk. Obviously the last chunk will probably be shorter, but encoding it is still independent of the rest.

Conversely, each 76-character MIME-formatted line (not counting the trailing CRLF) contains exactly enough data for 57 bytes of output without needing to retain leftover bits that need prepending to the next line. What that means is that each line can be decoded independently of the others, and the decoded chunks can then be concatenated together or written out sequentially. However, this does make the assumption that the encoded data really is MIME-formatted; without that assurance it is necessary to accept that the base64 data won't be so conveniently arranged.
A function I'm using to return local images as base64 encrypted code, i.e. embedding the image source into the html request.
This will greatly reduce your page load time as the browser will only need to send one server request for the entire page, rather than multiple requests for the HTML and the images. Requests need to be uploaded and 99% of the world are limited on their upload speed to the server.

used as so

.logo {
  background: url("") no-repeat right 5px;
}

or
'img/logo.png','png'); ?>"/>
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)
Unfortunately my "function" for encoding base64 on-the-fly from 2007 [which has been removed from the manual in favor of this post] had 2 errors!
The first led to an endless loop because of a missing "$feof"-check, the second caused the rare mentioned errors when encoding failed for some reason in larger files, especially when
setting fgets($fh, 2) for example. But lower values then 1024 are bad overall because they slow down the whole process, so 4096 will be fine for all purposes, I guess.
The error was caused by the use of "empty()".
Here comes the corrected version which I have tested for all kind of files and length (up to 4,5 Gb!) without any error: 
To make base64_encode encode a URL safe string compatible with .net HttpServerUtility.UrlTokenEncode function use this: 
This function supports "base64url" as described in Section 5 of RFC 4648, "Base 64 Encoding with URL and Filename Safe Alphabet"
  
You may wish to rtrim (or escape) trailing ='s for use in a URI.
Just a minor tweak of massimo's functions. 
@gutzmer at usa dot net
Nice idea! However...
The function base64url_decode doesn't pad strings longer than 4 chars.
str_pad will only pad the string if the second argument is larger than the length of the original string. So the correct function should be: 
I needed a simple way to obfuscate auto_increment primary keys in databases when they are visible to users in URIs or API calls. The users should not be able to increment the id in the URL and see the next data record in the database table.
My solution (uses modified base64 functions by Tom):
function base64url_encode($plainText) {
  
  $base64 = base64_encode($plainText);
  $base64url = strtr($base64, '+/=', '-_,');
  return $base64url;  
}
function base64url_decode($plainText) {
  
  $base64url = strtr($plainText, '-_,', '+/=');
  $base64 = base64_decode($base64url);
  return $base64;  
}
function encryptId($int, $class='') {
  
  return base64url_encode($int.'-'.substr(sha1($class.$int.encryptionKey), 0, 6));
}
function decryptId($string, $class='') {
  
  $parts = explode('-', base64url_decode($string));
  if (count($parts) != 2) {
    
    return 0;
  }
  
  $int = $parts[0];
  return substr(sha1($class.$int.encryptionKey), 0, 6) === $parts[1]
    ? (int)$int
    : 0;
}
- The optional 2nd argument is the class name, so two equal ids of different tables will not result in two equal obfuscated ids.
- encryptionKey is a global secret key for encryption.
- decryptId() checks if the second part of the base64 encoded string is correct.
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:

returns:
PGh0bWw+
A function like this could also be useful: 
An even faster way to line-breaks every 64th character is using the chunk_split function: 
shortest base64url_decode (correct version) 
I am finding a length restriction with base64_encode (or possibly with echo) in PHP 4.3.9.
This works ok for me:

But change the length to 3274 and the third echo prints nothing.

This has obvious implications if you're wanting to encode a fairly large serialized array and echo it to a form field.
If the function doesn't exist, this is a messy but effective way of doing it: 
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!!!)
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) 
Note that at least some Windows systems will not print a line of characters longer than a certain length unless it has line breaks of some kind. So if you base-64 encode a file, print it back for debugging purposes, and see nothing, don't be alarmed.
$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
output images into html:

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)