12

How can I have a password inside PHP code and guarantee that no one viewing the page in the browser can retrieve it?

Is: <?php $password = 'password' ?> enough? Is there a better, more secure way of doing this?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
nunos
  • 20,479
  • 50
  • 119
  • 154
  • maybe you could tell us, why you want to store your passwords in a php file. this is causing a lot of confusion in the answers – knittl Sep 16 '09 at 13:03
  • I am developing a script for a client. I am using a 'test' account because the client doesn't want nobody but him to know the password. I have to find a way that allows him to easily change the password from the test account to his without me knowing it. Btw, this will have no interaction with a database. – nunos Sep 16 '09 at 18:41
  • so you’re storing account information in a php file? if so, the accepted answer is by far not the best. a hash+salt is the way to go in this scenario. your client could give you his salted hash, and you’d have no way knowing his password (nor anybody else) – knittl Sep 17 '09 at 05:41
  • I will need to use the client password to login to a certain site melodramatically. I can't do that if I hash and salt the password, or can I? Thanks. – nunos Sep 17 '09 at 14:50
  • ok, so you need the password to authenticate to another service (like a database password). that way make sure your password file isn’t browseable (.htaccess or outside document root) – knittl Sep 17 '09 at 15:37

11 Answers11

16

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

knittl
  • 246,190
  • 53
  • 318
  • 364
  • 1
    i don't see how storing the passwords outside the document root really changes anything. As long as it's in ` – nickf Sep 16 '09 at 12:46
  • 13
    "only" if the files will be processed by PHP... A nuked PHP Installation could cause them to be send to the client in clear text – Heiko Hatzfeld Sep 16 '09 at 12:50
  • 3
    @nickf Both Facebook and Tumblr accidentally exposed their PHP code via a webserver misconfiguration. It can happen to you, too. http://techcrunch.com/2007/08/11/facebook-source-code-leaked/ http://staff.tumblr.com/post/3959106211/update-regarding-security-issue – ceejayoz Apr 07 '15 at 00:49
  • @knittl pls mention how to use ```.htaccess``` to deny all request like you have mentioned . – Yusuf May 07 '20 at 19:30
  • 1
    @Yusuf `Deny from all`: https://stackoverflow.com/questions/19118482/deny-access-to-one-specific-folder-in-htaccess – knittl May 07 '20 at 19:38
  • 1
    @knittl - since I am a beginner, for clarification..... I have my php src code files in public_html folder. So I should create a new folder and within it, create ```.htaccess``` file. and in same folder create one extra ```.php``` file and in it store db username, password, etc . Is this correct approach or am I getting it wrong ? – Yusuf May 07 '20 at 19:42
  • 1
    @Yusuf Store username and password outside of your document root. E.g. if http://website.com/yourscript.php points to `/var/www/html/yourscript.php`, store your password file in `/var/www/html` (cannot be reached from a webbrowser, it is outside the document). If that does not work, add a separate directory with an `.htaccess` file with the content describted in my linked answer. – knittl May 07 '20 at 19:48
  • @knittl - do you mean to store password file in ```/var/www/``` because in ```/var/www/html/``` ```yourscript.php``` is also stored ? – Yusuf May 07 '20 at 19:59
  • @knittl - or can I just include my connect.php file which will be stored outside of ```/var/www/html``` directory which contains all other ```php``` files ? – Yusuf May 07 '20 at 20:16
  • @Yusuf It needs to be stored outside of the Document Root of your website. Usually, the file will not have any output, so malicious user cannot read it anyway (unless, of course, there's any other vulnerability in your code). This is just an extra protection in case your PHP files are not interpreted anymore and output directly. If you you are just toying with PHP (and you are a beginner, so I suggest toying instead of building production websites), just put the file anywhere you like and include it. – knittl May 07 '20 at 20:33
  • 1
    @knittl - I finally did it. Thanks! .... what i did was - Suppose my document root is ```/var/www/public_html```. all code files are here.. I created new directory ```/var/www/private``` and put ```config.php``` in it which has the password etc. And in ```/var/www/public_html/connect.php``` I included ```../private/config.php```. And it worked !! Thanks – Yusuf May 09 '20 at 08:23
7

Your PHP code will (baring configuration errors) be processed on the server. Nothing inside the <?php ?>; blocks will ever be visible on the browser. You should ensure that your deployment server will not show syntax errors to the client - i.e. the error reporting is set to something not including E_PARSE, lest a hasty edit of live code (admit it, we all do them :) leak some information.

Edit: The point about storing them in a file outside the document root to avoid exposure if your PHP configuration breaks is certainly valid. When I used PHP, I kept a config.inc file outside of htdocs that was required at runtime, and exported configuration specific variables (i.e. passwords).

Adam Wright
  • 48,938
  • 12
  • 131
  • 152
  • that's not a good solution. and what if you’re working in a team, in which everybody has access to the sourcecode. no, no, no! hashing is the way to go – knittl Sep 16 '09 at 12:08
  • 6
    How does hashing help? If the hash is enough to connect to the "secure" resource, how is storing the hash any more secure than storing the password? – Adam Wright Sep 16 '09 at 12:09
  • usually there are two scenarios. see [my answer](http://stackoverflow.com/questions/1432545/how-to-safely-store-a-password-inside-php-code/1432589#1432589), it talks about both – knittl Sep 16 '09 at 12:16
  • what sort of project is this where some team members don't have admin access to their own system? – nickf Sep 16 '09 at 12:43
  • 1
    ...and if such a team exists - one where you can't trust one of them with a password - you should really reconsider working with them in the first place. – nickf Sep 16 '09 at 12:44
  • but you wouldn’t give your workplace password to everybody in your team, am i right? better safe than sorry – knittl Sep 16 '09 at 13:01
5

Let's say your password is "iamanuisance". Here's how to store the password in your code. Just slip this in your header somewhere.

//calculate the answer to the universe
${p()}=implode(null,array(chr(0150+floor(rand(define(chr(ord('i')+16),'m'),
2*define(chr(0x58),1)-0.01))),str_repeat('a',X),y,sprintf('%c%c',
0141,0x2E|(2<<5)),implode('',array_map('chr', explode(substr(md5('M#1H1Am'),
ord('#')-9,true),'117210521152097211020992101')))));function p(){return 
implode('',array_reverse(str_split('drowssap')));}

Just in case it's not completely obvious, you can then easily access the password later on as $password. Cheers! :P

brianreavis
  • 11,562
  • 3
  • 43
  • 50
3

There are noumerous ways of doing this. However, people will not be able to view the password you stored (as plain text) in a PHP file, since PHP is a server side language which means that, as long as you don't print it out to the browser, it will remain invisible.

So it's 'safe'.

Jake
  • 3,973
  • 24
  • 36
2

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.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Heiko Hatzfeld
  • 3,197
  • 18
  • 15
  • Exactly... but I wonder if adding random safeguards can help reduce liability if passwords get stolen. I worked with a guy who scrambled passwords to a database inside fields in the database. I'm still confused. It made it difficult to work with when you wanted the application to point to a different database with a different password. – Kieveli Sep 16 '09 at 12:43
1

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.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Martijn
  • 5,471
  • 4
  • 37
  • 50
0

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.

Jeff Ober
  • 4,967
  • 20
  • 15
  • 9
    Putting database passwords into the database calls for some ... interesting problems :-) – Joey Sep 16 '09 at 12:06
  • +1 this is the only sane solution! shame on all the others (i.e. php will be parsed, so one one can see your passwords :-S) – knittl Sep 16 '09 at 12:09
  • 21
    SHA is *not* an encryption. It’s a hash algorithm. – Gumbo Sep 16 '09 at 12:09
  • 7
    How does this help? One presumes the password allows access to some secure resource. If the hash is enough to access this resource, how is storing the hash any more secure than storing the raw password - both will allow access? – Adam Wright Sep 16 '09 at 12:15
  • 1
    be sure to use salt: sha1 can be broken using a rainbow table relatively easily. – Martijn Sep 16 '09 at 12:20
  • 2
    Most of the time you want to store passwords in your code, they're for connecting to resources such as databases, and I've never seen a database accept a hashed password for a connection before... – nickf Sep 16 '09 at 12:48
0

PHP code blocks cannot be retrieved by clients unless they output something. Observe:

<?php
   if($password=="abcd")
       echo "OK";
   else
       echo "Wrong.";
?>

User can get either OK or Wrong nothing else.

Cem Kalyoncu
  • 14,120
  • 4
  • 40
  • 62
  • 10
    Unless you accidentally uninstall PHP and Apache starts serving it as plain text, that is. Seen that happen a few times! – ceejayoz Sep 16 '09 at 12:09
  • Also there's the ubiquitous way of getting to file contents by putting things like `../../../../../etc/passwd` somewhere in the URL :-). But granted, that works whenever you don't pay attention to what the user enters and have something sensitive stored in a file. – Joey Sep 16 '09 at 12:18
0

I generally do not trust raw PHP code for passwords for services. Write a simple PHP extension to release the password. This ensures that the working set is password free, and it makes it an extra step for a compromised machine to grant access to the hacker to the service.

MathGladiator
  • 1,201
  • 1
  • 10
  • 24
0

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>
macjohn
  • 1,755
  • 14
  • 18
-1

The best way is to store password above your root directory. If you decide to have password in php file then no body would able to view because php files are excuted in the server. But if the server does not support php then those files will be delivered as text files and any one can see the password.

Mohamed
  • 3,420
  • 7
  • 28
  • 31