Should I Make Database Connection With PHP Includes - php

I've been told that it is unsecure to make database connections inside a PHP includes. For example If I have a login page and add an "include('process.php')" at the top of the page that has a database connection, is that unsecure?

For example If I have a login page and add an "include('process.php')" at the top of the page that has a database connection, is that unsecure?
No.
Maybe the person who told you this was talking about something else - like including a file using a dynamic value coming from a GET parameter, or using remote http:// includes, or as #AlienWebguy mentions, having the password include inside the web root. But using includes in itself is not insecure.

It's only insecure if you are storing your passwords literally in your PHP files. They should be declared outside of the web root. That being said, the lack of security is not due to the use of the include() function.

In and of itself, no, it is not insecure. How it's implemented inside the include is of course a different story.

That's the way I've always done it. I make sure that the include is in a different directory that has open permisions and that the directory your writing in has locked permisions. Hopefully that makes sense.

This question is way too broad to get a good answer from anyone. Short answer is no, there's nothing inherently insecure about including a file that connects to a database. However, if you write code that isn't written properly, then yes it may be insecure to do this.

Since using "include('process.php')" is exactly the same as pasting 'process.php' into the code of the other file, that should not be, per se, a security issue. The insecurity could be in your code, not in the fact the you use the "include". In fact, it could maybe improve the safety of your code, due the reuse.

Related

mysql/php is this a secure way to connect to mysql DB?

Ok , so many people are asking this question, and there are many approaches on how to make the connection to DB secure,
Now I did some googling , many suggest, putting the connection to DB code in a file outside the html_public , and to call it from there when I need to make a connection.
to be honest, am happy with what I have, though I'm not sure how secure it is,
this is how I connect to the DB:
first, I make sure all inputs are fully escaped and validated...
after , in the same page , i make the connection, for example:
mysql_connect("localhost","Admin","Password") or
die ("DB Connection Error");
mysql_select_db("Users") or die ("DB Error");
and the rest of the code after, I close the mysql connection.
Now , It just don't feel right that the DB user info are written in the page, but how can someone (a "hacker") , get this info?
I mean , all inputs are fully escaped and validated, the users I use have very limited previleges, like select and update... only.
Is this secure?? and if not, can u please suggest a more secure way?
Thank you very much for ur help in advance :)
shady
The reason you should consider putting this file outside the web root is that some hosting providers have temporarily stopped interpreting PHP from time to time (due to configuration faults, often after an update on their part). The code will then get sent in clear text and the password will be out in the wild.
Consider this directory structure, where public_html is the web root:
/include1.php
/public_html/index.php
/public_html/includes/include0.php
Now consider this index.php:
<?php
include('includes/include0.php');
do_db_work_and_serve_page_to_visitor();
?>
If the web server starts serving this file in the open, it won't take long before someone tries to download include0.php. Nobody will be able to download include1.php, however, because it's outside the web root and therefore never handled by the web server.
I've personally not heard of a hosting provider not interpreting PHP, leading to your php source code going public. I just did a quick test on this on a RHEL5-Based server without php installed, and just got back a blank page when trying to access a php document.
mysql_* functions have become deprecated with the latest releases of php, and are now moving towards mysqli, as an overall more efficient and secure solution; I'd recommend taking a look into that; http://php.net/manual/en/book.mysqli.php - there's no deprecation errors or anything of the sort yet in PHP5.4 for using plain mysql_ functions, but if you're looking to keep on top of things, take a look into mysqli.
As for a quick answer to your above question, to be honest, I'd see that method as reasonably secure. Just make sure you've got escape chars etc set up, and I don't think you'll run into any issues.
Edit: Some people have posted that in very rare cases, some providers can leak your php source code in this manner. If this is the case, my first advice would be to switch provider.. but using an include_once to load your db info from another php file/lib would be a quick workaround for this. But again, if your provider's setup does allow for leaks such as these, I would be more concerned about their security than yours.
You can have php grab your DB password from a text file stored outside of the public webspace (using fopen), but I personally don't see any real reason for doing this.
Best of luck!
Eoghan
The best pratice is to use PHP PDO instead of the old mysql API.
Take a look: http://php.net/manual/en/ref.pdo-mysql.connection.php
Also, here's an interesting article: http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/

Security implications of writing files using PHP

