How can I have a password inside PHP code and guarantee that no one viewing the page in the browser can retrieve it?
Is:
Basic, probably not 100% watertight but enough for general purposes:
hash the password (use salt for added security) using your favorite algorithm, and store the hash (and the salt). Compare salted & hashed input with stored data to check a password.
If you can retrieve the password within PHP, then it is retrievable...
The only thing that you can do is to move you password to a "protected" location.
Most hosting companies will offer a separate location where you can place your DB files etc, and this location will not be accessible via the browser. You should store passwords there.
But they are still on your server, and when someone gets access to your box, then he has your password. (He gets to your PHP that has the way to decode it, and he has access to the protected file -> he can read it)
So there is no such thing as a "safe password"
The only option YOU have is to not STORE PASSWORDS for your users etc... I get mad if I subscribe to a service, and they offer to send me my password via email in case I forget it. They store it in a "retrievable way", and that's no something you should do.
That's where all the hashing and salting comes in. You want to veryfy that someone can access a resource. So you hash + salt the password, and store that in the DB for the USER who want to access the service, and when the user wants to authenticate you apply the same algorithm to create the hash and compare those.
That depends on the type of passwords you want to store.
If you want to store passwords to compare against, e.g. having an $users array, then hashing is the way to go. sha1, md5 or any other flavor (here’s an overview)
Adding a salt accounts for additional security, because the same password will not result in the same hash
Update: password_hash uses a salted, strong one-way hash with multiple rounds.
If you want to store passwords to connect to other resources like a database: you’re safest if you store your passwords outside your document root, i.e. not reachable by browsers. If that's not possible, you can use an .htaccess file to deny all requests from outside
Store the password encrypted. For example, take the output of:
sha1("secretpassword");
...and put it in your code. Even better, put it in your database or in a file outside of the web server's directory tree.
As suggested, store the password sha1, salted and peppered
function hashedPassword($plainPassword) {
$salt = '1238765&';
$pepper = 'anythingelse';
return sha1($salt . sha1($plainPassword . $pepper));
}
and then compare the two values
if ($stored === hashedPassword('my password')) {
...
}
And if you can't store your hashed passwords outside of the server root, remember to instruct apache to forbid the access to that file, in your .htaccess file:
<Files passwords.config.ini>
Order Deny,Allow
Deny from all
</Files>