Hide PHP Variables in URL with url rewrite - php

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.

Related

Set session variable on <a> click

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.

loop through $POST to make $SESSION equivalent

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.

Hide ?ref string in URL but pass it to script

How can I hide ?ref string from users but pass it to php code so it will grab it?
For example, visitor visits this page:
http://mysite.com/?ref=ref+string
In browser URL I want to hide it, so user will see"
http://mysite.com/
But I want to grab content of ref string via this:
$ref = $_GET['ref'];
Is it possible?
No, if you want to use GET variables, they will always be in the url.
However, you can use an alternative, like $_SESSION or $_POST variables.
You could try something like this at the top of your PHP script:
session_start();
if (isset($_GET['ref'])) {
$_SESSION['ref'] = $_GET['ref'];
header('Location: /');
exit();
}
You would have to use $_SESSION['ref'] to access the value from then on, however.
This is not how the http protocol works with query strings. If you have information that needs to be in the query string that you want to hide or obfuscate from the user, I would recommend a simple encryption to change it. If you're attempting to get rid of this information for aesthetic reasons, you will need to pursue a different method of generating the header or storing the information (session/cookies/etc).

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']
}

Editing and creating things with address bar code?

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!

Categories