Is it necessary to unset php password variable? - php

Is it necessary to unset my password variable for my MySQL database.
Currently, my code for my "dbpwd.php" is like this:
# database setup
$dbserver = "localhost";
$db_usrname = "blah";
$db_pwd = "blahblahblah";
$dbname = "blah";
but I was thinking.... is this a securtly concern.. because anyone can just do this:
<?php
include 'http://www.mywebsite.com/dbpwd.php';
echo $db_usrname;
echo $db_pwd;
?>
Wouldn't that give them full access to my stuff... so is it good practice to unset variables that are sensitive at the end of your php code? or is there something that I am missing?
Edit to clarify...
In this situation listed above... they would be using their own php server (not mine), and using include from there php file to get information from my server.

If someone attempts to perform a remote include via allow_url_fopen to your script, remember that from your server's point of view that is a regular HTTP request. A properly configured server would then execute the PHP code, rather than send it down as source. So what they would receive, assuming your database configuration file produces no output, would be a blank document. They would not see or have access to your variables.
The result is the same as if you pointed your web browser to http://www.mywebsite.com/dbpwd.php. You would see a blank page.
As I mentioned though, this relies on your web server being properly configured to execute PHP code (which it should be if your code runs when requested otherwise). It is always recommended though, to place sensitive files outside the server's document root to avoid this issue should your server ever become incorrectly configured.
To answer the other part of your question, you do not need to unset any variables. PHP will clean them up when they are no longer needed, and they are not a danger to your security.

imho closing the database connection is quite enough and you do not need to unset those variables.
Also as Michael Berkowski pointed out - you need to put db connection files outside of document root.

Related

mysql passwords Connecting to MySQL with PHP

In tutrorials for Connecting to MySQL with PHP you see something similar to the below.
$pdo = new PDO('mysql:host=localhost;dbname=mydb', 'myuser','mypassword');
I have a connection working this way on my localhost but for putting it live what do you do about the password? Do you just leave it as plain text like that in your php file? Or is there a more secure way to handle this?
Nobody can see your connection string if they look at the source, it can only be seen by looking at your raw code. I would also have it inside a separate file, and include the file on your page. This also helps if you need to change the password, as you won't have to edit every page that uses a connection - you'll only need to edit the one file.
Alternatively, you can have a connection string in an include file and place it outside of document root. This stops people getting to this file using a browser or if they attack your FTP. This will help security of your plain-text passwords, but is still accessible if somebody gets/has access to your local directories. To do this, you may need to configure a PHP configuration variable, open_basedir, which allows your script to talk to a file outside of root. This all depends on if you have access to a folder behind root of course, and if you can change that configuration variable.
Other than that, there's not much that can be done.
Include File Example:
Create a file called conn.php and store your connection in there.
$dbConn = mysql_connect($host, $user, $pass);
mysql_select_db("dbName", $dbConn);
On the page that needs the connection, include the conn.php file like so:
<?php
include("conn.php");
if (!dbConn) {
die('Sorry, our database did not load. Please try again later.');
exit();
}
$result = mysql_query("...");
?>
An end user will never be able to see the text inside a PHP script. They only see what is output by the code. You can put passwords like that in, as long as you never do something like:
$mySecretPassIs='TheBoogeyManCometh';
echo $mySecretPassIs;
Having said that, it is often easier to put your connection details in a script, include it as you need from the various pages and off you go. The benefit is that if you change passwords or the like, you only have to change it in one place, and you can keep these included files in one safe place.
There really is no way around it. Just put that line in a mysql_connect.php file and include() it, so it's not on your source pages.
This way, even if someone is looking at your source, the password won't be immediately available.
Make sure your database permissions only allow that user certain privileges on the database, so even if the password is compromised, they only can modify things in that one database.

Superglobals: PHP security

Is it possible for a client to modify PHP superglobal variables, especially $_SERVER, somehow - maybe not in a common way?
In other words, is this code secure:
if (($this->error->getCode()) == '404') {
ob_clean();
echo #file_get_contents("http://".$_SERVER['SERVER_NAME'].'/404.html');
}
This code is fine - SERVER_NAME can't be modified. The ones to be careful with are $_SERVER['PHP_SELF'] or $_SERVER['REQUEST_URI'], as a user could add some js to the address bar - if these are written out to the screen they should be carefully escaped.
Your code is fine though.
Yes, that's fine.
No user can change any variable of your code unless you leave it open to them using some sort of POST/GET/COOKIE etc
On a side note, if the file is on your server, why are you using file_get_contents()?
In this case, since the $_SERVER variable only contains data related to the web server that the script is being executed on, I don't see any potential security issues unless the web server itself has been compromised. In that case, you've got a lot bigger problem on your hands. The main exception to this rule is if you use PHP_SELF or REQUEST_URI since those values can be altered via user input in the URL bar.

New Host - Php session data being saved to specified folder, but session variables are blank/not reading the data?

