How to properly store global variables for php server code - php

I am writing php scripts for a server code. These include sign up, log in, and similiar functions. These functions often reference the same database and URLs. I have been reading on stackoverflow and google that the user of a global PHP file and using a simple include is a bad idea. Seen below:
global.php
<?php
$databaseHost = "someurl.com";
$databaseUser = "adminUser";
$databasePassword = "adminUsersPassword";
$databaseName = "dbName";
?>
serverFile.php
<?php
include 'global.php';
//mysql functions that use the variables below
$databaseHost;
$databaseUser;
$databasePassword;
$databaseName;
?>
Can someone explain to me the safest way to do such includes or is it better that I just write all the information directly into every server php file? This seems like it will be hard to keep updated if we change / update our database or change our server host.
If you could also explain why you recommend what you recommend that would be greatly appreciated. I have a very good understanding of other programming languages and hardware (I'm a computer engineer), so in depth explanations are welcome.
Sorry for not having an exact problem, but I am very lost on how to best approach this. Thanks in advance for the stackoverflow knowledge.

This is fine. The only thing you should do is put the file outside of your web root (public_html). That way it can't be accessed directly, but instead can only be accessed from code.

Related

Is secure having MySQL in separate document? Because of include function

I learned (from internet tutorials) to create separate file, like mysql.php, with password and username.
$dbserver = "localhost";
$dbname = "";
$dbpass = "";
$dbname = "";
$db = mysql_connect($dbserver, $dblogin, $dbheslo);
mysql_select_db($dbnazev, $db);
And whenever I would need connect to mysql, I would use in my code include "mysql.php".
But doesn't it mean, that anybody in the internet can include this file to his script and get into my database?
BTW: My hosting is not using localhost, it's using mysql87.example.com... .
For your situation I can say to that it IS safe to use it that way (not my way, i like classes) and this is why:
When you start your web server there is php server started also (mod_php, php-fpm, php-cgi or other). This php server exclude from document, that will be shown to any other person that includes it thru web server.
This means that code
<!-- SOME CODE HERE -->
<?php require('mysql.php'); ?>
<!-- SOME CODE HERE ALSO -->
will be rewrited to
<!-- SOME CODE HERE -->
<!-- SOME CODE HERE ALSO -->
So anyone who includes this file will not see php code.
This means that it is safe to use it like this. But i recommend to secure direct access to such kind of files.
index.php
<?php
define ('MY_CUSTOM_CONSTANT', 42);
require('mysql.php');
// Other code
mysql.php
<?php
defined('MY_CUSTOM_CONSTANT') or die('You cannot access to this file directly');
In this case even if they include or just call this file from web - they will just get text message and code will not be executed in this case
Anyone can browse to your script, and it'll connect to the database, but the script will then immediately end. Assuming you aren't messing around with form or cookie variables in your mysql.php script, the would-be attacker is left with no way to run a query, so your database is safe.

Is it possible to overwrite a variable in another file

Forgive me if this is one of those dumb questions.
I'm writing a theme for wordpress and making use of PHP variables to communicate between files.
<?php
$somevar = 'cat';
$display = 10;
include 'cat_display.php';
?>
It has suddenly ocured to me that while I am including my own files, Wordpress must be including my files. What if those variables that I think I have declared have already been declared up the chain and hold something important.
The last thing I want to do is open my .htaccess for abuse or have something unmeaningful added to the database.
$user_id = 10; // Oops just granted uberuser status to WillyWonka
Do I have anything to worry about?
Yes, it certainly is.
You could rename your variables $yourinitials_somevar to avoid the problem.
[edit]Or put them in an array, as Christopher says in the question comments.
When developing WordPress plugins it's common to encapsulate variables by:
Using a unique prefix: $mywpp_var
Using an associative array: $mywpp['var']

Where to put the database sensitive information [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to secure database passwords in PHP?
Recently I was given a website project which was supposed to be done in PHP but I don't have much experience in PHP. Anyway, it is up and running but there is a big room to improve. The one thing that I am not feeling well is the way I am dealing with database: I put the database connection information in a separate db.php file and include it where needed. But I remember seeing PHP source files returned by the server many a time.
So now my question is: what is a better or the best way / place to put database sensitive data?
By the way, how NOT to let PHP show error messages on web pages when things are gone wrong? A custom error page or settings somewhere in php.ini? Thanks!
Note: I am using PHP in it's old flavor not object-oriented way. But I am open to object-oriented or MVC way if there are better approaches that way to prepare for future projects
I don't know if this is what you are looking for:
You can put your sensitive data in your db.php, but outside the web root directory (public_html or www).
For example, you could have a directory called config which is a sibling of your web root directory, and store your db.php file there.
You can include your db.php file like this:
require_once('../config/db.php');
I hope this helps.
Its fine to put it in a db.php file, just use require_once() just after the opening <?php tag of each document.
If basedir restriction is not in effect, move db.php file outside of your web/ftp root that way its definitely not accessible via http/ftp. Make sure permissions are set properly on this file though.
Since you aren't using OOP or an MVC structure for your code this is the best route to go.
I would personally create a file called db.php and place this above the public_html folder on your server
for example
<?php
error_reporting(0);
$link = FALSE;
$link = mysql_connect('hostname', 'username', 'password');
if ( ! $link)
{
die("Couldn't connect to mysql server!");
} else {
mysql_select_db('databasename');
}
?>
This turns off error reporting at the same time as connecting to your database, from your index.php you would include the file like so:
<?php require('../db.php'); ?>

How can I reference variables from another included file in PHP?

So I'm working on a PHP app and trying to make everything moduler. I have an index.php file that includes other php files. The first file included is settings.php which has my postgres credentials defined so they can be accessed elsewhere. The second file is connect.php that has a function you can pass sql to and it will return $result. The third file has functions that call the sql function and receive $result and parse it. In the third file, I can read the results of the $result however if I try if($result) it breaks and isset/empty have no effect.
Anyone have any ideas on a way to make this work, or is my structure just terrible?
Thanks so much!
Mike
let's say you have the following three files:
inc1.php
<?php
$foo = 'hello';
?>
inc2.php
<?php
echo $foo;
?>
main.php
include('inc1.php');
include('inc2.php');
it should echo "hello". however, passing variables around among files is a bad idea, and can lead to a lot of confusing, hard-to-follow code. If you need to pass variables around, use functions and/or objects so that you can at least see where they are coming from.
beyond that though, it's difficult to tell exactly what your problem is without seeing the code in question.
I would really try to switch to OOP. This makes things a lot of easier. If you just have to deal with classes, their methods and attributes you only have to include the classes and not this choas of functions. So I would recommend, give it a go ...

How to encrypt mysql password in php (or how to defeat automated code scanner red flag)

Management strikes again.
How should I satisfy the code scanner that is going to read my php source and red flag my MySQL connection string?
Linux Server (soon to be Sun)
php 4.2 (soon to be latest version)
MySQL database
Servers in a DMZ outside of the firewall
Read only MySQL account
Not a single byte of non public information in the database
I have to encrypt my MySQL password in the connection string for no reason other than it is going to be red flagged by the automatic code testing solution. Management is enthralled with the concept of Pen Testing without understanding it.
I know full well it isn't any more secure to encrypt the password in the file with all the other measures in place, but my sites will be taken down if I don't comply. I know it hurts performance but this site isn't so popular, and isn't a huge database driven app anyway.
My attempt:
//encrypt and decrypt are functions I stole wholesale off of the php.net manual
...
$SuperSecure[0] = array(encrypt("test"), encrypt("test")); //dev
...
$dbcnx = mysql_connect('localhost', decrypt($SuperSecure[0][0]), decrypt($SuperSecure[0][1]));
Is there a better way? More importantly, am I missing something and this is actually necessary?
Edit: I can't fight national anymore. If I ignore this directive my site comes down and losing my job over this is dumb. I just to do this as easily (and with the least performance impact) as possible.
If you don't want to write the password directly into mysql_connect, why not write something like:
$username = 'test';
$password = 'test';
mysql_connect('localhost', $username, $password);
Without knowing how clever the scanner is you won't really be able to tell what obsfucation is enough to not raise any flags.
You can use rot13 to obfuscate (not encrypt) the password
Couldn't you define the default mysql host, username, and password in a php.ini file? Then the mysql_connect function looks like:
`mysql_connect();`
And unless a hacker has your php.ini file, they won't be able to access the username or password. Even if they changed the function to echo. Sure they could echo the directives, but I think it is obfuscated enough, as the password could not be found in any of the source files, aside from php.ini, which is a server-file.
Given, if someone did a phpinfo(); it also would be displayed in plain site, but it would still work.
This solution is very similar to the ODBC solution provided by another answer. It also has the flaw that if the scanner checks your php.ini file, it is going to end up red flagging that instead.
If you would like to make fun of it at the same time, I'd suggest randomly putting snippets of your mysql code in random files that are all includes before you need to connect. AKA
Index.php
Global $password;
$password = "S";
RandomFile.php
Global $password;
$password .= "T";
RandomFile2.php
Global $password;
$password .= "A";
RandomFile3.php
Global $password;
$password .= "CK";
RandomFile4.php
Global $password;
mysql_connect($host, $username, $password."Overflow");
XOR! The basis of the venerable one-time pad. It's legitimate encryption, makes you look more suave then rot13() and anybody competent should be able to figure it out. At the same time, nobody will be grepping your password.
<?
$pass = 'foobar';
$key = 'monkey';
$secret = $pass XOR $key;
$list = array($key, $secret);
foreach($list as $x) {
print "Keypart: ";
print implode(unpack('H*',$x));
print "\n";
}
?>
Aaand I suddenly hate how PHP does arrays... Now, take the output of that...
<?
#Keypart: 6d6f6e6b6579
#Keypart: 666f6f626172
$secret = '666f6f626172';
$key = '6d6f6e6b6579';
$pass = pack('H*', $key) XOR pack('H*', $secret);
print "$pass\n";
?>
The first part is your encryption generator, and the second part is what you have to put in the program. The only rule is that whatever bytestring you XOR the password against should be the same length as the password. It probably won't do anything unwanted if it isn't, but I don't feel like building a testcase.
It IS unnecessary, since you'll just obfuscate the password. Anyone who has the source could log in to the database since your PHP script has to know decrypt to get the original password.
Example
let's say that your password is a number, for example 42 and that encrypt is a function which multiplies by two and decrypt does the opposite.
Then, you'll store 84 in the code somewhere. However, PHP has to know the decrypt function also and will convert it to 42 first before connecting to the database. So, since everything you need has to stand in the PHP file, it is pointless to obfuscate the necessary information.
Some evil hacker which has your source could always replace the mysql_connect in your code example with an echo and will get the plain text password...
Easy obfuscation
Maybe it suffices to use something like "t"."e"."s"."t" instead of "test" in your code to bypass detection of the password...
You could use an ODBC connection to access the database. The ODBC abstraction layer stores its connection properties in a separate file (in UnixODBC, it's /etc/odbc.ini and ~/.odbc.ini). That way, the system DSN can know how to access the database, and your script will rely on it.
I'd advise caution in using ODBC, though, as it doesn't have access to some of the more complicated functions and queries that a straight MySQL connection does.
I might be missing the point here, but let me ask this.
Why are you not storing your mysql connection information in some form of config file, that is included at run time, and using some form of database abstraction, rather then peppering your code with mysql_connects and other legacy methods of dealing with database connections?
I would find it doubtful that your automated code scanning solution would read plaintext ini files, or xml ini files, and some frameworks, Like Zend, make it very easy to deal with these types of configuration files, so that your password is not scattered throught your code, or web accessible at any point...
It sounds like you have all the other measures in place(server outside of network, secure mysql account with only the needed privs.). Am I misconstruing what you are doing, or is there a reason to avoid the best practices here?
Regards
Been using Windows as server from day 1 and dunno whether my way has been wrong from the start, but storing credentials in registry (and reading from it) works and I've been doing it this way.
Here's my snippet:
$Root = HKEY_CURRENT_USER;
$key = "Software\MyApp1";
if (!($registry = #reg_open_key($Root, $key))) {
throw new Exception("Valid Credential not found.");
}else{
$user = reg_enum_key($registry, 0);
$passw = reg_enum_key($registry, 1);
}
reg_close_key($registry);

Categories