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.
Related
I want to be able to test a website I am building using PHP that gets all its content from a database that uses point in time. I have a series of pages that I use to maintain the content and assign effective dates.
The live website will not have access to a session.
I simply want to hack the URL with a parameter like so:
mywebsite.com/current.php?asof=2016-01-01
But I want this parameter to appear on all subsequent pages.
I could use cookies I guess but I want the visual cue.
Finally, some of the pages I navigate to will have additional parameters.
Can this be done? If so, how?
EDIT:
Is there a way to edit the response by injecting URL parameters for any arbitrary response.
If navigation is done only via links and forms, and you have no session, you could try injecting the params into all links and forms before rendering the html.
// set the asof value once upon starting navigation
$_GET['asof'] = '2016-01-01';
// then on all pages onward
// grab all links and inject all $_GET params
$html = preg_replace('/(href="[^"]+)"/', '$1?'.http_build_query($_GET).'"', $html);
// the same for forms
$html = preg_replace('/(action="[^"]+)"/', '$1?'.http_build_query($_GET).'"', $html);
echo $html;
This gets all the data passed in the query string ($_GET) and injects it into all links and forms. So every click on a link will propagate the $_GET params. Keep in mind that this is a rough implementation. This doesn't take into account links that already have query strings or pasting the url.
Set your cookie and then for every link you can do something like the following:
<?php
$asof = (isset($_COOKIE['asof']) ? 'asof=' . $_COOKIE['asof'] : '');
?>
link
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.
I have a form that submits to the same page. Now when it gets submitted and after it's processed I need it to have a unique query string.
So for example the user inputs some info then clicks submit, then the page saves the info on the server then the server spits it back out with a unique query string for that info.
If I try to set $_SERVER['QUERY_STRING'] it just hangs. Is there another way to do this?
Is it possible with a redirect?
EDIT, I'm going from mysite.com/ and the form action is on mysite.com/ and I want the browser to go to mysite.com/?blah
OK I tried putting this on my the top of my page with no luck
<?php
if ($_POST['data']) header('location: /?' . idFromDifferentFunction() );
?>
but it just keeps loading, I'm guessing it just redirects itself to death.
I hope you now understand what I'm trying to do
Chances are that your script is continuing to run after the code that says it should redirect. You also need to be more precise with the header:
<?php
if (isset($_POST['data'])) {
header('Location: /?' . idFromDifferentFunction() );
exit;
}
?>
If you use the code above, it will make the script exit which dumps the output and the browser will see the redirect (note the capital L in Location).
The key point is the exit following the redirect header. Without it, PHP is very likely going to continue working on whatever other code you're doing in the script.
It's not entirely clear what you're after, but I think you mean you want to go to a page with a unique value in the query string (the bit after the ?) once the processing is complete. Does this unique value need to actually reference something in the system (for a newly-created DB entry does it need to reference the ID of the new entry) or does it just have to be unique?
If it's the latter, you could just generate a random unique ID do the following:
header ('location: /path/to/script?id=' . uniqid ());
If it's the former, then replace the call to uniqid with the value of the database key.
The values in $_SERVER are set at runtime by PHP and should be considered read-only. Changing their values will have no meaningful effect.
$_SERVER['QUERY_STRING'] is part of PHP's globals. You should not be setting those variables, instead set it via a session and return it after submission.
If you are trying to redirect the user to a specific URL then use:
header('Location: mysite.com/bla/bla');
Writing to $_SERVER is pointless. It doesn't affect the client browsers in any way. If you want to change the query string displayed in the client browser, you'll have to use a 301/302 redirect using a header('Location: ...') call.
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']
}
e.g. i have page with url http://mysite.com?page=3&var=10 also there is form on page.
When form submitted there some actions in php but i need to remove this ?page=3&var=10 after form was submitted somehow is there way compatible with all browsers trough PHP without mod_rewrite?
This is an old topic, but just in case anyone else is searching for this in the future, you can use the javascript replaceState to change the history and browser bar label. A simple php function to do this:
function set_url( $url )
{
echo("<script>history.replaceState({},'','$url');</script>");
}
Then would simply call this function with the desired url (presumably dropping the post variables):
set_url("http://example.com");
A page reload or a back after calling another page will now have the new url location in the history.
I think that using POST may be a more elegant solution, but if you must use GET this is a work around.
If you're using action=index.php, then all values will be posted to index php, ?page=3&var=10 will be automatically removed.
If you want to post to the same page you can either use 'action=index.php?page=3&var=10' or action=<?php echo $_SERVER['PHP_SELF'] ?>
You can check at the beginning of the page if something submitted and then redirect to whatever you want with header('Location: http://www.example.com/'); More about header function http://php.net/manual/en/function.header.php
Yeah, the solution is quite simple (even if not really SEO friendly):
<?php
header("Location: http://mysite.com")
?>
just for information...why do you need it?
use parse_str to get the query string as an associative array that is easy to modify. Then use http_build_query to convert the associative array into a query string.
$queryString = $s['QUERY_STRING'];
$params = array();
parse_str($queryString, $params);
//change $params as needed
$queryString = http_build_query($params);
if ($queryString) {
$queryString = '?'.$queryString;
}
return preg_replace("/\\?.*/s","",$s['REQUEST_URI']).$queryString;
preg_replace("/\\?.*/s","",$s['REQUEST_URI']) removes the original query string allowing you to replace it.
Does this work for you?
header('Location:/');
mod_rewrite cannot affect what's displayed in the user's browser address bar, UNLESS the rewrite does an externally visible redirect. Otherwise it only rewriting things within the webserver, and that's invisible to the user.
If you want to affect the user's address bar, you'll have to do a redirect via header('Location: ...') after the form's finished processing.