As the title suggests, I am having problems trying to move an existing site over to a new host.
I have edited my .htaccess find to point the php.ini session.save_path value to a new folder stored in my non public root.
This is working fine, I can see the sessions appear in this folder, with the correct entries written to them.
But for some reason, my scripts cannot make use of these sessions, as in the variables associated to them hold no value, as in, they come out blank.
Now, these scripts are in use on my old host and do work perfectly. And comparing the actual session data, once the files have been downloaded off each host, they are both exactly the same.
This leads me to think that this could be a server side issue. Possibly another php.ini value.
Has this happened to anyone before, or can anyone suggest a reason behind this kind of behavior.
It anyone has absolutely any input regrading this, or could point me in the right direction as to solve this issue. It would be more than greatly appreciated.
Thank you!
#Marc
sess.php
<?php
session_start();
$_SESSION['test'] = 'test';
include 'sess2.php';
?>
sess2.php
<?php
echo ''.$test.'';
var_dump($test);
?>
session data file value
test|s:4:"test";
Now when I load sess.php it includes sess2.php but the page only displays the vardump which is NULL. This is odd because the data has been written to the session as shown in the downloaded data file value...
Any ideas?
Looks like you're depending on register_globals. That's a hideously BAD thing in PHP which defaults to off these days. Try echo $_SESSION['test'] instead now. As well, such variables are only registered at script startup time/session_start. You'd need to use session_register() (DON'T) to make it take effect during the current execution run

Visibility of scripts on HTTP server

