Php encode decode string

base64_decode

If the strict parameter is set to true then the base64_decode() function will return false if the input contains character from outside the base64 alphabet. Otherwise invalid characters will be silently discarded.

Return Values

Returns the decoded data or false on failure. The returned data may be binary.

Examples

Example #1 base64_decode() example

The above example will output:

This is an encoded string

See Also

User Contributed Notes 17 notes

If you want to save data that is derived from a Javascript canvas.toDataURL() function, you have to convert blanks into plusses. If you do not do that, the decoded data is corrupted:

$encodedData = str_replace ( ‘ ‘ , ‘+’ , $encodedData );
$decocedData = base64_decode ( $encodedData );
?>

I had some trouble trying to let base64_decode decode base64-strings longer than ~5k chars.

The base64-decoding function is a homomorphism between modulo 4 and modulo 3-length segmented strings. That motivates a divide and conquer approach: Split the encoded string into substrings counting modulo 4 chars, then decode each substring and concatenate all of them.

$decoded = «» ;
for ( $i = 0 ; $i < ceil ( strlen ( $encoded )/ 256 ); $i ++)
$decoded = $decoded . base64_decode ( substr ( $encoded , $i * 256 , 256 ));
?>

where 256 can be replaced by a sufficiently small modulo 4 natural.

This function supports «base64url» as described in Section 5 of RFC 4648, «Base 64 Encoding with URL and Filename Safe Alphabet»

function base64url_decode ( $base64url )
$base64 = strtr ( $base64url , ‘-_’ , ‘+/’ );
$plainText = base64_decode ( $base64 );
return ( $plainText );
>
?>

Base64 for URL parameters/filenames, that adhere to RFC 4648.
Defaults to dropping the padding on encode since it’s not required for decoding, and keeps the URL free of % encodings.

function base64url_encode ( $data , $pad = null ) $data = str_replace (array( ‘+’ , ‘/’ ), array( ‘-‘ , ‘_’ ), base64_encode ( $data ));
if (! $pad ) $data = rtrim ( $data , ‘=’ );
>
return $data ;
>
function base64url_decode ( $data ) return base64_decode ( str_replace (array( ‘-‘ , ‘_’ ), array( ‘+’ , ‘/’ ), $data ));
>

@morgangalpin att gmail dotty com

A better implementation would be the following regular expression:

Which will also detect the usage of = or == at the end of the string (and only end).

If this regex isn’t following proper RFC guidelines, please comment on it.

A function geared specifically toward this:

function is_base64_encoded ()
if ( preg_match ( ‘%^[a-zA-Z0-9/+]*=$%’ , $data )) return TRUE ;
> else return FALSE ;
>
>;

Читайте также:  Выпадающее меню бургер css

