sending data via url securely

Depending on your situation, sometimes it is quicker to append form data to urls. To do this securely, we need to encrypt it and decrypt it later. One good solution is to use mcrypt.

We can create a class like so:

class Encryption {

 var $skey  = "your own key"; 

    public  function safe_b64encode($string) {

        $data = base64_encode($string);
        $data = str_replace(array('+','/','='),array('-','_',''),$data);
        return $data;
    }

 public function safe_b64decode($string) {
        $data = str_replace(array('-','_'),array('+','/'),$string);
        $mod4 = strlen($data) % 4;
        if ($mod4) {
            $data .= substr('====', $mod4);
        }
        return base64_decode($data);
    }

    public  function encode($value){

     if(!$value){return false;}
        $text = $value;
        $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->skey, $text, MCRYPT_MODE_ECB, $iv);
        return trim($this->safe_b64encode($crypttext));
    }

    public function decode($value){

        if(!$value){return false;}
        $crypttext = $this->safe_b64decode($value);
        $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        $decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->skey, $crypttext, MCRYPT_MODE_ECB, $iv);
        return trim($decrypttext);
    }
}

To send the data with the url, create an array containing your data, encrypt it with mcrypt and json.

$fields = array(
	'data1'=>'test1',
	'data2'=>'5777777777777777',
	);

$enc = new Encryption;
$url = 'http://yoururl?hash='.$enc->encode(json_encode($fields));
// redirect user
header('Location: '.$url);

on the other end, ie the url where you want to go to, you will need to decipher the information.

$enc = new Encryption;
$result = json_decode($enc->decode($_REQUEST['hash']));

That’s it, simple, sweet and secure.

* make sure you have mcrypt dll installed for php to work.

Author: bpeh

Bernard Peh is a great passioner of web technologies and one of the co-founder of Sitecritic.net Website Design and Reviews. He works with experienced web designers and developers everyday, developing and designing commercial websites. He specialises mainly in SEO and PHP programming.