I'm currently trying to create a CMS using PHP, purely in the interest of education. I want the administrators to be able to create content, which will be parsed and saved on the server storage in pure HTML form to avoid the overhead that executing PHP script would incur. Unfortunately, I could only think of a few ways of doing so:
Setting write permission on every directory where the CMS should want to write a file. This sounds like quite a bad idea.
Setting write permissions on a single cached directory. A PHP script could then include or fopen/fread/echo the content from a file in the cached directory at request-time. This could perhaps be carried out in a Mediawiki-esque fashion: something like index.php?page=xyz could read and echo content from cached/xyz.html at runtime. However, I'll need to ensure the sanity of $_GET['page'] to prevent nasty variations like index.php?page=http://www.bad-site.org/malicious-script.js.
I'm personally not too thrilled by the second idea, but the first one sounds very insecure. Could someone please suggest a good way of getting this done?
EDIT: I'm not in the favour of fetching data from the database. The only time I would want to fetch data from the database would be when the content is cached. Secondly, I do not have access to memcached or any PHP accelerator.
Since you're building a CMS, you'll have to accept that if the user wants to do evil things to visitors, they very likely can. That's true regardless of where you store your content.
If the public site is all static content, there's nothing wrong with letting the CMS write the files directly. However, you'll want to configure the web server to not execute anything in any directory writable by the CMS.
Even though you don't want to hit the database every time, you can set up a cache to minimize database reads. Zend_Cache works very nicely for this, and can be used quite effectively as a stand-alone component.
You should put your pages in a database and retrieve them using parameterized SQL queries.
I'd go with the second option but modify it so the files are retrieved using mod_rewrite rather than a custom php function.

PHP syntax displaying in HTML source

In my CMS I've added this code <div><?php include("my_contact_form.php") ?></div> which updates to a db. I can see it there OK.
I have this php code in my display page after the db call:
$content = $row['content'];
when I echo $content inside the body this is displayed in the HTML source:
<div><?php include("my_contact_form.php") ?></div>
How could this possibly be? Why wouldn't it show my contact form?
If anyone has any suggestions I would be extremely grateful.
Cheers.
It sounds like you are storing the PHP code in the database and expecting it to be executed when you echo it. This won't happen, as far as the PHP interpreter is concerned it's just text (not PHP code) so it will just echo it.
You can force PHP to interpret (/run) the code in your string with the eval() function, but that comes with a large number of security warnings.
Storing code in the database is rarely the right solution.
The simple solution is to run eval() on your content.
$content = $row['content'];
eval("?>".$content."<?php");
The closing PHP tag and opening PHP tag allow you to embed HTML and PHP into the eval() statement.
About the choice of storing your PHP and the DB vs Files.
Assuming you're goal is to have PHP that can be edited by admins from an interface, and executed by your server.
You have two choices:
Write the PHP to files, and include or exec() the files.
Write the PHP to the DB, and exec() or cache the content to files and include().
If you're on a dedicated or VPS server, then writing to files is the best choice.
However, if you're on a shared hosting system, then writing to DB is actually the safer choice. However, this comes with the task that you must use a very safe system for querying the database, to eliminated all SQL injection possibility.
The reason the DB is safer in a shared environment is due to the fact that you'll need write access for the PHP process to the PHP files. Unfortunately, on "every" shared hosting setup, the same PHP user runs on each account and thus has write access to the same PHP files. So a malicious user just has to sign up for hosting and land on the same physical machine as you, or exploit a different account to gain access to yours.
With saving the PHP in mysql, PHP cannot write to the mysql files since it doesn't have the privileges. So you end up with more secure code, if you eliminate the possibility of SQL injection. Note that if you have an SQL injection vulnerability with write ability, then you have also opened a remote code execution vulnerability.
Edit:
Sorry the correct syntax is:
eval("\r\n?>\r\n ".$php."\r\n<?php\r\n");
Thats been tested quite intensively to work on every PHP configuration/setup.
You're echoing $content, that just prints out the value, but it doesn't execute any PHP within it.
If you're using an existing CMS, like Joomla, Drupal, etc.
The CMS is handling the text from the DB as what it is - text. It won't execute the text, it's probably just pulling it as a string from the DB and echoing it onto the page. See Brenton Alker's answer for a better explaination.
If possible, it would be better to work within the functionality of the CMS, and avoid hacking your CMS's source to use eval(). Depending which CMS you're using, there may be a feature (ie: a button in your editor, or similar) to include code from another file.
Or perhaps there's a feature to create "objects", "modules", whatever-they-wanted-to-call-them, which would allow you to place the code (as HTML) that you're trying to include into an "object", stored in the DB, allowing you to include it in numerous pages. This would attain the same goals as doing an include() in PHP (code reuse, avoiding duplicates, making changes in one place, etc.) but it would also save you having to hack the CMS or start risking security.
If you've built your own CMS
You may want to build such a feature in. It all depends on your needs, and how important security is.
Ultimately if you use eval(), and if anyone hacks either:
Your DB
Your CMS's admin interface
then they will be able to execute any PHP code on your server. And if you have exec() enabled in your php.ini (which is not safe), then they will also be able to run any code they want on your server itself... eeek!
Thanks for this - simple solutions are the best for me! Thanks for the extra info too. Sadly eval() as you suggest it didn't work for me here. So, plan C, I've decided to create a selectable tinymce template that has an iframe which calls the contact_form page and all the processing happens in the iframe. This works. Thanks everyone!

