Thursday 30 May 2013

How to encode and decode form data in PHP

First, let me ask you the question. Why you need to encode and decode form data.

1) When you are submitting form data to other PHP file using GET Request, form values will be displayed in the browser URL.

2) When you are submitting form data to other PHP file using POST Request, form values will be
viewed using Firebug in Firefox, Chrome Developer Tools in Chrome and IE Developer Tools.

3) If you are performing any credit card transactions in e-commerce site and submitting credit card details to the Payment gateway server using Form.

If you are in above of these cases, you can encode the form data and submit to the Destination server and decode it. Let me demonstrate this by providing an example.

How to Encode Form Data:

Following are the PHP array data that we are going to use for our demonstration
$formData = array();
$formData[] = 'Suresh';
$formData[] = 'Kumar';
$formData[] = 'Business';
$formData[] = 'youemail@domain.com';

Next, we are going to convert array to string using implode() method.
$encoded = implode(' ', $formData);
Now, we are going to serialize the string using serialize() method.
$encoded = serialize($encoded);

After that, we are going to compress the string with ZLIB data format using gzcompress() method.
$encoded = @gzcompress($encoded,9);

Finally, we are going to add slashes and apply encoding the string with MIME base64 using base64_encode() method.
$encoded = base64_encode(addslashes($encoded));

Here is the final output for the $encoded variable
eNortjIxtFIKLi1KLc5Q8C7NTSxScCotzsxLLS5WqMwvTc1NzMxxSMkHUnl6yfm5StZcMKpmEXw=


How to Decode the encoded data:

First, Lets take the encoded string and by using base64_decode(), we are going to decode the string with MIME base64.

$encoded = "eNortjIxtFIKLi1KLc5Q8C7NTSxScCotzsxLLS5WqMwvTc1NzMxxSMkHUnl6yfm5StZcMKpmEXw=";
$decoded = base64_decode($encoded);

Then, we will strip the slashes and we are going to uncompress the compressed string using gzuncompress().
$decoded = @gzuncompress(stripslashes($decoded));

After that, we are going to unserialize the serialized string using unserialize().
$decoded = unserialize($decoded);

Finally we are converting string to array using explode().
$decoded = explode(' ',$decoded);

Here is the final output for the $decoded variable (which is same as the original array values before encoding).
array(4) { [0]=> string(6) "Suresh" [1]=> string(5) "Kumar" [2]=> string(8) "Business" [3]=> string(19) "youemail@domain.com" }

Hope, you enjoyed this Post.

No comments:

Post a Comment