one of the project required me to encrypt DB connection string (username & password).
Usually I use .htaccess to restrict user to access from web. But this pro
if the extension is available on your server you can use mcrypt Store your username and password crypted in a file outside the web root and read/write it with mcrypt
For exemple :
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$key = "This is a very secret key";
$text = "myusername";
echo $text . "\n";
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv);
echo $crypttext . "\n";
End of course mcrypt_decrypt let you get the original string.
It's impossible.
If you encrypt the MySQL password for example with mcrypt, only way to decrypt that MySQL password is to use your secret mcrypt password, which will be, obviously, stored also in some PHP script or elsewhere on the server.
Whoever has an access to the server or can read the script will get an access to MySQL password or any other password used to decrypt MySQL password.
If you project requires you to store password not in clear text, ask the project manager about this logical problem - how can I decrypt the password and how can I store a password to decrypt the password.
consider to store your credentials in any cloud service provider using key vault