is_base64_encoded ( «iash21iawhdj98UH3» ); // true
is_base64_encoded ( «#iu3498r» ); // false
is_base64_encoded ( «asiudfh9w=8uihf» ); // false
is_base64_encoded ( «a398UIhnj43f/1!+sadfh3w84hduihhjw= keyword»>); // true

To follow up on Starson’s post, PHP was changed to no longer treat a space as if it were a plus sign in CVS revision 1.43.2.1, which corresponds to PHP 5.1.0. You can see what happened with a diff to branch point 1.43 at:

The CVS log indicates that this change was made to fix bug #34214 (base64_decode() does not properly ignore whitespace).

It would seem from the comment preceding the code which was removed that the treatment of the space as if it were the plus sign was actually intentional at one time:

When Base64 gets POSTed, all pluses are interpreted as spaces.
This line changes them back. It’s not exactly the Base64 spec,
but it is completely compatible with it (the spec says that spaces
are invalid). This will also save many people considerable
headache.

However, RFC 3548 states that characters not in the Base64 alphabet should either be ignored or cause the implementation to reject the encoding and RFC 2045 says they should be ignored. So the original code was unfortunately not fully compatible with the spec or other implementations. It may have also masked problems with code not properly escaping POST variables.

The change took place between 5.0.5 and 5.1.0. Exactly where I don’t know or care.

In short php = 5.1.0’s base64_decode( $string ) will no longer make that assumption. I did not see this noted in the change log.

Please note that, as of this writing, mb_convert_encoding( $string, «UTF-8», «BASE64» ) still behaves as base64_decode( $string ) did in php

I was wondering how to decode attached images within mails. Basically they are mostly JPEG files, so it was obviously to write a function that decodes JPEG images.
I guess the plainest way to do so was the following:

function base64_to_jpeg ( $inputfile , $outputfile ) <
/* read data (binary) */
$ifp = fopen ( $inputfile , «rb» );
$imageData = fread ( $ifp , filesize ( $inputfile ) );
fclose ( $ifp );
/* encode & write data (binary) */
$ifp = fopen ( $outputfile , «wb» );
fwrite ( $ifp , base64_decode ( $imageData ) );
fclose ( $ifp );
/* return output filename */
return( $outputfile );
>
?>

This function decodes the given inputfile (a filename!) and saves it to the given outputfile (a filename as well) and then returns the output filename for further usage (e.g. redirect, imagejpeg() and so on).
I thought that might be helpful.

Источник

Encoding & Decoding PHP Code

There are many ways to encode and decode PHP code. From the perspective of site security, there are three PHP functions — str_rot13() , base64_encode() , and gzinflate — that are frequently used to obfuscate malicious strings of PHP code. For those involved in the securing of websites, understanding how these functions are used to encode and decode encrypted chunks of PHP data is critical to accurate monitoring and expedient attack recovery.

Читайте также:  Питон разница между кавычками

For those already familiar with the concept, but could use a quick reference with examples, I put together a concise summary of this article. The article here is intended as a “behind-the-scenes” look at the decoding and encoding happening on the examples page. Here’s the quick-jump menu:

Encoding and decoding with str_rot13()

As explained in the PHP documentation, str_rot13() is a simple function used for rotating every letter “13 places in the alphabet” while ignoring non-alphanumeric characters. This type of encoding is called ROT13 encoding and it’s very straightforward using the str_rot13() function. Let’s look at an example..

Let’s say we want to ROT13-encode the following string:

We run this string through str_rot13() and set it as a variable named $encoded like so:

Echoing the $encoded variable to the browser, we get this string of gibberish:

Rapbqvat naq Qrpbqvat Rapelcgrq CUC Pbqr

To decode a string encoded with str_rot13() , we simply run it back through the function to restore the original string. Here is an example that returns the original string to a variable named $decoded :

Echoing $decoded , we see the original string as expected:

Encoding and Decoding Encrypted PHP Code

Copy/paste example (try it for yourself):

Encode and decode with base64_encode() & base64_decode()

Also explained in the PHP documentation, the base64_encode() function “encodes the given data with base64.” Rather than get into the mechanics of encoding with base64, I’ll repeat the enigmatic haiku given in the docs:

This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean, such as mail bodies.

Ahh, I love taking stuff out of context, but I digress.. Let’s get back on track with a quick example showing how base64_encode() works its magic. Let’s say we want to encode the following string with base64:

We run this string through base64_encode() and set it as a variable named $encoded like so:

Echoing the $encoded variable to the browser, we get this string of gibberish:

As you may count, the base64-encoded string contains around 33% more data than the original. Now to decode a string encoded with base64_encode , we use the converse function, base64_decode. Here is an example that returns the original string to a variable named $decoded :

Читайте также:  Вывести корни квадратного уравнения питон

Echoing $decoded , we see the original string as expected:

Encoding and Decoding Encrypted PHP Code

Copy/paste example (try for yourself):

Deflate and inflate with gzdeflate() & gzinflate()

A third visit to the PHP docs gives us our third function, gzdeflate() is used to “compress the given string using the DEFLATE data format.” Again, not gonna veer off — let’s stay focused with a quick example.

Let’s say we want to “gzdeflate” the following string:

We run this string through gzdeflate() and set it as a variable named $compressed :

Echoing the $compressed variable to the browser, we get this bizarre-looking gibberish:

To “decode” this alien-speak, we inflate it with the converse function, gzinflate(), to restore the original string. Here is an example that returns the original string to a variable named $uncompressed :

Echoing $uncompressed , we see the original string as expected:

Encoding and Decoding Encrypted PHP Code

Copy/paste example:

Parameters

Also worth mentioning: whereas the first two functions — str_rot13() and base64_encode() — accept only one parameter (the input $string ), the inflate/deflate functions accept two parameters. Perhaps surprisingly, these second parameters are different between the two functions:

  • gzdeflate() — level = the level of compression ( 0 to 9 )
  • gzinflate() — length = the maximum length of data to decode

Returning to our example, let’s employ these second parameters to help visualize:

And the result as displayed in a browser:

s�K�O��KWH�KQpI�r\���* JRS Encoding and Decoding Encrypted PHP Code

Combined example: gzinflate(str_rot13(base64_decode()))

Malicious scripts often combine multiple encoding methods to further obfuscate data strings. Using the numerous PHP encoding-type functions (and their various parameters), it’s possible to scramble data with many layers of obfuscation. For example, on common technique for encrypting malicious scripts combines all three of the functions described in this article. The structure of such technique looks like this:

The concept is straightforward, however decoding the $gibberish can be tricky. The easiest way to decode such a string is to use an online decoding tool. And that’s my slick segue into the next section..

Online tools for decoding/encoding PHP code

To further contribute to the cause, I’ve created some online decoding tools to simplify the process. Here are some tools for encoding/decoding with some common PHP functions:

Additional resources

Into this decoding/ecoding stuff? You may also enjoy these fine functions..

  • chunk_split() — Split a string into smaller chunks
  • convert_uuencode() — Uuencode a string
  • gzcompress() — Compress a string
  • gzuncompress() — Uncompress a compressed string
  • gzencode() — Create a gzip compressed string

Источник

Оцените статью