I want to make a programming environment. I will explain it with an example.
One programmer will write that code;
<html>
<head>
<?php definedMetaTags(); ?>
</head>
</body>
Programmer will save this file and then upload to my system. That file will be executed at server side and then they system will turn generated code back.
That definedMetaTags() function will be already written in the system.
An example of Compiler.php:
<?php
require_once("definitionsForProgrammer.php");
include("uploadedfile.php");
?>
My question is that I want to allow that uploadedfile.php only what functions I want. Else, maybe that programmer writes some codes what I want him/her to do. (Deleting files, mysql connection, etc.)
Is there any way to allow a code only specific functions, variables, constans?
If the goal is to allow a user to insert placeholders that will be replaced by some PHP function execution, then there's no need to treat the uploaded file as PHP code:
<html>
<head>
{[definedMetaTags]}
</head>
</body>
Then Compiler.php would look like this:
<?php
require_once("definitionsForProgrammer.php");
$macros = array();
$macros['definedMetaTags'] = definedMetaTags();
$output = file_get_contents("uploadedfile.php");
foreach($macros as $macro=>$value) $output = str_replace("{[$macro]}", $value, $output);
echo $output;
?>
The definedMetaTags() function would need to be reworked so that it returns the tags as a string instead of printing them directly to output.
This method would allow you to define any number of macros without exposing yourself to all the security risks the others here have mentioned.
If you're aiming for security and you want to let them to write functions, then the short answer is: no.
Essentially you're asking for a PHP sandbox which will let you constrain what code can be executed. PHP would have to support this at a fundamental level for it to work. For example, supposing you took the approach of saying "I only allow the user to write a function named 'foo'". Inside that function, though the user can do all kinds of bad things like making system calls, downloading other code and executing it, etc. In order to prevent this you'd need to implement checks at a much lower level in the system.
If you're willing to restrict the scope only to variable definitions then yes you can do it. You can use token_get_all() and token_name() to examine the file to make sure that it doesn't have any code that you don't want in it. For example:
foreach (token_get_all(file_get_contents("uploadedfile.php")) as $token) {
if (is_array($token)) {
echo token_name($token[0]), " ";
} else {
echo $token;
}
}
If you don't like any tokens you see, don't include the file. You could theoretically guard against bad functions this way as well, but it'll require a fair amount of effort to properly parse the file and make sure that they're not doing something bad.
references:
http://www.php.net/manual/en/function.token-get-all.php
http://www.php.net/manual/en/function.token-name.php
http://www.php.net/manual/en/tokens.php
Well, if i'm understanding your question correctly. If you include("uploadedfile.php"); you will acquire everything in it.
What you could do is break your code up into related sections (whether it be via classes or just function definitions in a file) then only include the file/class that you want.
(let me know if that's not what your asking)
Related
What I am trying to do is change a variable in fileb from filea. Kind of like using fileb as a config file in a way.
Example:
File A:
require_once "fileb.php";
if($power == 'off') {
exit;
}
if($test1 == 'one') {
echo "The first option is selected";
} elseif($test1 == 'two') {
$power = 'off';
}
File B:
$power = 'on';
So in this example a user id prompted for $test1, if they reply with "one" they get a echo. What I want to do is make it so if they reply with "two" it shuts down the page, and not just for them but for everyone. I am trying to do all of this without using a DB, that would be too easy lol. Thanks for the help!
I am trying to do all of this without using a DB, that would be too easy
There's a reason using a database for this is easy. It's the correct way to accomplish this task. Modifying actual PHP code files is a famously bad idea. (And one that somebody on Stack Overflow has almost weekly, it seems.)
If you include the file as part of the executing code, you can use the variable as any other. This allows you to manipulate the variable in a transient way, but not manipulate the code which creates the variable.
What you're trying to do is persist that changed variable. In order to do that, it needs to be written somewhere outside of the application. Databases are really good for that sort of thing. You could also write to a simple text file (a string of text, structured XML, etc.) though in that case you'll have to manually watch out for concurrent writes and other such errors. (Databases are really good at that too, which makes them ideally suited for multi-thread/multi-user applications like web apps.)
I suppose you could treat the PHP file itself as an editable text file like any other. (Since PHP is, after all, just text.) But, again, that's a really bad idea. For one thing, parsing out exactly the value you want and writing back a change only to that value is going to be very difficult. Also, you run the risk of breaking a file which is treated as executable code which opens up all sorts of potential risks.
Just write to a database, or to a file, or to any other simple data persistence medium outside of the application.
Your fileb is lacking the <?php ... ?> tags. Without those, you "code" is never seen as code. it'll just be treated as plain text.
file b:
<?php
$power = 'on';
file c:
Hello
<?php
$foo = 'world!';
file a:
<?php
include('fileb.php');
echo $power;
include ('filec.php'); // "Hello" is immediately output
echo $foo; // tell PHP to put the $foo var, which will print out "world!"
The actual questions
How to "map" access restrictions so it can be used from php and javasript?
What kind of method should I use to share access restrictions / rules between php and javascript?
Explanation
I have created a RESTful backend using php which will use context-aware access control to limit data access and modification. For example, person can modify address information that belongs to him and can view (but not modify) address information of all other persons who are in the same groups. And of course, group admin can modify address details of all the persons in that group.
Now, php side is quite "simple" as that is all just a bunch of checks. Javascript side is also quite "simple" as that as well is just a bunch of checks. The real issue here is how to make those checks come from the same place?
Javascript uses checks to show/hide edit/save buttons.
PHP uses checks to make the actual changes.
and yes,
I know this would be much more simpler situation if I ran javascript (NodeJS or the like) on server, but the backend has already been made and changing ways at this point would cause major setbacks.
Maybe someone has already deviced a method to model access checks in "passive" way, then just use some sort of "compiler" to run the actual checks?
Edit:
Im case it helps to mention, the front-end (js) part is built with AngularJS...
Edit2
This is some pseudo-code to clarify what I think I am searching for, but am not at all certain that this is possible in large scale. On the plus side, all access restrictions would be in single place and easy to amend if needed. On the darkside, I would have to write AccessCheck and canAct functions in both languages, or come up with a way to JIT compile some pseudo code to javascript and php :)
AccessRestrictions = {
Address: {
View: [
OWNER, MEMBER_OF_OWNER_PRIMARY_GROUP
],
Edit: [
OWNER, ADMIN_OF_OWNER_PRIMARY_GROUP
]
}
}
AccessCheck = {
OWNER: function(Owner) {
return Session.Person.Id == Owner.Id;
},
MEMBER_OF_OWNER_PRIMARY_GROUP: function(Owner) {
return Session.Person.inGroup(Owner.PrimaryGroup)
}
}
canAct('Owner', 'Address', 'View') {
var result;
AccessRestrictions.Address.View.map(function(role) {
return AccessCheck[role](Owner);
});
}
First things first.
You can't "run JavaScript on the server" because Javascript is always run on the client, at the same way PHP is always run on the server and never on the client.
Next, here's my idea.
Define a small library of functions you need to perform the checks. This can be as simple as a single function that returns a boolean or whatever format for your permissions. Make sure that the returned value is meaningful for both PHP and Javascript (this means, return JSON strings more often than not)
In your main PHP scripts, include the library when you need to check permissions and use the function(s) you defined to determine if the user is allowed.
Your front-end is the one that requires the most updates: when you need to determine user's permission, fire an AJAX request to your server (you may need to write a new script similar to #2 to handle AJAX requests if your current script isn't flexible enough) which will simply reuse your permissions library. Since the return values are in a format that's easily readable to JavaScript, when you get the response you'll be able to check what to show to the user
There are some solutions to this problem. I assume you store session variables, like the name of the authorized user in the PHP's session. Let's assume all you need to share is the $authenticated_user variable. I assume i'ts just a string, but it can also be an array with permissions etc.
If the $authenticated_user is known before loading the AngularJS app you may prepare a small PHP file whish mimics a JS file like this:
config.js.php:
<?php
session_start();
$authenticated_user = $_SESSION['authenticated_user'];
echo "var authenticated_user = '$authenticated_user';";
?>
If you include it in the header of your application it will tell you who is logged in on the server side. The client side will just see this JS code:
var authenticated_user = 'johndoe';
You may also load this file with ajax, or even better JSONP if you wrap it in a function:
<?php
session_start();
$authenticated_user = $_SESSION['authenticated_user'];
echo <<<EOD;
function set_authenticated_user() {
window.authenticated_user = '$authenticated_user';
}
EOD;
?>
From what I understand using something like require_once will essentially copy and paste the code from one file into another, as if it was in the first file originally.
Meaning if I was to do something like this it would be valid
foo.php
<?php
require_once("bar.php");
?>
bar.php
<?php
print "Hello World!"
?>
running php foo.php will just output "Hello World!"
Now my question is, if I include require_once inside a method, will the file that is included be loaded when the script is loaded, or only when the method is called?.
And if it is only when the method is called, is there any benefit performance wise. Or would it be the same as if I had kept all the code into one big file.
I'm mainly asking as I've created an API file, which handles a large amount of calls, and I wan't to simplify the file. (I know I can do this just be creating separate classes, but I thought this would be good to know)
(Sorry if this has already been asked, I wasn't sure what to search for)
It will only include when the method is called, but have you looked at autoloading?
1) Only when the method is called.
2) I would imagine there's an intangible benefit to loading on the fly so the PHP interpreter doesn't have to parse extra code if it's not being used.
I usually use the include('bar.php'); i use it for when i use databvase information, i have a file called database.php with login info and when the file loads it calls it right up. I don't need to call up the function. It may not be the most effective and efficient but it works for me. You can also use include_once... include basically does what you want it to, it copies the code essencially..
As others have mentioned, yes, it's included just-in-time.
However, watch out for variable definitions (require()ing from a method will only allow access to local variables in that method's scope).
Keep in mind you can also return values (i.e. strings) from the included file, as well as buffer output with ob_start() etc.
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 ...
I render a page using YUI. and depending on the user I need to change how it is rendered. This change is not something that can be parametrized, it is drastic and different for each user.
Please tell me how can I generate Javascript dynamically?
I personally use a PHP file to pass a JavaScript object made up of some basic session and internal settings, nothing mission-critical as passing information to the client isn't overly secure, but I believe it might follow the same principles as what you are looking for.
Similarly, I use this to display certain elements once the client is logged in, although all the authorization is still done on the server-side. If my session handler gives the PHP file the ok, it outputs a JavaScript object using a PHP heredoc string, otherwise, it doesn't output anything. You can use attributes of this object to compare against, or you could output only the JavaScript for how a certain page should be rendered, based on settings in your PHP file.
HTML:
<script src="common/javascript/php_feeder.php" type="text/javascript"></script>
PHP:
//my session handler authorisation check has been removed
//although you could place your own up here.
//assuming session was authorised
//set content type header
header("content-type: application/x-javascript");
$js_object = <<<EOT
var my_object = {
my_attr: '{$my_attr}',
my_attr2: '{$my_arrt2}',
etc: '{$etc}'
}
EOT;
print($js_object);
You can probably create two separate Java script files, and include the required file, depending upon the user type.
Pseudocode
If user_type is One
<Script src='one.js' type='javascript'></script>
else
<Script src='other.js' type='javascript'></script>
End If
JavaScript has an eval function, so I think (I haven't tried it) that you can generate JavaScript by writing it into a string variable (and then calling eval on that string variable).
A little bit of elaboration here would most certainly help in getting you a more descript and helpful answer. That in mind, though, you could easily just use functions declared inside an if statement to provide distinctly varied experiences for different users.
A very basic example:
<script>
function do_something(userType)
{
if (userType == 'A')
{
// everything you need to do for userType A
}
if (userType == 'B')
{
// everything you need to do for userType B
}
}
</script>