PHP Base64 encoding decoding a variable

Posted on : Fri, 17th Apr 15 11:17 am (Updated on : Fri, 17th Apr 15 11:17 am) UTC
Author : Code2care
100+ votes

To convert a PHP variable to Base64 String we can make use of base64_encode() function,

Syntax : String base64_encode(String $var);

File : php_encode_example.php Language : PHP

    $data = "This is the text to be converted to Base64 string @ $ % ^ & * #@ %& &* &^( " ;

    $base64EncodedData = base64_encode($data);
    echo $base64EncodedData;

Output : VGhpcyBpcyB0aGUgdGV4dCB0byBiZSBjb252ZXJ0ZWQgdG8gQmFzZTY0IHN0cmluZyBAICQgJSBeICYgKiAjQCAlJiAmKiAmXigg


Similarly, we can make use of base64_decode() function to decode a Base64 encoded text to plain text,

Syntax : String base64_decode(String $Base64encodedString);

File : php_encode_example.php Language : PHP

    $Base64encodedData = "VGhpcyB0ZXh0IHdhcyBiYXNlNjQgZGVjb2RlZCB1c2luZyBiYXNlNjRfZW5jb2RlKCkgZnVuY3Rpb24=" ;

    $plainText = base64_encode($Base64encodedData);
    echo $plainText;

Output : This text was base64 decoded using base64_encode() function

Code2care's mission is to share varied knowledge in technical and non-technical areas gathered during day-to-day learnings and development activities so that our visitors can leverage this portal to find solutions to their queries without re-inventing the wheel. Technical posts include Learnings, Tutorials, Video Tutorials, Code Snippets, Tips-n-tricks.

Follow us : Facebook - Twitter - Google +