accessing values globally

I have 2 files namely:
uploading.php
emaillinks.php
both include a file inc.php which has all the include files and initiate database connection.
a variable is declared in file uploading.php, i wanted to know how can i access it in emaillinks.php, i cant include uploading.php in emaillinks.php.
I want to avoid cookies because data is big and always different.
what is the best option to make it accessible by emaillinks.php?
Thank You.
Depending on what it is, you could put it into the database or into the session ($_SESSION)
If you can't include you'll need to go with session variables or cookies.
Reading your question the words "registry pattern" suddenly popped into my head. This might be a bit of overkill for your needs, but it might be worth looking into.
You'd probably have to do a lot of refactoring to make this solution available. So you'd probably be best using the session, database or some text file to store your variable.
Here is a good article on using a registry, though (if you're interested).

How do I execute PHP that is stored in a MySQL database?

I'm trying to write a page that calls PHP that's stored in a MySQL database. The page that is stored in the MySQL database contains PHP (and HTML) code which I want to run on page load.
How could I go about doing this?
You can use the eval command for this. I would recommend against this though, because there's a lot of pitfalls using this approach. Debugging is hard(er), it implies some security risks (bad content in the DB gets executed, uh oh).
See When is eval evil in php? for instance. Google for Eval is Evil, and you'll find a lot of examples why you should find another solution.
Addition: Another good article with some references to exploits is this blogpost. Refers to past vBulletin and phpMyAdmin exploits which were caused by improper Eval usage.
Easy:
$x // your variable with the data from the DB
<?php echo eval("?>".$x."<?") ?>
Let me know, works great for me in MANY applications, can't help but notice that everyone is quick to say how bad it is, but slow to actually help out with a straight answer...
eval() function was covered in other responses here. I agree you should limit use of eval unless it is absolutely needed. Instead of having PHP code in db you could have just a class name that has method called, say, execute(). Whenever you need to run your custom PHP code just instantiate the class of name you just fetched from db and run ->execute() on it. It is much cleaner solution and gives you great field of flexibility and improves site security significantly.
You can look at the eval function in PHP. It allows you to run arbitrary PHP code. It can be a huge security risk, though, and is best avoided.
Have you considered using your Source Control system to store different forks for the various installations (and the modules that differ among them)? That would be one of several best practices for application configuration I can think of. Yours is not an unusual requirement, so it's a problem that's been solved by others in the past; and storing code in a database is one I think you'd have a hard time finding reference to, or being advised as a best practice.
Good thing you posted the clarification. You've probably unintentionally posed an answer in search of a suitable question.
Read php code from database and save to file with unique name and then include file
this easy way for run php code and debug it.
$uniqid="tmp/".date("d-m-Y h-i-s").'_'.$Title."_".uniqid().".php";
$file = fopen($uniqid,"w");
fwrite($file,"<?php \r\n ".$R['Body']);
fclose($file);
// eval($R['Body']);
include $uniqid;
How I did this is to have a field in the database that identified something unique about the block of code needing to be executed. That one word is in the file name of that code. I put the strings together to point to the php file to be included. example:
$lookFor = $row['page'];
include("resources/" . $lookFor . "Codebase.php");
In this way even if a hacker could access you DB he couldn't put malicious code straight in there to be executed. He could perhaps change the reference word, but unless he could actually put a file directly onto the server it would do him no good. If he could put files directly onto the server, you're sunk then anyway if he really wants to be nasty. Just my two cents worth.
And yes, there are reasons you would want to execute stored code, but there are cons.

Categories