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.
Related
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.
So, I'm am fairly new to NodeJS and any programming in general, and I'm not sure if I'm going about this correctly. I've been practicing things like this since I was 9 or 10 (currently 13). So before I delved into NodeJS anymore, I wanted to make sure I'm using it correctly.
So, after working with PHP for some time. You can simply "echo" something in the document to return data from the server, such as an IP address.
<?php
echo $_SERVER["REMOTE_ADDR"];
?>
This would effectively echo the user's IP wherever the bit of PHP is located in the document - parsed by Apache's module (right?)
What is the con of this? Is there any way to re-create NodeJS syntax with-in a document which is then parsed by the NodeJS HTTP server to get any NodeJS between, lets say <nodejs>script</nodejs>.
So, in shorter, more understandable terms.
Is it technically safe to take NodeJS out of a document before it's displayed - eval that Nodejs script, then remove it and display it.
Although this sounds kinda sketchy. So I'm currently using an alternative method. But I'm not sure if this would technically be safe either.
Right now, in the document, I would have something like <p>Your IP is [*IP*]</p>, which I use NodeJS's file system module to do something like this:
app.get("/", function(req, res){
res.send(fs.readFileSync(__dirname + "index.html").replace(/\[\*IP\*\]/g, req.connection.remoteAddress));
});
Although, this just seems a little iffy to me. And since I haven't got a lot of experience on the security aspect of web development, I was hoping I could get some insite on how this is safe or unsafe.
How would I accomplish this?
Thanks for taking the time to read and help me improve my knowledge on this subject!
I don't think it's a question of security or something like that, but a question of how Node.js works compared to PHP.
PHP is basically, as you wrote correctly, file based. So you create a text file with the extension .php, put your HTML markup and maybe some logic (like printing the ip address) in it and that's it. The rest is done by the web server, mainly Apache, which sends each request to a .php-file through "the PHP engine" which interprets your code and renders the result to the client (which in your case is your browser).
Node.js does not work that way. Instead of looking for a file which is then interpreted and returned, the most common (not the only) way is to use a "middleware" which is processing the request.
First it looks after an "endpoint" for each request. Broadly speaking you can register a function for each route, as you did in your example code for the route "/" (could also be ("/what-is-my-ip").
That function is your "controller action" which could perform some business logic, as fetching the ip address.
After finishing that, it passes the result to a view engine or simply returns a simple view trough that engine.
A view is basically what your .php would be, but it does not contain any logic, which is the main difference to PHP.
It's mainly working after the Model View Controller pattern.
Some view engines:
Handlebars: https://www.npmjs.org/package/express-handlebars
Jade: https://www.npmjs.org/package/jade
Vash: https://www.npmjs.org/package/vash
EJS: https://www.npmjs.org/package/ejs
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?
After doing a lot of reading on the subject, I realized that many developers mix javascript and php in the same file (by adding the .php extension or using other ways).
On the other hand, if I choose to separate the javascript from the php and store it in an external cacheable static file, I gain some performance advantage, but I also need to find creative ways to pass server-side data to the javascript.
For example, since I can't use a php foreach loop in the .js file I need to convert php arrays to json objects using json_encode. In other cases, I need to declare gloabl javascript variables in the original php file so I can use them in the external js file.
Since server side processing is considered faster than javascript, converting to js arrays and using global vars may also be a bad idea...
The bottom line is I'm trying to understand the trade off here. Which has more impact on performance, enable caching of js files or keeping a cleaner code by avoiding global js variables and multidemnsional js arrays?
are you talking about performance of the server or the browser?
my personal opinion is that given the choice between making a server slower or making a browser slower, you should always choose to let the browser be slower.
usually, "slow" means something like "takes 100ms" or so, which is not noticeable on an individual browser, but if you have a few hundred requests to a server and they're all delayed by that, the effect is cumulative, and the response becomes sluggish. very noticeable.
let the browser take the hit.
I think it depends on what your trying to do. My personal opinion is that it's a little bit of a pain to prevent your dynamic JavaScript from being cached.
Your static JS files need to contain your functions and no dynamic data. Your HTML page can contain your dynamic data. Either within a SCRIPT block (where you will be able to use PHP foreach), or by putting your data into the DOM where the JavaScript can read it, it can be visible (in a table) or invisible (e.g. in a comment) - depends on whether your data is presentable or not.
You could also use AJAX to fetch your dynamic data, but this will be an additional request, just like an external JS file containing the data would.
As Kae says, adding additional load onto the client would benefit your server in terms of scalability (how many users you can serve at any one time).
Data:
If the amount of dynamic data isn't too big and constantly changing (must not be cached by the browser), I would suggest adding it to the head of the HTML. To prevent it from polluting the global namespace, you can use either a closure or a namespace (object), to contain all related variables. Performance-wise, I don't think that in this case, there would be much difference between looping the data into JS-friendly format or handling it to the finest detail on the server (JS has become amazingly fast).
Things are a bit more complicated when the amount of data is huge (100+kbs to megabytes). In case the data is pretty much constant and cacheable, you should generate a external data file (not an actual new file, but an unique URL), which you could then include. Using a timestamp in the name or correctly set cache headers would then enable you to save the time on both server-side (generating the JS-friendly output) and client-side (downloading data) and still offer up to date data.
If you have a lot of data, but it's constantly changing, I'd still use external JS files generated by PHP, but you have to be extra careful to disable browser caching, which make your constantly changing data pretty much constant. You could also do dynamic loading, where you pull different parts of data in parallel and on demand via JS requests.
Code:
The functional part of your code should follow the explanation from before:
Now to the question whether JS should be inlined to the HTML or separated. This depends highly on code, mostly of it's length and reusability. If it's just 20 lines of JS, 10 of which are arrays, etc that are generated by PHP, it would make more sense to leave the code inside the HTML, because HTTP requests (the way how all resources are delivered to the client) are expensive and requesting a small file isn't necessarily a great idea.
However, if you have a bit bigger file with lots of functionality etc (10s of kbs), it would be sensible to include it as a separate .js file in order to make it cacheable and save it from being downloaded every time.
And there's no difference in PHP or JS performance, whether you include the JS inside templates/PHP or separately. It's just a matter of making a project manageable. Whatever you do, you should seriously look into using templates.
After doing a lot of reading
That's what you are probably doing wrong.
There are many people fond on writing articles (and answers on Stackovervlow as well) who has a very little experience and whose knowledge is based... on the other articles they read!
Don't follow their bad example.
Instead of "a lot of reading" you have to do a lot of profiling!.
First of all you have to spot the bottlenecks and see if any of them are caching related.
Next thing you have to decide is what kind caching your system require.
And only then you can start looking for the solution.
Hope it helps.
QDF to your problem is to send the data in a hidden HTML table.
HTML tables are easy to generate in php and easy to ready in JavaScript.
I have a solution when the situation is passing info from php to js and keep most js outside the main php file.
Use the js objects or js functions.
You make some code that needs data from php. When the page loads some small js code is generated from php. Like:
<script type="text/javascript">
a(param1, param2, param3)
</script>
and it's done. The server indicates param1, param2 and param3 directly in the code.
The function is inside a .js file that is cached. With this you reduce the server's upload and the time for the page js to start. The client's code is a bit slower but you win for the time to download and the server becomes faster.
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!