If I have a http server with various HTML pages and various PHP (or other) scripts, then If I try to view the code (as in Chrome's View source tool) then the PHP code is not shown, which is just as well. I want to know how secure from prying eyes is the code? Would a password hardcoded into the script be safe?
The only time your PHP code could become exposed is if the script somehow becomes treated as "not-PHP" and gets served up as raw text. If your server configuration is correct, then the code is 'safe' from web-based leakage.
That being said, it is best to put critical information that should remain private (usersnames/passwords, config variables, database DSNs, etc...) in a separate file that's kept OUTSIDE of the site's document root. That way, even if PHP becomes corrupted/disabled on the server, all a user would see is
<?php
include('critical_data_here.php');
?>
and not
<?php
$username = 'root';
$password = 'password';
$lotto_ticket_worth_50million = 'under the left couch cushion at 221B Baker Street';
?>
It's never 100% safe to keep passwords, especially on your server.
If you have to keep passwords in script - keep them in files, which placed not in public directory (can not be accessed by user in browser).
<?php
$password = "password";
?>
is save until you've got PHP module loaded.
<span>$password = "password";</span>
is not secure and will not work

PHP Session data not being saved

I have one of those "I swear I didn't touch the server" situations. I honestly didn't touch any of the php scripts. The problem I am having is that php data is not being saved across different pages or page refreshes. I know a new session is being created correctly because I can set a session variable (e.g. $_SESSION['foo'] = "foo" and print it back out on the same page just fine. But when I try to use that same variable on another page it is not set! Is there any php functions or information I can use on my hosts server to see what is going on?
Here is an example script that does not work on my hosts' server as of right now:
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views'] = $_SESSION['views']+ 1;
else
$_SESSION['views'] = 1;
echo "views = ". $_SESSION['views'];
echo '<p>Refresh</p>';
?>
The 'views' variable never gets incremented after doing a page refresh. I'm thinking this is a problem on their side, but I wanted to make sure I'm not a complete idiot first.
Here is the phpinfo() for my hosts' server (PHP Version 4.4.7):
Thanks for all the helpful info. It turns out that my host changed servers and started using a different session save path other than /var/php_sessions which didn't exist anymore. A solution would have been to declare ini_set(' session.save_path','SOME WRITABLE PATH'); in all my script files but that would have been a pain. I talked with the host and they explicitly set the session path to a real path that did exist. Hope this helps anyone having session path troubles.
Check to make sure you are not mixing https:// with http://. Session variables do not flow between secure and insecure sessions.
Had same problem - what happened to me is our server admin changed the session.cookie_secure boolean to On, which means that cookies will only be sent over a secure connection. Since the cookie was not being found, php was creating a new session every time, thus session variables were not being seen.
Use phpinfo() and check the session.* settings.
Maybe the information is stored in cookies and your browser does not accept cookies, something like that.
Check that first and come back with the results.
You can also do a print_r($_SESSION); to have a dump of this variable and see the content....
Regarding your phpinfo(), is the session.save_path a valid one? Does your web server have write access to this directory?
Hope this helps.
I had following problem
index.php
<?
session_start();
$_SESSION['a'] = 123;
header('location:index2.php');
?>
index2.php
<?
session_start();
echo $_SESSION['a'];
?>
The variable $_SESSION['a'] was not set correctly. Then I have changed the index.php acordingly
<?
session_start();
$_SESSION['a'] = 123;
session_write_close();
header('location:index2.php');
?>
I dont know what this internally means, I just explain it to myself that the session variable change was not quick enough :)
Check to see if the session save path is writable by the web server.
Make sure you have cookies turned on.. (I forget when I turn them off to test something)
Use firefox with the firebug extension to see if the cookie is being set and transmitted back.
And on a unrelated note, start looking at php5, because php 4.4.9 is the last of the php4 series.
Check who the group and owner are of the folder where the script runs. If the group id or user id are wrong, for example, set to root, it will cause sessions to not be saved properly.
Check the value of "views" when before you increment it. If, for some bizarre reason, it's getting set to a string, then when you add 1 to it, it'll always return 1.
if (isset($_SESSION['views'])) {
if (!is_numeric($_SESSION['views'])) {
echo "CRAP!";
}
++$_SESSION['views'];
} else {
$_SESSION['views'] = 1;
}
Well, we can eliminate code error because I tested the code on my own server (PHP 5).
Here's what to check for:
Are you calling session_unset() or session_destroy() anywhere? These functions will delete the session data immediately. If I put these at the end of my script, it begins behaving exactly like you describe.
Does it act the same in all browsers? If it works on one browser and not another, you may have a configuration problem on the nonfunctioning browser (i.e. you turned off cookies and forgot to turn them on, or are blocking cookies by mistake).
Is the session folder writable? You can't test this with is_writable(), so you'll need to go to the folder (from phpinfo() it looks like /var/php_sessions) and make sure sessions are actually getting created.
If you set a session in php5, then try to read it on a php4 page, it might not look in the correct place! Make the pages the same php version or set the session_path.
I spent ages looking for the answer for a similar problem. It wasn't an issue with the code or the setup, as a very similar code worked perfectly in another .php on the same server. Turned out the problem was caused by a very large amount of data being saved into the session in this page. In one place we had a line like this:$_SESSION['full_list'] = $full_list where $full_list was an array of data loaded from the database; each row was an array of about 150 elements. When the code was initially written a couple of years ago, the DB only contained about 1000 rows, so the $full_list contained about 100 elements, each being an array of about 20 elements. With time, the 20 elements turned into 150 and 1000 rows turned into 17000, so the code was storing close to 64 meg of data into the session. Apparently, with this amount of data being stored, it refused to store anything else. Once we changed the code to deal with data locally without saving it into the session, everything worked perfectly.
I know one solution I found (OSX with Apache 1 and just switched to PHP5) when I had a similar problem was that unsetting 1 specific key (ie unset($_SESSION['key']);) was causing it not to save. As soon as I didn't unset that key any more it saved. I have never seen this again, except on that server on another site, but then it was a different variable. Neither were anything special.
Thanks for this one Darryl. This helped me out. I was deleting a session variable, and for some reason it was keeping the session from committing. now i'm just setting it to null instead (which is fine for my app), and it works.
I know one solution I found (OSX with Apache 1 and just switched to PHP5) when I had a similar problem was that unsetting 1 specific key (ie unset($_SESSION['key']);) was causing it not to save. As soon as I didn't unset that key any more it saved. I have never seen this again, except on that server on another site, but then it was a different variable. Neither were anything special.
Here is one common problem I haven't seen addressed in the other comments: is your host running a cache of some sort? If they are automatically caching results in some fashion you would get this sort of behavior.
Just wanted to add a little note that this can also occur if you accidentally miss the session_start() statement on your pages.
Check if you are using session_write_close(); anywhere, I was using this right after another session and then trying to write to the session again and it wasn't working.. so just comment that sh*t out
I had session cookie path set to "//" instead of "/". Firebug is awesome.
Hope it helps somebody.
I had this problem when using secure pages where I was coming from www.domain.com/auth.php that redirected to domain.com/destpage.php. I removed the www from the auth.php link and it worked. This threw me because everything worked otherwise; the session was not set when I arrived at the destination though.
A common issue often overlooked is also that there must be NO other code or extra spacing before the session_start() command.
I've had this issue before where I had a blank line before session_start() which caused it not to work properly.
Adding my solution:
Check if you access the correct domain. I was using www.mysite.com to start the session, and tried to receive it from mysite.com (without the www).
I have solved this by adding a htaccess rewrite of all domains to www to be on the safe side/site.
Also check if you use http or https.
Edit your php.ini.
I think the value of session.gc_probability is 1, so set it to 0.
session.gc_probability=0
Another few things I had to do (I had same problem: no sesson retention after PHP upgrade to 5.4). You many not need these, depending on what your server's php.ini contains (check phpinfio());
session.use_trans_sid=0 ; Do not add session id to URI (osc does this)
session.use_cookies=0; ; ensure cookies are not used
session.use_only_cookies=0 ; ensure sessions are OK to use IMPORTANT
session.save_path=~/tmp/osc; ; Set to same as admin setting
session.auto_start = off; Tell PHP not to start sessions, osc code will do this
Basically, your php.ini should be set to no cookies, and session parameters must be consistent with what osc wants.
You may also need to change a few session code snippets in application_top.php - creating objects where none exist in the tep_session_is_registered(...) calls (e eg. navigation object), set $HTTP_ variables to the newer $_SERVER ones and a few other isset tests for empty objects (google for info). I ended up being able to use the original sessions.php files (includes/classes and includes/functions) with a slightly modified application_top.php to get things going again. The php.ini settings were the main problem, but this of course depends on what your server company has installed as the defaults.

Categories