loop through $POST to make $SESSION equivalent - php

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.

Related

Hide PHP Variables in URL with url rewrite

I am working on a site that has to deal with reservation numbers and I need to pass variables to confirmation page. Currently when you arrive at confirmation.php the URL looks something like the below:
http://localhost/confirmation.php?reservation_id=1&proceed=no
These variables are sent via a link to this page from the index page. I need a way to either encrypt the $reservation_id OR rewrite my URL so it looks like this
http://localhost/confirmation.php
...but still have access to my variables. I have tried sessions and some encryption methods, but cant find anything that wont over complicate the page as I am trying to keep it as simple as possible. Forms with hidden fields is not an option, I am printing all the reservations in links with a loop from the database.
Thanks!
Use session variables. Create a random session variable name, and assign the reservation information to it:
foreach ($reservations as $r) {
$random = make_random_string(); // You need to write this function
$_SESSION[$random] = $r;
echo "<a href='reservation.php?id=$random'>...</a>";
}
Then reservation.php can look up $_SESSION[$_GET['id']] to get the reservation information.
It sounds like you need to start a session and pass the data in there. Or, you could POST the data instead (Use a form). But the session is probably the better choice.

Can you carry on a $_POST variable? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP Pass variable to next page
Here is my current code:
$search = $_POST['s'];
$search = strtoupper($search);
$search = strip_tags($search);
$search = trim($search);
$search = mysql_real_escape_string($search);
I need to be able to carry on the $search variable to my second, third, etc, pages.
I'm a beginner in php and i'm sort of stuck here
It would appear that sessions are your friend here. In the simplest form, sessions will just put data in cookies that are sent to and from the user's browser. Make sure you call session_start() before you do anything with the session, this will start or resume the user's sessions. After that, you can use $_SESSION as a global associative array that will persist between pages.
Xander has already linked you to the docs, Here are some simple examples. Make sure you understand session_start() otherwise you'll have some bugs.
N.B. Do not use this basic session format for sensitive data. Look into using something like memcache to store the data and simply put the memcache key into $_SESSION. Also, consider encrypting the sessions. Those are more advanced things you should think about when dealing with user authentication/login
Assuming it is a search string, there is only sane method:
First, change the form's method to GET
Next, just pass your search variable in the query string using GET method.
The only modification you have to apply is urlencode()
So, the code should be
$query_string = 'search='.urlencode($_GET['search']);
echo "<a href='?page=2&$query_string'>page 2</a>";
producing an HTML code
page 2
so a user can click this link and you will have your search string back
While $_SESSION has been suggested, another option is to use a hidden field (with the same name and filled with the appropriate value) on subsequent generated pages. Then, when those pages are posted back, they too will have the field available in $_POSTS (this time supplied by the hidden field, not the original text field).
Advantages:
"Bound to the current page"; really good for some page context-sensitive stuff! (The session is scoped to the browser, not the page.)
Avoids the need for session/cookies (which is a non-issue if the session is already required for other purposes).
Disadvantages:
"Bound to the current page": value will be lost when navigated away from outside of back/next context. (As Bert notes, a slight modification can use this "breadcrumb" approach to alter the URL and use GET parameters, which can make the data universally persistent, at the expense of a "less pretty" URL.)
Data must be treated as untrusted and insecure, just like the original post.
Requires population of additional [hidden] fields.
Happy coding.
Use session_start() in each of the pages you want to access the search varaible
in the first page
$search = $_POST['s'];
$search = strtoupper($search);
$search = strip_tags($search);
$search = trim($search);
$search = mysql_real_escape_string($search);
set a session variable as
$_SESSION['searchStr']=$search
then in everyother page
session_start(); // at the very begining
if(isset($_SESSION['searchStr'])) {
$search=$_SESSION['searchStr']
}

Unassigning a variables value from $_GET

I use;
$referrer = $_GET['_url'];
If I echo $referrer; it will display correctly.
If I use $referrer within a $_POST, it is empty. I think due to $referrer being assigned to $_GET.
How can I extract the value of $referrer into another variable so it is no longer assigned to the $_GET?
I hope that makes sense..
$_POST will only contain data IF you send that from form.
So, your code is basically right. Because you use referrer from within your URL.
If you really want to have $referer from $_POST, you will have to code something like this:
<form method="post" action="somewhere.php">
<input type="hidden" name="_url" value="{place the referrer here}" />
</form>
Or, like #Michael Gillette answer, you can change that with $_REQUEST.
hope that makes sense..
sorry, but it doesn't :)
$referrer become distinct variable with no relation to $_GET['_url']. It already contains value extracted from $_GET
there are not a single reason for $_GET sourced variables to conflict with $_POST.
Your problem is somewhere else.
It seems you're just trying to access variable that doesn't exist. Because every variable dies along with whole PHP after it's execution.
PHP scripts execution is atomic. It's not like a desktop application constantly running in your browser, and not even a demon with persistent connection to your desktop application. It's more like a command line utility - doing it's job and exits. It runs discrete:
a browser makes a call
PHP wakes up, creates an HTML page, sends it to the browser and dies
Browser renders that HTML and shows it to the user.
User clicks a link
a browser makes a call
another PHP instance, knowing nothing of the previous call, wakes up and so on
So, if you set your $referrer in one instance and trying to access it in another, it will fail. You have to re-sent it's value with next call
Use the clone keyword, as seen in the examples in this article:
http://php.net/manual/en/language.references.php
could you post an example of what you might like to do?
$referrer = $_REQUEST['_url'];
will return true on both GET and POST requests

PHP - Pass POST variables with header()?

I'm trying to use the header() function to create a redirect. I would like to display an error message. Currently I'm sending the message as a parameter through the URL, however this makes it look quite ugly.
Is there a way to pass this value as a post variable instead?
Any advice appreciated.
Thanks.
Dan, You could start and store a session in PHP then save the message as a session variable. This saves you from having to transfer the message in an HTTP request.
Manipulating Sessions
//Start the session
session_start();
//Dump your POST variables
$_SESSION['POST'] = $_POST;
//Redirect the user to the next page
header("Location: bar.php");
Now, within bar.php you can access those POST variables by re-initiating the session.
//Start the session
session_start();
//Access your POST variables
$temp = $_SESSION['POST'];
//Unset the useless session variable
unset($_SESSION['POST']);
To read more about sessions, check out: http://php.net/manual/en/function.session-start.php
The header function is used to send HTTP response headers back to the user so actually you cannot use it to create request headers :(
One possibility is to use the CURL but I don't think it is worth of what you are doing.
Provided that you have local access to the page displaying the error, instead of redirecting you could include it in the page which caused the error and then programmatically display the error message.
if(something_went_wrong()) {
require_once('errors.php');
display_error('something really went wrong.');
}
The errors.php file would then contain a definition for display_error($message), which displays the formatted message.
When passing variables between modules I have found it easier to construct an array from the variables, convert the array to json and store it in a db table with two columns, a varchar key and a text data. The json would go in data and the key could be anything you want. Then in the target module you just read that back, convert the json back to an array and voila, you have your variables. No $_POST, no $_SESSION, no fuss, no muss, quick and easy. Of course that assumes you have access to a database, although you could use a file on the server. $_POST is useless since it needs a and $_SESSION can be cranky and can lead to unexpected results. Otherwise you'd almost have to use ajax.

Among $_REQUEST, $_GET and $_POST which one is the fastest?

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.

Categories