PHP Encoding with base64

Suppose you have a long file data and you have to save the same in the database. this data is too long and contains some especial character like (\, /, *…etc ) that can corrupt your database or can’t be inserted.
I was working on some configuration file and have to insert it in the database, but didn’t get success in inserting it as it is, because of special characters.

So let’s take “php.ini” configuration file to save this content on database, use php function base64_encode() which encodes data with MIME base64


// its too big file and and have lot of special character
$file = "php.ini";
$file_data	= file_get_contents("$file");
$encode_config_file = base64_encode(implode("\n", $file_data));

now above variable “$encode_config_file” can store this data into the database as a string.
and when we want to fetch and work with this data we need to decode with php function base64_decode()

below code show the fetching of data using base64_decode function:

// $file_data keep encoded string fetched from database
$file_decode = base64_decode($file_data);
echo $file_decode;

/// Output Some part of php.ini like:

// ; allow_call_time_pass_reference
// ;   Default Value: On
// ;   Development Value: Off
// ;   Production Value: Off

Happy Coding…:)

2 Responses to PHP Encoding with base64

  1. Rob says:

    I assume you meant

    file_get_contents($file);

    and not

    file_get_contents(“$file”);

Leave a Reply

Your email address will not be published. Required fields are marked *