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']
}
Related
I'm trying to make an <a> link which triggers PHP code on the next page. I've tried using $_GET variables to do this but the thing is I also want to remove the variable afterwards, as I automatically link back to the redirected page with header(). There don't seem to be any feasible ways to do this without redirecting the user to one page alone, but the thing is they're expected to be redirected to the page they were on previously. Keeping $_GET variables then cause an endless loop of redirects.
In general, I wish to avoid using $_GET as it could be abused in the context I'm using it in. Any other workarounds would be greatly appreciated, though. Basically I'm just trying to use an <a> link to remove an entry from a MySQL database.
Here's the PHP that handles the variable.
if (isset($_GET['rm'])) # 'rm' contains the uuid of the entry to be deleted.
{
$uuid = $_GET['rm'];
unset($_GET['rm']); # Didn't expect this to work, of course it didn't remove the variable from the URL.
$query = "DELETE FROM posts WHERE uuid = '$uuid'";
$result = $mysqli->query($query);
header("Location: " . $_SERVER['REQUEST_URI']);
exit();
}
EDIT: I realize now that I have wildly complicated my explanation here. The main goal was to make the click of an <a> link trigger PHP code, with a variable specific to the link clicked. (Each link is a delete button on a post, and each post has a UUID)
If there is a way to alternatively trigger javascript code, that would be immensely helpful as well, since I'm looking to use such a method here too. I will likely be making a separate thread asking about this.
You can use $_SESSION to delete the variable after for example
if (isset($_SESSION['rm'])) # 'rm' contains the uuid of the entry to be deleted.
{
$uuid = $_SESSION['rm'];
unset($_SESSION['rm']); # Didn't expect this to work, of course it didn't remove the variable from the URL.
$query = "DELETE FROM posts WHERE uuid = '$uuid'";
$result = $mysqli->query($query);
header("Location: " . $_SERVER['REQUEST_URI']);
exit();
}
consider that you have register the value of the next shape.
$_SESSION['rm'] = "My value";
If your goal is to redirect to the current page but remove the query string, you can redirect to header("Location: ?"); which is essentially just that. (Technically you are redirecting to a new query string with no value which is different than no query string at all but php will just show an empty array for $_GET which is essentially the same)
I was going to mention additional options like variables from $_SERVER, but many of those have various security or other issues associated with them. I only mention this because I wouldn't suggest using any unless necessary. Also, it really doesn't get easier than the above.
Currently I put a constant on my webpage using PHP which I then send, with Ajax, to my POST function. However, this leaves it susceptible to hacking (the user could change the variable with Firebug), so is there a way to store the variable in the PHP of the page and then access it later on, in the POST method (or is the GET variable of the page still available in the POST function, since that's where I get the variable from)?
I think what you have wanted is to store the post value to use it later.
Here you would need to use $_SESSION
You can do it like
session_start();
// Save variables into session
$_SESSION['thevalue'] = $_POST['value'];
If you wish to store between successive calls from the same user use the follwing:
<?php
session_start();
$_SESSION["your variable/constant"] = yourvaule;
Now use the variable as needed, accessing it as $_SESSION["your variable/constant"]
Hope it helps, and it's what you're asking.
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.
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.
how to secure your passing variables between the two pages via url? Let's assume i have a TEST variable in one page and i want to pass on that variable to test2.php page in the secure method?
How to convert test variable into Hash Method and pass on test2.php page via url?
for example
$test=$_POST['test'];
echo $row['test'];
Test
OR
Test
test2 Page
$test=$_REQUEST['test'];
By secure if you mean that you want the variable to be visible but you want to prevent users from changing the variable you can simply pass a hash along with the variable.
I.e.
$variable = 'abc';
$salt = 'your secret key';
$hash = md5($salt.$variable);
Page 2
On the second page you can rehash to see if the value has changed or not.
$variable = $_REQUEST['variable'];
$salt = 'your secret key';
$hash = md5($salt.$variable);
if($hash == $_REQUEST['hash']){
//do staff
}
However this will not hide the variables from URL, you can use other suggested answers for that.
It's not secure at all, because URLs (incl. GET arguments) are usually stored in httpd logs. So use POST for this, use SSL for transmission. If you need to use GET you can try to encrypt your data but mind that some web browsers got limits on max length of URL used, so too much data in GET may make them confused
Secure hash functions are one way, so no good for passing values. The most secure way to do this would be to use SSL, and POST your variables so they aren't displayed in the querystring/address bar.
Use SSL (for encrypted traffic - see here) and POST (see here).
The answer is simple.
either you need that variable in the url to identify the particular page and it's content
or it's internal site variable, like authorization information - it have to be passed via session.
For the first case you shouldn't "secure" this variable at all.