I try to read Claroline source code to learn from their coding.
In index.php file, at the first line of code, they write
unset($includePath); // prevent hacking
You can see full claroline source code from here.
They commented that the line is used to prevent hacking..
I have no idea why should they unset $includePath while the variable is never defined before that line..
What is the purpose of that line of code do actually, and what hacking type that they means?
I have not looked at the source myself, but a bit of searches gives the following kind of security advisory :
Claroline mambo.inc.php and postnuke.inc.php "includePath" file include
Note that this relies on register_globals being enabled, which :
is not the default : it's been disabled by default for a very long time (since PHP 4.2.0)
is bad practice (unsafe ^^ as it allows anyone to inject variables into the PHP scripts ; which is why this one, in this case, is unset "to prevent hacking" )
The variable might not be set in code before that point, but if register_globals is turned on, it could be set in the URL by a malicious user.
It sounds like you're mostly looking for educational info, so here's a wee explanation of what register_globals used to do ... why it was there ... and why it's not any more (and you should never turn it on).
Variables come in via the $_GET and $_POST (or $_REQUEST) arrays ... what register_globals did, was make programming easier, by taking all the elements of these arrays, and putting them in the global namespace - i.e., making "regular" global variables out of them - so $_GET['includes'] could very easily be referenced simply as $includes.
This was in the happy days of the intarweb when the internet hadn't proliferated nearly as much as it has now, the technology wasn't so well know, there were fewer people who knew how to hack sites, and no one was writing worms that would automatically hack sites.
It was terribly insecure - because if a lazy programmer hadn't bothered to initialize all variables properly (e.g., checking if $includes is set, and then using it, before it's properly initialized), any of these improperly initialized variables could be set to whatever a hacker wanted. PHP was fairly new then, and many hobbyists were writing code - frequently also doing things like forgetting to properly escape variables in SQL queries. So one security flaw was usually easy to follow up with another one, allowing a hacker (or automated script) to gain deeper and deeper levels of access.
Around 2001 or so, people began very seriously warning about the consequences of register_globals - so this is a rather old issue, but it's still good to be on the lookout, especially with applications that don't have a solid reputation for security.
héhé it's a long story.
In fact in early "naive" version of claroline, Security was not really a target ;-)
$includePath was compute in init to buil all others paths of claroline.
With servers configured with register global=on, it's was a very easy way to hack.
ie : include($includePath."/lib/pager.lib.php");
This simple line was a "patch".
as require '../../../../inc/claro_init_global.inc.php';is included in all.
Conclusion : Claroline is an old code started in php4, with script writed for php3, secure (now) but old. The style is not a good inspiration for "modern" code :-)
Secure claroline was a great adventure -) Mathieu has done most of correction.
I remeber they work more than one month to be comptabile with register global off (I mean it 7y ago)
Related
I have a PHP code stored in the database, I need to execute it when retrieved.
But my code is a mix of HTML and PHP, mainly used in echo "";
A sample that looks like my code:
echo "Some Text " . $var['something'] . " more text " . $anotherVar['something2'];
How can I execute a code like the either if I add the data to the DB with echo""; or without it.
Any ideas?
UPDATE:
I forgot to mention, I'm using this on a website that will be used on intranet and security will be enforced on the server to ensure data safety.
I have a PHP code stored in the database
STOP now.
Move the code out of the database.
And never mix your code with data again.
It's not only a bad idea but also invitation to several type of hacking attempts.
You can do with eval(). but never use it . The eval() is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.
See eval. It lets you pass a string containing PHP and run it as if you'd written it directly into your file.
It's not a common practice to store executable PHP in a database; is the code you store really that different that it makes more sense to maintain many copies of it rather than adapting it to do the same thing to static data in the database? The use of eval is often considered bad practice as it can lead to problems with maintenance, if there's a way of avoiding it, it's normally worth it.
You can execute code with eval():
$code_str = "echo 'Im executed'";
eval($code_str );
BUT PAY ATTENTION that this is not safe: if someone will get access on your database he will be able to execute any code on your server
use the eval() function.
heres some info
http://www.php.net/manual/en/function.eval.php
something along the lines of:
eval($yourcode);
If that is the last resort, you want it to be secure as it will evaluate anything and hackers love that. Look into Suhosin or other paths to secure this in production.
As everyone'd indicated using eval() is a bad approach for your need. But you can have almost the same result by using whitelist approach.
Make a php file , db_driven_functions.php for instance. get your data from db. and map them in an array as below
//$sql_fn_parameters[0] = function name
//$sql_fn_parameters[1,2,3.....] = function parameters
Then define functions those include your php code blocks.for instance
my_echo($sql_fn_parameters){
echo $sql_fn_parameters[1];//numbered or assoc..
}
then pull the data which contains function name
after controlling if that function is defined
function_exists("$sql_fn_parameters[0]")
call function
call_user_func_array() or call_user_func()
( any you may also filter parameters array $sql_sourced_parameters_array does not contain any risky syntaxes for more security.)
And have your code controlled from db without a risk.
seems a little bit long way but after implementing it's really a joy to use an admin panel driven php flow.
BUT building a structure like this with OOP is better in long term. (Autoloading of classes etc. )
Eval is not safe obviously.
The best route IMO
Save your data in a table
Run a stored procedure when you are ready to grab and process that data
You should not abuse the database this way. And in general, dynamic code execution is a bad idea. You could employ a more elegant solution to this problem using template engines like Smarty or XSLT.
There are a few way to achieve this:
1) By using evil
eval($data);
That's not a typo, eval is usually considered evil and for good reasons. If you think you have fully validated user data to safely use eval, you are likely wrong, and have given a hacker full access to your system. Even if you only use eval for your own data, hacking the database is now enough to gain full access to everything else. It's also a nightmare to debug code used in eval.
2) Save the data to a file, then include it
file_put_contents($path, $data); include $path;
There are still the same security concerns as eval but at least this time the code is easier to debug. You can even test the code before executing it, eg:
if (strpos(exec('php -l '.$path), 'No syntax errors detected') === false))
{
include $path;
}
The downside to this method, is the extra overhead involved in saving the code.
3) Execute the code straight from the database.
You'd need to use database software that allows this. As far as I am aware, this is only includes database software that stores the content as text files. Having database software with "php eval" built in would not be a good thing. You could try txt-db-api. Alternatively, you could write your own. It would like become very difficult to maintain if you do though but is something to consider if you know exactly how you want your data to be structured and are unlikely to change your mind later.
This could save a lot of overhead and have many speed benefits. It likely won't though. Many types of queries run way faster using a traditional database because they are specifically designed for that purpose. If there's a possibility of trying to write to a file more than once at the same time, then you have to create a locking method to handle that.
4) Store php code as text files outside of the database
If your database contains a lot of data that isn't php code, why even store the php code in the database? This could save a lot of overhead, and if you're database is hacked, then it may no longer be enough to gain full access to your system.
Some of the security considerations
Probably more than 99% of the time, you shouldn't even be attempting to do what you are doing. Maybe you have found an exception though, but just being an intranet, isn't enough, and certainly doesn't mean it's safe to ignore security practices. Unless everyone on the intranet needs full admin access, they shouldn't be able to get it. It's best for everyone to have the minimum privileges necessary. If one machine does get hacked, you don't want the hacker to have easy access to everything on the entire intranet. It's likely the hacker will hide what they are doing and will introduce exploits to later bypass your server security.
I certainly need to do this for the CMS I am developing. I'm designing it mainly to produce dynamic content, not static content. The data itself is mostly code. I started off with simple text files, however it slowly evolved into a complicated text file database. It's very fast and efficient, as the only queries I need are very simply and use indexing. I am now focusing on hiding the complexity from myself and making it easy to maintain with greater automation. Directly writing php code or performing admin tasks requires a separate environment with Superuser access for only myself. This is only out of necessity though, as I manage my server from within, and I have produced my own debugging tools and made an environment for code structured a specific way that hides complexity. Using a traditional code editor, then uploading via ssh would now be too complicated to be efficient. Clients will only be able to write php code indirectly though and I have to go to extreme lengths to make that possible, just to avoid the obvious security risks. There are not so obvious ones too. I've had to create an entire framework called Jhp and every piece of code, is then parsed into php. Every function has to pass a whitelist, is renamed or throws an error, and every variable is renamed, and more. Without writing my own parser and with just a simple blacklist, it would never be even a tiny bit secure. Nothing whatsoever client-side can be trusted, unless I can confirm on every request that it has come entirely from myself, and even then my code error checks before saving so I don't accidentally break my system, and just in case I still do, I have another identical environment to fix it with, and detailed error information in the console that even works for fatal errors, whilst always been hidden from the public.
Conclusion
Unless you go to the same lengths I have (at minimum), then you will probably just get hacked. If you are sure that it is worth going to those lengths, then maybe you have found an exception. If your aim is to produce code with code, then the data is always going to be code and it cannot be separated. Just remember, there are a lot more security considerations other than what I have put in this answer and unless the entire purpose of what you are doing makes this a necessity, then why bother at all mix data with code?
In order to gain more experience in Wordpress I delved into its code base to study its inner working and its workflow, and I was quite astonished when I saw that:
They implement register_globals (an excerpt from wp-includes/class-wp.php):
// The query_vars property will be extracted to the GLOBALS. So care should
// be taken when naming global variables that might interfere with the
// WordPress environment.
function register_globals() {
global $wp_query;
// Extract updated query vars back into global namespace.
foreach ( (array) $wp_query->query_vars as $key => $value) {
$GLOBALS[$key] = $value;
}
They rely on magic quotes (exerpt from wp-includes/functions.php. magic_quotes_gpc is turned off at bootstrapping, before calling this function):
function add_magic_quotes( $array ) {
foreach ( (array) $array as $k => $v ) {
if ( is_array( $v ) ) {
$array[$k] = add_magic_quotes( $v );
} else {
$array[$k] = addslashes( $v );
}
They rely on addslashes (but since 2.8.0 they introduced also mysql_real_escape_string, but the _weak_escape() function that uses addslashes() still exists in the wpdb class)
UPDATE: I see they emulate prepared statements by using sprintf() and custom placedholders, so queries should be safe I think. Still I'm puzzled on why they don't provide at least mysqli, after all the detection of Mysql and PHP version happens early in the bootstrapping sequence.
Now, from the year-long frequentation of SO I learned a lot of things, especially that the above three function are "deprecated" and show security issues, and are watched in horror by many.
But WP must have a reason to use them. I'd like to know from more experienced programmers if there are really security issues, or if sometimes their usage is just too clouded in rumors and false convinctions. I know that magic_quotes is an heritage from the past, and the same could be said for addslashes (at least when used for databases), but while googling before asking this I found many websites talking about using addslashes() over mysql_real_escape_string().
I'm interested in knowing a clear, detailed reason on why those badly depicted functions are used; Wordpress had had many improvements over the years, addressing different aspects, and yet these functions are still used; I'm looking, therefore, to a concrete explanation over the positive aspects that somehow override the negative ones and justify the usage of those functions.
I'm not looking for opinions (I perfectly know they're offtopic here), nor I am ranting about Wordpress, I hope this is clear. I'd just like to know why many php programmers consider these functions "bad", and yet a worldwide giant like Wordpress, who's at the 3rd version now, still uses them.
Is this for compatibility with different servers and php versions? (they check very earl for those, though).Is there something I miss about this functions, how important they can be in an environment like wordpress (or in general)? I'm quite confused, to be honest.
(Wordpress Open Tickets over Time)
Don't rely on the Wordpress codebase to do assumptions about good practice or current standards in PHP coding. I'm saying this as someone who has fiddled with wordpress development over a longer period of time.
Wordpress codebase is about 10 years old, it's full of legacy code[1]. The program can not evolve on the code-level much because of that, so you find a lot of workarounds for problems that are already solved nowadays much better.
Just take this story: PHP had magic quotes. Wordpress developers thought it was useful. So for those hosts that did not have it configured, they added it. Ending up whith code that expects slashed input data often and at various places. The simple thing is, now they just can't change it to proper input processing and sanitization easily because of the usage of (super)globals introducing static global state nearly everywhere.
You can not easily refactor such code.
Same for the database class. It has a long history, originally based on an early version of ezSQL. At that time there was not mysql_real_escape_string and when it was introduced, the WP devs had the problem that not all installation bases support it.
So don't wonder about the coding practice you find inside the Wordpress code. You'll learn how things could have been done years ago and with more or less outdated PHP versions. It's not that long ago that Wordpress switched to PHP 5 for example.
Backwards compatibility.
Target a large amount of (technically more or less outdated) hosts.
Don't break what works with defects.
This might not be your list of priorities (hopefully), projects differ here a lot. But having a legacy code-base alone is a burden regardless how project priorities are set. Wordpress is only one example.
[1] see Milestones of WordPress: Early Project Timeline (ca. 2000 to 2005))
In complement to #tom answer.
Magic Quotes
Automatically parsing the whole entries and adding magic quotes is both creating bugs and useless.
Useless as you cannot rely on magic quotes to secure your input (multy-bytes encoding bugs for SQL injections is an example). So you need to apply a real filter before saving your data to a database
Creating bugs: If you need to really escape your data before a save in database you have to check that it's not already escaped (and the simple fact this settings exists and may be enforced by the hosting environment makes that you have to check this setting was set or not).
Creating bugs: All the data sent by the user is not always dedicated to a database storage. Escaping it may break the content, think about a json content for example, or even file content with the dangerous magic_quote_runtime
Creating bugs: All database storage are not escaping quotes the same way...
So Why?, why do we see such function in a CMS?
see that here it's an add_magic_quotes function, that can be used on a dedicated array, maybe not on _GET or _POST. But effectively the fact this function is just using addslashes and not a database dedicated function makes it quite bad.
The fact the hosting provider may enforce an automatic magic quotes is a nightmare for a CMS developper. Either you detect it and tell the user you refuse to run, or you have to manage the fact the content may or may have not be magically-addslahed... and to put everyone in the same state, you run the non-addslashed content in this function so that at least everyone is in the same (bad) state.
From what I can see on Wordpress, before the save a stripslahes_deep is performed in the wp_insert_post. And add_magic_quotes is usually performed on data pulled from Db before this data is send to the wp_insert_post. This may me think the problem is effectively to add slashes before removing them... maybe because sanitize filters which happen before the save expect content with slashes, or maybe because no one remember why the code is running in this way :-)
register_globals
Seems that this is the way to implement a Registry pattern in wordpress... They wanted to make the code simple to understand, and to allow a simple way to access importants objects like the query or the post. And an object oriented Registry class was not in the simple PHP way, where the $_GLOBALS array is already an existing registry.
Having a Registry is a perfectly valid thing in an application. a register_global thing is dangerous only if you allow some user input to override your valid secure input. And of course only if this secure input is taken from $_GLOBALS elsewhere (or with global keyword).
The dangerous part in the function here is the part of the function you have extracted, the loop on $query->query_vars. You will have to track the calls to see if user injected keys could run throught wp_parse_args and end in that function. But the next part of this function is fixing $_GLOBALS content for several objects:
$GLOBALS['query_string'] = $this->query_string;
$GLOBALS['posts'] = & $wp_query->posts;
$GLOBALS['post'] = (isset($wp_query->post)) ? $wp_query->post : null;
$GLOBALS['request'] = $wp_query->request;
So at least theses globals cannot be overwritten by user input and are safe.
So, theses functions are bad. But you can use them if you understand what they do and what you need to do to prevent the bad effects. And when you want to implement a simple framework for developpers, available on a very wide environments you sometimes have to use them.
But for sure it's a bad practice, you can certainly find bad wordpress plugins using $_GLOBALS in the wrong way or misusing the add_magic_quotes to data pulled from db wordpress concept. But there will be years before a Zend Framework CMS gained such a big number of contributions.
Magic Quotes
The following text is taken from PHP.net
http://www.php.net/manual/en/security.magicquotes.why.php
There is no reason to use magic quotes because they are no longer a supported part of PHP. However, they did exist and did help a few beginners blissfully and unknowingly write better (more secure) code. But, when dealing with code that relies upon this behavior it's better to update the code instead of turning magic quotes on. So why did this feature exist? Simple, to help prevent SQL Injection. Today developers are better aware of security and end up using database specific escaping mechanisms and/or prepared statements instead of relying upon features like magical quotes.
addslashes() vs mysql_real_escape_string()
The reason why you should use mysql_real_escape_string() is because it's a "MySQL function" and is created especially for escaping user input before it's executed in a mysql query, while addslashes() is a "PHP function". That probably sounded a little weird, but there's one important difference between the two and it has to do with the use of single- and multi-byte characters. You can still inject databases protected by the addslashes function, but injecting databases protected by mysql_real_escape_string is far more difficult. You can read more about it HERE
Register Globals
The reason why you should NOT use register_globals is because variables become accessible to everyone, which means that in the following example you would be able to set $access to true if it hasn't been initialized before
<?php
if (isAuthenticated()) { $access = true; }
if ($access == true) {
include(controlpanel.php);
}
?>
The above code would give you sh#! loads of problems, but if we initialize the variable first by adding the following to the top of the page
$access = false;
...we should be fine even if we have register_globals ON
So, if the Wordpress team have initialized all variables (which they probably have) then you don't have to worry about the use of globals.
Conclusion
It's definitely bad practice using any of those 3 functions/features and I would never do it myself. Are you sure you're working with the latest version of Wordpress? Like someone commented, if you are using the latest version it's because of laziness or worse it's still in there. I'ld never use Wordpress for anything other than blogs that doesn't require much security..
Wordpress. I've spent a lot of sleepless nights trying to answer the only one question: "Why??"
Since I've faced with its source code I hate it. It is awful. And let my post(and reputation as well) will be minused but it's true.
It doesn't have core. There is a rubbish of code instead of core. It reminds php3. Huge heap of unrelated and unlogical functions are used in it. "Copy and Paste" - the only one design pattern is used in wordpress.
Yes, the have emulated using of prepared statements. But why they don't use PDO, or mysqli? They have copypasted almost all PDO functions but haven't use it instead. Using of mysqli instead of mysql requires even less efforts.
They use myql_real_escape_string. But there is still something like protect_string_strongly, protect_string_weakly. There is no only only one function - do_not_protect_string_i_believe_my_users.
Global variables - is the philosophy of wordpress. "If we don't know how to change this var we'll mark it as global var and everybody will be happy." - here is what wordpress developers thought when they developed hellpress.
Every new version contains a lot of new in design, they add new default themes, they change background color in admin area from #ccc to #cdcdcd, they use dropdown menu in admin area instead of accordeon. And it awesome. But they do not improve its code.
Did you read comments in WP "core"? No? And I did. They are "awesome". Something like "What this function is called for? Let's it leave just in case." or "Do not hardcode this in new version." and so on.
The only one answer to the question "Why?" I got is: "Because it works. And if it does work do not touch it!!!"
wordpress.org is one most visited sites in the world. Why? Because nobody able to understand wordpress's logic. Everybody every time needs to ask something on the forum or read in the codex.
I hope you understand my point of view.
There is no better way to answer why they are bad than referring to the PHP documentation on magic_quotes:
Why did we use Magic Quotes?
Why to not use Magic Quotes
Also note:
This feature has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.
So why does Wordpress still use Magic Quotes?
Wordpress minimum requirements uses PHP 4.3. Yes, it is absolutely a backwards compatibility reason.
What about the other functions?
I am honestly not sure. Relying on super globals is a very bad idea. This is simply laziness of the Wordpress development team. Perhaps they have more important issues to work on.
They did this for one reason:
To make sure Wordpress is compatible with most Web Hosting providers.
This is wrong place to ask such a question.
It is always a bad idea to ask some third party person of the reasons someone else had somewhere else.
It is obvious that you can't get an answer here unless you will lure some authorized wordpress developer here with such a bounty.
Yet your question is too broad. However, it is possible to answer it's abstract part:
I'd like to know from more experienced programmers if there are really security issues, or if sometimes their usage is just too clouded in rumors and false convinctions.
Does hands washing really prevents a disease?
What if I won't wash my hands - will I surely sick?
Most of time - no.
As a general habit - yes.
These features (although indeed, as any other feature of our unlucky language, too clouded in rumors) are merely a hygiene everyone have to follow as a basic instinct.
Although most of time...
addslashes won't do any harm as long as your encoding is either utf-8 or any single-byte one;
register globals won't do any harm if you initialize all your variables;
magic quotes won't do any harm as long as you have all your variables quoted for the SQL and slashes stripped for any other use;
...any exception from these circumstances can make you sick with high probability.
One of the main differences between mysql_real_escape_string() and addslashes is that mysql_real_escape_string() works in conjunction with the character set so it knows how to properly escape data based on the character set.
Generally I think the best approach is to use a request class and do all your stuff there.
That way there is only one place where you deal with GET,POST,COOKIE, SERVER etc which makes it far easier to manage in contrast to having a bunch of random functions doing different things. That's just a recipe for disaster.
I have a rather big php site, which was written for php4 and register_globals enabled. It is old custom CMS. Now I want to run it on the php5 hosting without register_globals. Is it possible to change parameters parsing from $id to $_GET["id"] automatically, with some script?
I can get parameters names from wget -r on this site.
It have dozens of php scripts, and it is not very easy to do this change manually.
PS: UPDATE: I want to convert only GET variables. The additional line is $var_name = $_GET["var_name"] for each parameter. This line should be inserted very high in the script, e.g. by adding a new <? ?> section at very top.
Running such tool would introduce great risk of introducing errors in code.
I'd suggest running extract() on superglobals, so that you force register_globals and aplication will work properly.
http://php.net/manual/pl/function.extract.php
Next, when everything will be ok, write an OO wrapper for input parameters, pack it into nice DI Container and start manually transitioning whole script to the new style.
I don't know of any tools that help you in the conversion, but you have several options:
Simulate register globals by doing the same thing that register_globals did: At the beginning of the script, put all variables from GET and POST into the global variable namespace (i.e. via extract). While this is fastest and the most easy solution, it will lead to the security problems that register_globals was known for, and it doesn't help with the performance of your application
Determine the variables that are used and load them only via the init script into $GLOBALS only. Still not nice
Determine the variables that are used and replace the GLOBALS usage with REQUEST
Walk through it manually. This way, you can be sure everything is correct and will have the least trouble afterwards.
From your description, solution 1 or 2 might be the best for you since the cms doesn't seem to be updated anyway (which is a shame).
Although the actual finding/replacing might take more time, doing this manually will most likely result in less bugs / weird behaviour.
If are not the original author of the application, then this manual finding/replacing is also an opportunity for you to become much more familiar with the codebase than some automatic method.
Automatic: fast, almost definitely will result in some horrible bugs
Manual: slower (likely), almost definitely will result in better understanding, less bugs - and any bugs that are introduced will be easier to fix because of your better understanding.
I have an admin site that I have copied over to a new server to test for bugs and put live, along with some other sites.
The admin appears to have REGISTER GLOBALS on and is using it for most of the 300 php files.
Based on the fact that you have to login to this system anyway is it worth the weeks of work to re code all the variables?
Or be happy that I would fix each page as I add any new feature to it in the future?
Does Register Globals leave problems in code that has been cleaned, if we don't fix all at once?
I'm guessing it could as $user_id can be set by any global.
This app could be littered with many other shoddy programming practices as well. (How large is the app to warrant 300 php files?). If that's the case, it might be a good idea to leave the app as it is and code a new version from scratch on top of a decent framework if maintenance has already become too troublesome.
I would disable register_globals from the php.ini, and put a code block at the top of each script that extracts the variables from the $_REQUEST, $_GET or $_POST, something like:
$nVars = extract($_GET, EXTR_SKIP);
The above code will register variables by the same name as the key in the passed array. It is useful for quickly refactoring old REGISTER_GLOBALS enabled code, but you must be careful. Read the following excerpt from the PHP extract() documentation:
Do not use extract() on untrusted
data, like user-input ($_GET, ...). If
you do, for example, if you want to
run old code that relies on
register_globals temporarily, make
sure you use one of the
non-overwriting extract_type values
such as EXTR_SKIP and be aware that
you should extract in the same order
that's defined in variables_order
within the php.ini.
Register_Globals is insecure and shouldn't be used. If I were you I would rewrite the code, or the application itself from scratch. However if this is an admin system, and no one knows its URL and therefore only the admin himself can access it, then you should be fine with not changing it (just make sure its URL remains a secret)
It can lead to some very serious security issues, it kinda depends on how it's coded.
For example:
<?php
// $loggedin comes from $_SESSION['loggedin']
if($loggedin)
{
echo 'Loggedin!';
}
else
{
echo 'Please login';
}
?>
The main problem here is, is that the script doesn't check where $loggedin comes from. So if I would do script.php?loggedin=1, I would be logged in. Seeing as there are ~300 PHP files, it would be hard to check everything.
So keeping it is a (very) bad idea. Even it you'd use .htaccess to block access, it would probably lead to problems in the future (IE web hoster setting REGISTER_GLOBALS off) and confusion.
Don't re-write the entire system. If the system works and you'll casually upgrade as you go you don't need to start from scratch.
I would weigh the importance of addressing the Register Globals based on the sensitivity of the information.
If it's a well built system you should be able to see what variables are used throughout the site and simply make them available at the top of the pages. Be wary of any functions that pull in their data through global $this, $that;
My vote, if the data is important to protect, is to do the work.
This depends on your quite a lo t of things. Just to name a few:
Company's security policy
Cost to rewrite
Importance of the application
Impact on other parts of the application.
etc
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.