Encrypt and Decrypt String/text/ids for URL Using PHP

Posted by & filed under PHP.

Mostly we pass some ids in url to detail page to view detailly about the particular user/something.  Passing ids in URL is biggest security issue. When someone sees this ids in url, he can easily change it to see others details. To avoid such an activity we need to encrypt particular ids and pass it to the detail page via URL.

For example I am going to pass id = 5  to detail page via URL, before passing. I am going encrypt that id =5 to ‘cjhwYlZ6RFdmU0dBbFdLSlBzZXZtUT09’ using encryptor() function with unique hashing that you are going to set. Using $_GET method get that id in detail page and decrypt that encrpted  id ‘cjhwYlZ6RFdmU0dBbFdLSlBzZXZtUT09’ to 5.

 

Encrypt and Decrypt String/text/ids for URL Using PHP

Encrypt and Decrypt String/text/ids for URL Using PHP

Before passing that encrypted string via URL, please URLENCODE() that encrypted string and pass it. Then before decrypt that encrypted string, please URLDECODE() that encrypted string.

Here is the that function for Encrypt and Decrypt String/text/ids for URL Using PHP.

please set change $secret_key and $secret_iv for your wish to generate secure encryption and decryption keys.

function encryptor($action, $string) {
    $output = false;

    $encrypt_method = "AES-256-CBC";
    //pls set your unique hashing key
    $secret_key = 'muni';
    $secret_iv = 'muni123';

    // hash
    $key = hash('sha256', $secret_key);

    // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
    $iv = substr(hash('sha256', $secret_iv), 0, 16);

    //do the encyption given text/string/number
    if( $action == 'encrypt' ) {
        $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
        $output = base64_encode($output);
    }
    else if( $action == 'decrypt' ){
    	//decrypt the given text/string/number
        $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
    }

    return $output;
}

Call this encryptor function like this for encryption

encryptor(‘encrypt’, 5);

and for decryption

encryptor(‘decrypt’, ‘cjhwYlZ6RFdmU0dBbFdLSlBzZXZtUT09’).

Download Premium Only Scripts & 80+ Demo scripts Instantly at just 1.95 USD per month + 10% discount to all Exclusive Scripts

If you want any of my script need to be customized according to your business requirement,

Please feel free to contact me [at] muni2explore[at]gmail.com

Note: But it will be charged based on your customization requirement

Get Updates, Scripts & Other Useful Resources to your Email

Join 10,000+ Happy Subscribers on feedburner. Click to Subscribe (We don't send spam)
Every Email Subsciber could have access to download 100+ demo scripts & all future scripts.

Get Instant Script Download Access!