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
Related
I've been fortunate enough to be a CF dev for pretty much my entire IT career without having to take on using another development language so I have a knowledge hole I'd like to ask others to help me with.
I've built an API and I want to describe to others how to invoke it. It needs to be invoked first thing during a request before any generated content is sent back to the user. One of the possible outcomes of the API call is that the incoming user request could be aborted so that there's no error message but also no generated content. Just a blank screen. Sending back the blank screen with no generated page code is critical.
I can tell someone using CF that it needs to be called at the beginning of the Request scope or OnRequest scope but I'm at a loss as to how to get across the same arrangement for someone using other languages/frameworks like PHP, ASP.NET, Node.js, Wordpress, etc.
So, for example, for a CF based site I'd say something like: "The synchronous API call needs to be made early in the Request or OnRequest scope and BEFORE any generated page content is returned to the user". What I'm looking for is how to describe that same thing but for users of those other languages/frameworks.
Odd question but Google has been zero help (or perhaps I just don't know how to search for something like this). Any advice/guidance would be most appreciated.
Thanks in advance!
Is not the answer to your question simply to tell them "It needs to be invoked first thing during a request before any generated content is sent back to the user" (I copy and pasted that from your question).
That's it. That is absolutely clear.
That's all you need to do.
Don't worry about how they need to do that in their language of choice, esp given the very nature of your question, you won't know how. It's their job to write the code to consume your API. Not yours.
At most you could give them some usage pseudo-code along the lines of:
// at the beginning of the response handler
apiResult = apiObj.makeRequest(args, here)
if (apiResult.youCanComeIn == false) {
// handle it with a 403 or something appropriate
// stop
}
// they're allowed in, so rest of processing here
Obviously, any API request must return a specific response. And probably you need to pass the expected value and the value of a certain error at the level of your API. Further, any developer will understand what information to issue when receiving some error from the API response.
You probably mean something like: "request processing is required on the server side, in case of an error, generate an empty page on the client side", etc.
It's hard to recommend anything. Maybe server-side rendering, SSR
User A has some PHP library files. User B needs access to the library. Is it possible permission-wise to make user B able to include the PHP file but not able to view the source code?
User A library entry file is lib.php.
User B uses lib.php in his start.php like this:
include path/to/lib.php;
However user B won't be able to view the content of lib.php or any other class files thereof.
Is this possible?
You're trying to find a way to do something that can't be done properly. Maybe in a kind of hackish, definitely dirty way.
You really should consider writing an API for your Application that contains all your logic. Then you could just handle everything else with User permission and so on, perfectly clean and state of the art.
Nobody but the API devs can look into the code, but everyone can use it based on his user permissions.
Every other method could is just to hard to handle and will cause more problems than just writing an API. It's worth the time.
Basically what you ask is not possible. The PHP interpreter needs to be able to read the file in order to include it, and if the PHP process can read it then your untrusted user can write some code that would read it in and dump it back out.
A few options you have are:
1) Use an API. Would allow you to keep you code secret as you'd only expose the API. Might take a few days work to implement though (or might not even be possible - impossible to say without knowing what you are doing), so probably not suitable in your situation.
2) Obsfucate your code. There are a number of PHP code obsfucators out there. It wouldn't stop prying eyes completely but it might be enough for your purposes.
3) Create a stub include file. If what your library includes isn't all critical to the running of the code you could create a cut-down stub library for your client to code against, then replace it with the real thing when they've done.
I am trying to trace the flow of execution in some legacy code. We have a report being accessed with
http://site.com/?nq=showreport&action=view
This is the puzzle:
in index.php there is no $_GET['nq'] or $_GET['action'] (and no
$_REQUEST either),
index.php, or any sources it includes, do not include showreport.php,
in .htaccess there is no url-rewriting
yet, showreport.php gets executed.
I have access to cPanel (but no apache config file) on the server and this is live code I cannot take any liberty with.
What could be making this happen? Where should I look?
Update
Funny thing - sent the client a link to this question in a status update to keep him in the loop; minutes latter all access was revoked and client informed me that the project is cancelled. I believe I have taken enough care not to leave any traces to where the code actually is ...
I am relieved this has been taken off me now, but I am also itching to know what it was!
Thank you everybody for your time and help.
There are "a hundreds" ways to parse a URL - in various layers (system, httpd server, CGI script). So it's not possible to answer your question specifically with the information you have got provided.
You leave a quite distinct hint "legacy code". I assume what you mean is, you don't want to fully read the code, understand it even that much to locate the piece of the application in question that is parsing that parameter.
It would be good however if you leave some hints "how legacy" that code is: Age, PHP version targeted etc. This can help.
It was not always that $_GET was used to access these values (same is true for $_REQUEST, they are cousins).
Let's take a look in the PHP 3 manual Mirror:
HTTP_GET_VARS
An associative array of variables passed to the current script via the HTTP GET method.
Is the script making use of this array probably? That's just a guess, this was a valid method to access these parameter for quite some time.
Anyway, this must not be what you search for. There was this often misunderstood and mis-used (literally abused) feature called register globals PHP Manual in PHP. So you might just be searching for $nq.
Next to that, there's always the request uri and apache / environment / cgi variables. See the link to the PHP 3 manual above it lists many of those. Compare this with the current manual to get a broad understanding.
In any case, you might have grep or a multi file search available (Eclipse has a nice build in one if you need to inspect legacy code inside some IDE).
So in the end of the day you might just look for a string like nq, 'nq', "nq" or $nq. Then check what this search brings up. String based search is a good entry into a codebase you don't know at all.
I’d install xdebug and use its function trace to look piece by piece what it is doing.
EDIT:
Okay, just an idea, but... Maybe your application is some kind of include hell like application I’m sometimes forced to mess at work? One file includes another, it includes another and that includes original file again... So maybe your index file includes some file that eventually causes this file to get included?
Another EDIT:
Or, sometimes application devs didn’t know what is a $_GET variable and parsed the urls themselves -> doing manual includes based to based urls.
I don't know how it works, but I know that Wordpress/Silverstipe is using is own url-rewriting to parse url to find posts/tags/etc. So the url parsing maybe done in a PHP script.
Check your config files (php.ini and .htaccess), you may have auto_prepend_file set.
check your crontab, [sorry I don't know where you would find it in cpanel]
- does the script fire at a specific time or can you see it definitely fires only when you request a specific page?
-sean
EDIT:
If crontab is out, take a look at index.php [and it's includes] and look for code that either loops over the url parameters without specifically noting "nq" and anything that might be parsing the query string [probably something like: $_SERVER['QUERY_STRING'] ]
-sean
You should give debug_backtrace() (or debug_print_backtrace() a try. The output is similar to the output of an Exception-stacktrace, thus it should help you to find out, what is called when and from where. If you don't have the possibility to run the application on a local development system, make sure, that nobody else can see the output
Are you sure that you are looking at the right config or server? If you go the url above you get an error page that seems to indicate that the server is actually a microsoft iis server and not an apache one.
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.
I have a while loop that constructs a url for an SMS api.
This loop will eventually be sending hundreds of messages, thus being hundreds of urls.
How would i go about doing this?
I know you can use header(location: ) to chnage the location of the browser, but this sint going to work, as the php page needs to remain running
Hope this is clear
thankyouphp h
You have a few options:
file_get_contents as Trevor noted
curl_ - Use the curl library of commands to make the request
fsock* - Handle the connection a bit lower level, but making and managing the socket connection.
All will probably work just fine and you should pick one depending on your overall needs.
After you construct each $url, use file_get_contents($url)
If it just a case that during the construction of all these URLs you get the error "Maximum Execution Time Exceeded", then just add set_time_limit(10); after the URL generation to give your script an extra 10 seconds to generate the next URL.
I'm not quite sure what you are actually asking in this question - do you want the user to visit the urls (if so, can you does the end users web browser support javascript?), just be shown the urls, for the urls to be generated and stored or for the PHP script to fetch each url (and do you care about the user seeing the result) - but if you clarify the question, the community may be able to provide you with a perfect answer!
Applying a huge amount guesswork, I infer from your post that you need to dynamically create a URL, and the invoking of that URL causes an SMS message to be sent.
If this is the case, then you should not be trying to invoke the URL from the client but from server side using the url_wrappers or cURL.
You should also consider running the loop in a seperate process and reporting back to the browser using (e.g.) AJAX.
Have a google for spawning long running processes in PHP - but be warned there is a lot of bad advice on the topic published out there.
C.