I want to make some game in PHP that involves scripting. For obvious reasons I don't want players/users to use PHP that I just include or eval. So I decided to go with LUA.
But I've never experimented with LUA in PHP. So my questions are:
Is allowing user LUA script in (out of the box) PHP a secure solution?
If not, then can I (and how to) make it secure?
What I aim for:
User writes some code with some generic root function, let's say main()
PHP code calls that function and evaluates the results
LUA code should be able to call a select few methods on certain object. For example from class Enemy::isNear() or Enemy::getHP()
LUA code should not be able to call other methods/access other objects/call any global php functions/access any insecure OS stuff
Again, I only scratched LUA very long time ago for, where a game in C allowed for LUA mods. No experience with LUA in PHP at all.
If you are talking about this, the source code indicates it is just creating standard lua instance as with C embedding. It does not seem to define much of the lua-to-host interface whatsoever, so, lua code does not have direct access to the php state.
To have user call Enemy::isNear() you'll have to first put Enemy in the lua state first. It seems that it is capable of semi-intelligently convert php objects to lua tables (lua.c line 386), I'm not sure if method fields will transfer well. At worst you'll need to do implement object wrapping on your own (write a lua "class" whose constructor takes a php object and slaps a metatable on it). There seems to be a way of passing php functions to lua.
Lua should not have access to any php stuff you didn't put in. There are still dangerous lua functions: require, dofile, load, loadstring, loadfile and libraries os and debug in the lua's environment.
You can always check what is available to a lua function by putting in snippet like this:
for k in pairs(_ENV) do print(k) end
Just to be sure you might throw in this line as well:
if not (_G==_ENV) then for k in pairs(_G) do print(k) end end
From this point onwards proceed with lua manual on scoping and other discussions on sandboxing lua (e.g. this. Google finds other results as well). You might also read up on lua closures so that you don't accidentally stove undesirable methods in upvalues.
Finally, there are endless loops in the code while true do end. In case your sandbox does not take care of that (which is likely), you'll have to handle that externally. Probably like this.
Related
I am working with action script 3 and often I see server calls that link to php files.
var serverCall:ServerCall = new ServerCall("getDeviceFirmwareLog", getDeviceFirmwareLogResponse, getDeviceFirmwareLogResponse, false);
This line calls some php functions that cannot be searched in my IDE, so I usually go from here and I would try to grep for that string "getDeviceFirmwareLog" and then I run into some php that makes other weird calls that somehow calls some stuff on the embedded hardware we run. In general when I grep for that string I don't even get any results and I'm so confused as to how it might be connected.
I am much more used to regular code calls and includes that are easier to follow. I've asked some people at work but it seems to get glossed over and I don't want to ask the same question a third time until I've exhausted my other options. I am wondering if there are any general debugging / code following tips for this kind of a setup that could help me understand what is going on in my codebase.
Thanks in advance.
Without intimate knowledge of your environment, I'd say it appears ServerCall is a custom socket class that calls external functions, with n number of arguments.
getDeviceFirmwareLog would therefore be the function being called, and would be a native function to the API of the hardware (not PHP); this is why you wouldn't be able to find it with a grep search.
Consequently, unless it's rigged with event listeners, ServerCall would populate with the requested data asynchronously (which would likely still fire an event when the request completed).
As you're working with both Flash and PHP, it appears as though you might be testing this through a browser. If so, you could always try the native debugging tools in your browser (F12).
The PHP portion is harder as it's server side scripting, however, take a look at the Eclipse Plugin PDT, which offers debugging facilities for PHP code.
I can't build hhvm at the moment for lack of access to a 64-bit VM, so I haven't been able to use the typechecker that they have. Their documentation doesn't seem to describe the operation of the typechecker (hh_server and hh_client?) in any detail.
What I'm wondering, for anyone who's used it, is if the typechecker could be used in this situation:
Let's say someone can't convert their PHP codebase to Hack, so they instead write their PHP with comments in the form of hacklang type annotations, and at build time use a tool to strip the comments out, make a hh file, run the typechecker and report errors.
E.g. original PHP:
<?php
function lar(/* int */ $x)/* : int */
{
return $x;
}
Make a copy of the above, strip out comments, change ?php to ?hh :
<?hh
function lar(int $x): int
{
return $x;
}
Run it through the typechecker and see if it produces errors.
That way you'd get access to legitimate type checking with normal PHP without the need for running it on HHVM. Does the typechecker run in a way amenable to this set up?
I am an engineer at Facebook who works on Hack. You definitely could do this and I wouldn't say it's a bad thing to do, but you'd be missing out on a bunch of great features. The Hack typechecker can be run at build time (hh_server --check /path/to/www), but the best way to run the typechecker is as a daemon. Since the daemon incrementally checks your code in the background, it can report the errors very quickly whenever asked. This allows you to get feedback while you are writing your code rather than after you have finished. This quick feedback loop really helps speed up development.
Some other things that you would be missing out on:
Many language features, like Collections, lambda expressions, runtime enforcement of type annotations, and trailing commas (Paul Tarjan's personal favorite)
HHVM's massive performance boost.
So if you absolutely can't use HHVM then this might be worth considering, but if you can then I strongly recommend HHVM in order to reap the full benefits of Hack.
This is exactly what we did in-house in our development division.
We made a script to convert code between hacklang and php as we wanted to be able to do the type checking without converting our production servers to hhvm (we are planing to do so)
You can find the script on my github page
https://gist.github.com/Chipcius/d3dd4052b07a152870bd#file-hacklang-php-juggler-php
You can convert you files by passing in a directory and a flag to decide the conversion level (decl, partial, strict)
After conversion you can run hh_client just as you were coding hacklang
When you want to turn back you can run the same script on your code with the php flag and it comments out the annotations that need commenting.
workflow example
php hacklang-php-juggler.php <myDir> hack
hh_client
php hacklang-php-juggler.php <myDir> php
I was wondering, I have a few functions in PHP that're not called every time but still are included in my files on each load. Does it still run the code even if your not calling the function at that time? The reason I'm asking, the codes in my function are expensive to run CPU wise and I don't call them every time and want to make sure if there not called they do not run the code within the function.
Thank you
In short, a function that isn't explicitly called does not run. However, here is a short what and why we use functions that I found.
A function is a "black box" that we've locked part of our program
into. The idea behind a function is that it compartmentalizes part of
the program, and in particular, that the code within the function has
some useful properties:
It performs some well-defined task, which will be useful to other
parts of the program.
It might be useful to other programs as well; that is, we might be
able to reuse it (and without having to rewrite it).
The rest of the program doesn't have to know the details of how the
function is implemented. This can make the rest of the program
easier to think about.
The function performs its task well. It may be written to do a
little more than is required by the first program that calls it,
with the anticipation that the calling program (or some other
program) may later need the extra functionality or improved
performance. (It's important that a finished function do its job
well, otherwise there might be a reluctance to call it, and it
therefore might not achieve the goal of reusability.)
By placing the code to perform the useful task into a function, and
simply calling the function in the other parts of the program where
the task must be performed, the rest of the program becomes clearer:
rather than having some large, complicated, difficult-to-understand
piece of code repeated wherever the task is being performed, we have
a single simple function call, and the name of the function reminds
us which task is being performed.
Since the rest of the program doesn't have to know the details of
how the function is implemented, the rest of the program doesn't
care if the function is reimplemented later, in some different way
(as long as it continues to perform its same task, of course!). This
means that one part of the program can be rewritten, to improve
performance or add a new feature (or simply to fix a bug), without
having to rewrite the rest of the program.
Functions are probably the most important weapon in our battle against
software complexity. You'll want to learn when it's appropriate to
break processing out into functions (and also when it's not), and how
to set up function interfaces to best achieve the qualities mentioned
above: reuseability, information hiding, clarity, and maintainability.
http://www.eskimo.com/~scs/cclass/notes/sx5.html
Im coding in php and taking part in a coding competition which gives points to scripts on the basis of memory usage, running time, and ofcourse accuracy of algorighm.
I got the algo right and working for all test cases. But I got a little less marks than I expected.
To save lines of code, I used strpos() function in a loop.
when I changed strpos() function to manually finding string function that I made, my points increased...
Now I'm confused... I guess I can make more points if I use my own defined functions instead of all library functions I used (strlen,strpos,etc) ...
Does making our own defined functions in scripts help in making the code faster ?
I'm not a professional but have worked in php for 3-4 years and never thought of saving time/memory before :P so I'm kinda stuck over here...
In general, the built-in functions for basic things like string operations tend to be faster than anything you could code yourself.
According to TuxRadar, built-in PHP functions use
highly optimised C code that is likely
to be as fast as it can get.
so it's "never better to rewrite a built-in function using PHP".
Part of the performance issue of writing functions in PHP is that PHP code usually isn't compiled before running, it's interpreted. I think I read online somewhere a while back that some Facebook engineers actually wrote a PHP compiler or something though...but I could be wrong, I don't quite remember off the top of my head.
I am first and foremost a perl coder, but like many, also code in PHP for client work, especially web apps.
I am finding that I am duplicating a lot of my projects in the two languages, but using different paradigms (e.g. for handling cgi input and session data) or functions.
What I would like to do is start to code my Perl in a way which is structured more like PHP, so that I
a) am keeping one paradigm in my head
b) can more quickly port over scripts from one to the other
Specifically, I am asking if people could advise how you might do the following in perl?
1) Reproduce the functionality of $_SESSION, $_GET etc.
e.g. by wrapping up the param() method of CGI.pm, a session library?
2) Templating library that is similar to PHP
I am used to mixing my code and HTML in the PHP convention. e.g.
<h1>HTML Code here</h1>
<?
print "Hello World\b";
?>
Can anybody advise on which perl templating engine (and possibly configuration) will allow me to code similarly?
3) PHP function library
Anybody know of a library for perl which reproduces a lot of the php built-in functions?
Have a look at EmbPerl.
It's a Perl based templating system, which seems to provide anything that PHP does based on my admittedly very small knowledge of PHP.
To cover your specific points:
$_GET : EmbPerl provides %fdat hash which contains full set of form data passed via either POST or GET
%fdat makes no distinction of whether the value originated in GET's query string or form field via POST).
If you absolutely MUST have only the values from GET's QUERY_STRING, here's a simple example of a function to get it: http://urlgreyhot.com/personal/resources/embperl_getting_values_query_string - although why would you want to separate GET from POST data is escaping me at the moment.
$_SESSION : I'm not 100% I get what this does in PHP but if I'm right, there's %udat for per-user data and %mdat for per-module/page data for handling session stuff.
Using both is described in more detail in "Session Handling" area of EmbPerl docs, along with all the other multitude of session support in EmbPerl
Here's a quick %udat blurb:
... as soon as you write anything to %udat, Embperl creates a session id and sends it via a cookie to the browser. The data you have written to %udat is stored by Apache::Session. The next time the same user request an Embperl page, the browser sends the cookie with the session id back and Embperl fills the %udat hash from Apache::Session with the same values as you have stored for that user.
The templating code you included would look like this in EmbPerl:
<h1>HTML Code here</h1>
[-
print OUT "Hello World!";
-]
Or for a more idiomatic/correct solution,
<h1>HTML Code here</h1>
[+ "Hello World!" +]
P.S. I have no clue what "\b" does in PHP so I didn't clone that.
Embperl supports all the standard templating stuff ([- -] for execution, [+ +] for inclusion of results of arbitrary Perl code, template flow control commands ([$ if $]/'[$ for $]` etc...) and much more. It's also fully compatible with mod_perl.
2) If you literally want your script to be the template as in PHP, there is the Markup::Perl module (which grew out of another project that was actually called PerlHP). There are other modules like HTML::Mason for what Perl programmers think of as templating engines.
3) On CPAN I found PHP::Strings and PHP::DateTime, but I haven't used them and otherwise can't vouch for them.
You should also check out mod_perlite, it's an Apache module trying to emulate the mod_php behaviour for Perl, although development on it seems to have been stalled. More info from the README.
I was going to tell you to love Perl and PHP for their unique selves, but no. 1 strikes me as a bit of idle fun. My advice is to code it yourself, and post it to CPAN. I read your question and thought:
use CGI::PHPLike qw(:superglobals); # Pull in everything from CGI::PHPLike::Vars
CGI::PHPLike::Config->variables_order 'EGPCS';
...
%_ENV is probably just an alias for perl's %ENV. %_REQUEST and %_SESSION are probably tied objects, etc. Heck, %_SESSION may even be backed by PHP::Session::Serializer::PHP.
Read the CGI spec, and check out the source of CGI.pm, of course, but also simpler modules like CGI::Lite.