How to Encrypt a String in PHP?

In this post, we build-in function to encrypt large files. openssl_encrypt() can be used to encrypt strings in php.

1. Code:

    <?php 
	
    function encryptString($string, $key = null){
		$_method = "AES-256-CBC";
		$_digest = "sha512";
		$_keyLength = "256";
		$_iteration = "1000";
		$_key = "Soltuts.com";
		if (empty($key))
			$key = $_key;
		$key = mb_convert_encoding($key, "UTF-8");
		$salt = random_bytes(16);
		$iv = random_bytes(16);
		$hash = openssl_pbkdf2($key, $salt, $_keyLength, $_iteration, $_digest);
		$encrypted = openssl_encrypt($string, $_method, $hash, OPENSSL_RAW_DATA, $iv);
		$result = base64_encode($salt . $iv . $encrypted);
		return $result;
	}
    $number = "Soltuts.com is providing PHP tutorials, tips, tricks and code snippets";
    echo encryptString($number);
    ?> 

2. Example:

Input:

String input: "Soltuts.com is providing PHP tutorials, tips, tricks and code snippets"

Output:

output: "amQi1iV7IjGKQ55/6aIzBhFY82eL6ReVxs47W+bhLAjG7rPa7U1dYe437UhJitO7TvG+CZL0oNH/N0qMHnw86T2ZAVMVEmu506xg6MzyKpLgKUHNozBbmJ0By2XDuKkHaZb0rZ06rfEmjurDzwgDtQ=="