I have a functions file where I handle POST and GETS letting the user perform either a post or a get. It's more like an API call.
Should I be doing it like this or would using $_REQUEST handle both a POST and a GET?
if ($_SERVER['REQUEST_METHOD'] === "GET") {
$function = $_GET['f'];
$user_id = $_GET['user_id'];
}
elseif ($_SERVER['REQUEST_METHOD'] === "POST") {
$function = $_POST['f'];
$user_id = $_POST['user_id'];
}
$res = new stdClass();
if (isset($function)) {
switch ($function) {
....
}
}
The benefit that your current approach offers it that you can use the best method for each instance. There are some times when you would not want to GET since it just appends the data to the URL, exposing it to anyone who looks as well as exposing that "call" to anyone who knows how to use URLs for bad things.
If you are worried about catching calls that you not not be able to controll the request method, you could add the $_REQUEST as a last resort but I would suggest limiting what you use that for - example: just pulling data from the DB and not anything that modifies it.
If you want to allow both, you can just use $_REQUEST. It's much easier if you don't care whether the value was POSTed or -er- GETted. Note, though, that $_REQUEST may contain cookies as well, based on settings in PHP.ini.
$_REQUEST can be both $_POST and $_GET, but it can also be $_COOKIE as well, depending on the request_order or variables_order settings. Because it can also be neither of these depending on an ini setting, I wouldn't use it at all.
My recommendation is use $_GET and $_POST separately. They mean completely different things. You want to use a $_POST for an action, and a $_GET for fetching. If you want form filling based on $_GET you can use $_SERVER['REQUEST_METHOD'] == 'POST' to determine what is actually happening and toggle between the two.
$_REQUEST is the most convenient way to handle the both type of request ($_GET & $_POST). So use the $_REQUEST :
REQUEST METHOD IN PHP
Yes you can, $_REQUEST handles both $_POST and $_GET.
Related
The variables in $_REQUEST are provided to the script via the GET, POST, and COOKIE input mechanisms.
Is there a way in code igniter to access GET and POST both data through one predefined variable or function
You can use
$this->input->post_get('some_data', TRUE);
This will work like $_REQUEST.More function are there like cookie,server.
For more information check here
I use global variables on my website such GET,POST,FILES,SESSION. I wrote my website on a server where register_globals is on. And i just moved my website to another server where register_globals is off and i actually do not know how to deal with it.
For exmaple, i have this code:
$do = $_GET['do'];
or
$name = $_POST['name'];
How i understood, i can not do this, php can't extract this data. How can i change my code to receive data from GET,POST,SESSION,FILES?
Thank you
You misunderstand. $_GET & co are superglobals which are always available and cannot be disabled, your code will always work.
register_globals makes those $_GET values directly available as variables. I.e. instead of $_GET['do'] you could use $do.
This is the proper way to access the vars and works with register_globals_gpc = off:
$do = $_GET['do'];
If register_globals_gpc = on the $_GET would automatically be extracted and this would work:
echo $do;
So if you are doing it the way you show then all is well. $_GET, $_POST, $_COOKIE, as well as $_SERVER and $_SESSION are already superglobal and available anywhere.
The quick and easy way would be using extract function.
extract($_POST);
extract($_GET);
extract($_COOKIES);
But this is VERY VERY VERY BAD from security and maintainablity aspect! You should rewrite the code, if possible, to:
$variable = $_POST['variable'];
..
when I googled this issue and open the very first serch result it gave me the solution. Try this, Hope it will work for you
Would this be the correct way to loop through the $POST data sent by an API and have a equivalent $SESSION name/value pair be created from it?
foreach($_POST as $key=>$value)
{ $_SESSION['$key']=$value; }
UPDATE: First, thanks for the solid responses - I think I need to explain the problem I'm trying to overcome and why this functionality is being considered. The $_POST response is coming from a payment processor gateway - the problem is that since the payment form/processing is not on our domain the results of the payment (approved/declined etc. etc.) is being RELAYED to our server via $POST - When our PHP code tries to process the response data it looks for various PHP structures (Like php include 'file.php') under there domain instead of ours and errors out - I need to move the $POST data into a session and then move the person back to our domain so that the file/directory/resource tree is correct. Does this make sense what im encountering?
Don't use single quotes:
foreach ($_POST as $key => $value) {
$_SESSION[$key] = $value;
}
I'd encourage you to read about Strings in PHP.
Note: This is potentially unsafe for several reasons - mostly injection by key collision. Consider if I posted the logged in user id.
This could be mitigated through encapsulation:
$_SESSION['posted_data'] = $_POST;
Don't you rather want to keep them separated?
$_SESSION['response'] = $_POST;
If you really want to do it as you state, you could use something like
$_SESSION=array_merge($_SESSION,$_POST);
which would work but be a "bad thing" - plenty of scope to overwrite items already in the $_SESSION variable:
index.php:
<form action="2.php" method="post">
<input type="text" name="hidden" value="hidden">
<button type="submit">Click</button>
</form>
2.php:
<?php
session_start();
session_unset();
$_SESSION['hidden']="existing";
$_SESSION=array_merge($_SESSION,$_POST);
echo '<pre>'.print_r($_SESSION,true).'</pre>';
Better would be to use
$_SESSION['POST']=$_POST;
Obviously, perform any data checks you need to before doing this though
Ignoring the security issues this could cause depending on how you use it, what you could do is use:
$_SESSION = array_merge($_POST, $_SESSION);
This will only bring in POST vars which have a key not already found in $_SESSION. Switch them around if you want the POST vars to take precedence of course.
Just a quick note on security, if like a lot of people you use the session to store user id, what would happen if i sent a POST request to your script with userid=1?
All im saying is, be careful what you are doing with this. You'd be better off if possible doing as suggested and using a unique key in $_SESSION for post vars such as $_SESSION['post_vars'] = $_POST (or maybe ['form_data'] if you're using it to persist form data, which is usually why people do this).
You could also use the array union operator:
$_SESSION = $_POST + $_SESSION;
This takes the values of $_POST and adds those values of $_SESSION whose keys are not already present in $_POST.
Since the POST is made by a payment gateway, the session will be associated with it (and most likely be lost at first request, since it can be assumed that it won't ever bother reading the session cookie).
Your client won't ever see this data in their session.
If you want to have this data available, you need to persist it somehow, if the payment gateway gives you exploitable client information. Possible solution are a database, key/value store...
Alternatively, it is common that the payment gateway will allow you to specify a link to redirect the client's browser to after the purchase. Getting the parameters from the POST, you could append them to the redirect URL to pass them back to your website as GET parameters.
Which of these code will be faster?
$temp = $_REQUEST['s'];
or
if (isset($_GET['s'])) {
$temp = $_GET['s'];
}
else {
$temp = $_POST['s'];
}
$_REQUEST, by default, contains the contents of $_GET, $_POST and $_COOKIE.
But it's only a default, which depends on variables_order ; and not sure you want to work with cookies.
If I had to choose, I would probably not use $_REQUEST, and I would choose $_GET or $_POST -- depending on what my application should do (i.e. one or the other, but not both) : generally speaking :
You should use $_GET when someone is requesting data from your application.
And you should use $_POST when someone is pushing (inserting or updating ; or deleting) data to your application.
Either way, there will not be much of a difference about performances : the difference will be negligible, compared to what the rest of your script will do.
GET vs. POST
1) Both GET and POST create an array (e.g. array( key => value, key2 => value2, key3 => value3, ...)). This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.
2) Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.
3) $_GET is an array of variables passed to the current script via the URL parameters.
4) $_POST is an array of variables passed to the current script via the HTTP POST method.
When to use GET?
Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.
GET may be used for sending non-sensitive data.
Note: GET should NEVER be used for sending passwords or other sensitive information!
When to use POST?
Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send.
Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to bookmark the page.
$_GET retrieves variables from the querystring, or your URL.>
$_POST retrieves variables from a POST method, such as (generally) forms.
$_REQUEST is a merging of $_GET and $_POST where $_POST overrides $_GET. Good to use $_REQUEST on self refrential forms for validations.
I'd suggest using $_POST and $_GET explicitly.
Using $_REQUEST should be unnecessary with proper site design anyway, and it comes with some downsides like leaving you open to easier CSRF/XSS attacks and other silliness that comes from storing data in the URL.
The speed difference should be minimal either way.
Use REQUEST. Nobody cares about the speed of such a simple operation, and it's much cleaner code.
Don't worry. But you should still use the second solution (plus an extra check for none of those variables existing), because there are security issues with $_REQUEST (since $_GET and $_POST aren't the only sources for that array).
There was a post about the problems with $_REQUEST yesterday, I believe. Let me go find it.
EDIT: Oh well, not directly a post, but here it is anyway: http://kuza55.blogspot.com/2006/03/request-variable-fixation.html
if (isset($_GET['s'])) {
$temp = $_GET['s'];
}
else {
$temp = $_POST['s'];
}
Use that because it is safer and it won't make noticeable speed difference
$_GET retrieves variables from the querystring, or your URL.>
$_POST retrieves variables from a POST method, such as (generally) forms.
$_REQUEST is a merging of $_GET and $_POST where $_POST overrides $_GET. Good to use $_REQUEST on self refrential forms for validations.
There are certain security concerns involved as a hacker can set a cookie that will override a $_POST or $_GET value. If you handle sensitive data, I would not recommend using $_REQUEST. – Xandor
you can't be used $_GET alternative of $_POST on some case.
When ??
when you want to upload a file.
when you don't won't to show a data in url.
GET also has limits on the amount of information to send. The limitation is about 2000 characters.
Other thing's there are few case when you can't retrieve a data using $_POST
When ?
when data is passed in URL.
For Rest Service
`GET` - Provides a read only access to a resource.
`PUT` - Used to create a new resource.
there is nothing be wrong to use $_REQUEST.
But the way to do that is to check $_SERVER['REQUEST_METHOD'] explicitly, not rely on $_POST being empty for a GET.
I would use the second method as it is more explicit. Otherwise you don't know where the variables are coming from.
Why do you need to check both GET and POST anyway? Surely using one or the other only makes more sense.
I only ever use _GET or _POST. I prefer to have control.
What I don't like about either code fragment in the OP is that they discard the information on which HTTP method was used. And that information is important for input sanitization.
For example, if a script accepts data from a form that's going to be entered into the DB then the form had better use POST (use GET only for idempotent actions). But if the script receives the input data via the GET method then it should (normally) be rejected. For me, such a situation might warrant writing a security violation to the error log since it's a sign somebody is trying something on.
With either code fragment in the OP, this sanitization wouldn't be possible.
I would use $_POST, and $_GET because differently from $_REQUEST their content is not influenced by variables_order.
When to use $_POST and $_GET depends on what kind of operation is being executed. An operation that changes the data handled from the server should be done through a POST request, while the other operations should be done through a GET request. To make an example, an operation that deletes a user account should not be directly executed after the user click on a link, while viewing an image can be done through a link.
I use this,
$request = (count($_REQUEST) > 1)?$_REQUEST:$_GET;
the statement validates if $_REQUEST has more than one parameter (the first parameter in $_REQUEST will be the request uri which can be used when needed,
some PHP packages wont return $_GET so check if its more than 1 go for $_GET, By default, it will be $_POST.
You are prematurely optimizing. Also, you should really put some thought into whether GET should be used for stuff you're POST-ing, for security reasons.
It's ugly and I wouldn't recommended it as a final solution when pushing code live, but while building rest functions, it's sometimes handy to have a 'catch-all' parameter grabber:
public static function parseParams() {
$params = array();
switch($_SERVER['REQUEST_METHOD']) {
case "PUT":
case "DELETE":
parse_str(file_get_contents('php://input'), $params);
$GLOBALS["_{$_SERVER['REQUEST_METHOD']}"] = $params;
break;
case "GET":
$params = $_GET;
break;
case "POST":
$params = $_POST;
break;
default:
$params = $_REQUEST;
break;
}
return $params;
}
Someone creative could probably even add to it to handle command line parameters or whatever comes from your IDE. Once you decide what a given rest-function is doing, you can pick one appropriate for that given call to make sure you get what you need for the deploy version.
This assumes 'REQUEST_METHOD' is set.
How do I make it so that I can make a thing at the end of the address where the .php is and then tell it to do certain things. For example pull up a page like this:
sampardee.com/index.php?page=whatever
Help?
Anything else I could do with this?
This is generally achieved with the global php array $_GET. You can use it as an associative array to 'get' whatever variable you name in the url. For example your url above:
//this gives the $page variable the value 'whatever'
$page = $_GET['page'];
if($page == 'whatever'){
//do whatever
}
elseif($page == 'somethingelse'){
//do something else
}
Check out the php documentation for more information:
$_GET documentation
and there's a tutorial here:
Tutorial using QUERY_STRING and _GET
A small improvement over Brett's code:
if (array_key_exists('page', $_GET) === false)
{
$_GET['page'] = 'defaultPage';
}
$page = $_GET['page'];
// ... Brett Bender's code here
$_GET is usually used if you are sending the information to another page using the URL.
$_POST is usually used if you are sending the information from a form.
If you ever need to write your code so that it can accept information sent using both methods, you can use $_REQUEST. Make sure you check what information is being sent though, especially if you are using it with a database.
From your question it looks like you are using this to display different content on the page?
Perhaps you want to use something like a switch to allow only certain page names to be used?
i.e.
$pageName=$_REQUEST['page'];
switch($pageName){
case 'home':$include='home.php';break;
case 'about':$include='about.php';break;
case default:$include='error.php';break;
}
include($include);
This is a really simplified example, but unless the $page variable is either home or about, the website will display an error page.
Hope it helps!
I'm not quite sure what you're asking, but I think you're asking how to use GET requests.
Make GET requests against any PHP page as follows:
www.mysite.com/page.php?key1=value1&key2=value2
Now, from within PHP, you'll be able to see key1 -> value1, key2 -> value2.
Access the GET hash from within PHP as follows:
$myVal1 = $_GET['key1'] #resolves to "value1"
$myVal2 = $_GET['key2'] #resolves to "value2"
From here, play with your GET variables as you see fit.
The system of adding page parameters to a URL is know as HTTP GET (as distinct from HTTP POST, and some others less commonly used).
Take a look at this W3 schools page about GET in PHP and ahve a play about in getting parameters and using them in your PHP code.
Have fun!