What is the CF OnRequest scope called in other languages? - php

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

Related

Inner document data replace with NodeJS

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

how to determine failure in ajax request

I'm working with Mootools to develop a simple ajax-y page that does some manipulation with db records using PHP as the backend.
I'm submitting the ajax request to a PHP page that calls a function and returns TRUE or FALSE if the record was able to be updated/deleted or not.
However, it seems like the mootools onSuccess event is fired anytime the server returns a 200 status, regardless of the value returned (eg. FALSE is still assumed to be a success).
How do I use onSuccess in a meaningful way, short of returning a 40x error code or something?
All answers given by #dombenoit and #Marc are technically correct.
However, I totally differ from #Marc's vision: to me, using HTTP status codes is both efficient and common for webservices. I use them all the times and much favor them over outputting text, mainly for the following reasons:
they give a free standard for handling incorrect values, instead of making you output text and parsing it clientside, meaning semantical repetition;
they make all tools understand something went wrong, as the question itself outlines;
they feel right in a REST architecture.
To support this vision, here's a question: what's the goal of your call? Is it to update or delete a record? Then if this goal is not reached, something went wrong. It failed, and the application should know it at application-level, not through first saying 200/OK and then precising in the textual response it did not! To me, it feels like using "undefined" instead of undefined.
So, here, I would make PHP send an HTTP error status code, that is one in the 4xx-5xx ranges.
Then, the good question is: which code to use? This is a design decision that totally depends on your application and the degree of specificity you want to get to.
If the goal of the call is to update / delete, and the fact that it does not happen is extremely unlikely and is an unexpected, serious error (for example: the DB is inconsistent because there's no way the call could reference an entity that does not exist), then you should use 500 / Internal Server Error.
If it could be possible that the targeted entity does not exist at the time of the call without it being a critical error (example: your app provides several ways to delete an item, so another one could have been used instead of this call), then I'd advise 410 / Gone: you get a clear, expressive error handling, for free! And you can still use 500 for actual errors (DB connexion exceptions…).
Then, you could get even more specific about update errors only, for example with 409 / Conflict if that's the kind of errors you're trying to foresee with updates…
I always give a look at the HTTP status codes reference when I'm designing a webapp.
Just for the sake of completion, that's how you send headers in PHP (without framework at least — check for specificities):
header("HTTP/1.0 404 Not Found");
UPDATE: since it seems you decided to go with the answer that suggested to use JSON to encode success or failure, I have to add the following points about resilience.
Not relying on status codes and only on application-level data makes your code very fragile. Indeed, there are situations where you get actually unexpected errors. Not the application-level “exception” that you raised yourself, but something wrong on a lower level (server unavailable, bad config that makes the server crash, changed routing system…). These will all show through HTTP status codes (or through timeout), but not through a JSON-encoded answer, since your application will have already crashed before being able to output anything.
Like #Dimitar put it, from a programming point of view, this is somehow “naive”: you trust not only your code (you shouldn't), but also the environment (server) and the network. That's a very, very optimistic vision.
Using status codes as the standard way to handle expected exceptional situations give you a free handling of those unexpected situations: you've already registered other handlers than onSuccess, and supposedly good ones (retrying once, notifying the user, offering backup possibilities…).
Personaly, I feel that using the HTTP status codes to indicate the success/failure of whatever was supposed to happen on the server is incorrect. Everything about the HTTP call itself worked perfectly - the fact that the server was unable to complete the request doesn't mean the HTTP request failed.
It's like driving to the store to buy something, only to find it's out of stock. Returning an HTTP 404, to me, would imply that the store itself was gone. Yet, you've successfully driven to the store, walked inside, walked back out, drove home.
So, use a JSON data structure to indicate the results of the requested transaction, which you can check for in your client-side code:
$results = array()
$results['success'] = false;
$results['failure_code'] = XXX; // some code meaningful to your app
$results['failure_message'] = 'Something dun gone blowed up, pa!';
echo json_encode($results);
Then in your Moo code:
if (!results['success']) {
alert("AJAX call failed: " + results['failure_message']);
}
If the call worked, then you'd have
$results = array();
$results['success'] = true;
$results['data'] = ....;
You have a couple options, two of which you mentionned in your question. You can use onSuccess and execute some code based on a true/false response, like so :
onSuccess: function(responseText, xml){
if(responseText == "false"){
// do something...
}
}
Or you could raise errors in your PHP code, returning an actual valid error code thus firing the onFailure event.
Or as mentionned by Marc previously, you could use a JSON response format, in which case you would use MooTools' Request.JSON.
onSuccess: function(responseJSON, responseText){
// do something...
}

jQuery posting variables within the same file

I have some variables set in Javascript. Further down the script I want to use these values in PHP. I realise I need to POST/GET them with jQuery, but I don't understand either function fully, even after looking at the manuals.
Could somebody break it down and explain the parameters?
Would I be better off using GET or POST in the instance?
Can the URL specified be the same as the current page e.g. index.php?
Thanks very much for your help.
You can not do this unless PHP is writing the javascript. PHP is on the server side and will be parsed before Javascript is ever seen by the client. Any variables set by JS will NOT be seen by PHP on the same request.
It's really just a question of style, really.
GET places all key/value-pairs in the URL field, whereas POST puts it in the HTTP body. Since URLs are limited in length, POST is preferred for longer, larger sets of data or data needing to benefit from TLS/SSL encryption.
So let's say we have a key: articleID. You want to pass 1 to articleID, so that the backend can contact the database and retrieve the article in question.
If you make a GET request, you'd invoke the following URL:
index.php?articleID=1
If you use POST, you'll put the data in the request body itself, so you wouldn't be able to tell what value you sent to the server without opening the packet in question and examining the request.
You'll find more information on how to perform these requests back at jQuery's reference site. More information about GET and POST.
You are the architect of the application, so you would know best what method to use. As for contacting the view itself, it's certainly possible albeit questionable from an architectural point of view.

Passing variable over to a new HTTP Request

As the title says, is there another way to pass a variable from "current" page over to "next" (new HTTP request) page without using sessions/cookies/$_GET?
Well, I guess $_POST could be an option too, but the thing here is, that I want to pass this variable from already executed $_POST back to off-the-post environment page, but inbetween I'm having a redirect, to disallow reposting the same form.
In other words, basicly, I'm trying to "make" a seamless PRG, but sessions/cookies/$_GET is not an option.
And yes, I'm working with classes (hence the oop tag). Therefore maybe some kind of magic functions, or output control?
This has to work within PHP environment, no JavaScript or other non server side language.
I also have a bad feeling that it's impossible, but hopefully I'm wrong, and there is a solution.
Thanks in advance!
update no. 1
Basicly, I want to create a PRG with response.
Inside this $_POST I'm adding data to database. I want this response to hold information whether this database query has been successful or not. Kind of make this $_POST process almost invisible to the user. And yes, display a response with the result later on.
All of this happens in one method:
if($_POST){
// insertion
}else{
// display no-post environment, if response exists (therefore posted) display response too
}
Something like that...
Sessions is not an option because this is meant to be some kind of API.
update no. 2
Huh, let me rephrase the question a little. Well, it seems that I don't actually need to pass the variable over. What I want to do, is to have 2 different results after POST so on next page load I could know whether the actions in POST has been successful or not. So, what other options are out there without using sessions/cookies/$_GET to get this result?
Currently there is:
temporary database usage: a good option, but I'd like to see different options;
Since you're already using a database it seems like the easiest way to handle this would be to update some kind of temporary table with the information you want based on the post call, then on the page you're doing a header redirect to, read the information in that table. With the constraints you've placed on this (no GET, SESSION, Cookie or Javascript) you're not going to be able to maintain a variable when you redirect from one page to the next.
So leverage that database and take the work off of PHP. Initially I was going to suggest utilizing cURL but I don't think that will help here (though you may want to look it up if you're unfamiliar with it, as it might be what you're looking for)
HTTP is a stateless protocol; thus, there's not going to be an easy, built-in way to add state. That said, I think sessions are the best way to accomplish what you want to do. If what you're doing isn't in the browser, maybe try some sort of session key setup (like the Facebook platform uses).

Alternative to header(location: ) php

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.

Categories